text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { log } from "@ledgerhq/logs"; import type { Currency, Account } from "../types"; import { flattenAccounts, getAccountCurrency } from "../account/helpers"; import { promiseAllBatched } from "../promise"; import type { CounterValuesState, CounterValuesStateRaw, CountervaluesSettings, TrackingPair, RateMap, RateGranularity, PairRateMapCache, } from "./types"; import { pairId, magFromTo, formatPerGranularity, formatCounterValueDay, formatCounterValueHashes, parseFormattedDate, incrementPerGranularity, datapointLimits, } from "./helpers"; import { fetchHistorical, fetchLatest, isCountervalueEnabled, aliasPair, mapRate, resolveTrackingPair, } from "./modules"; // yield raw version of the countervalues state to be saved in a db export function exportCountervalues({ data, status, }: CounterValuesState): CounterValuesStateRaw { const out = { status, }; for (const path in data) { const obj = {}; for (const [k, v] of data[path]) { obj[k] = v; } out[path] = obj; } return <CounterValuesStateRaw>out; } // restore a countervalues state from the raw version export function importCountervalues( { status, ...rest }: CounterValuesStateRaw, settings: CountervaluesSettings ): CounterValuesState { const data = {}; for (const path in rest) { const obj = rest[path]; const map = new Map(); for (const k in obj) { map.set(k, obj[k]); } data[path] = map; } return { data, status, cache: Object.entries(data).reduce( (prev, [key, val]) => ({ ...prev, // $FlowFixMe [key]: generateCache(key, <RateMap>val, settings), }), {} ), }; } // infer the tracking pair from user accounts to know which pairs are concerned export function inferTrackingPairForAccounts( accounts: Account[], countervalue: Currency ): TrackingPair[] { const yearAgo = new Date(); yearAgo.setFullYear(yearAgo.getFullYear() - 1); return resolveTrackingPairs( flattenAccounts(accounts).map((a) => { const currency = getAccountCurrency(a); return { from: currency, to: countervalue, startDate: a.creationDate < yearAgo ? a.creationDate : yearAgo, }; }) ); } export const initialState: CounterValuesState = { data: {}, status: {}, cache: {}, }; const MAX_RETRY_DELAY = 7 * incrementPerGranularity.daily; // synchronize all countervalues incrementally (async update of the countervalues state) export async function loadCountervalues( state: CounterValuesState, settings: CountervaluesSettings ): Promise<CounterValuesState> { const data = { ...state.data }; const cache = { ...state.cache }; const status = { ...state.status }; const nowDate = new Date(); const latestToFetch = settings.trackingPairs; // determines what historical data need to be fetched const histoToFetch: any[] = []; const rateGranularities: RateGranularity[] = ["daily", "hourly"]; rateGranularities.forEach((granularity: RateGranularity) => { const format = formatPerGranularity[granularity]; const earliestHisto = format(nowDate); log("countervalues", "earliestHisto=" + earliestHisto); const limit = datapointLimits[granularity]; settings.trackingPairs.forEach(({ from, to, startDate }) => { const key = pairId({ from, to, }); const c: PairRateMapCache | null | undefined = cache[key]; const stats = c && c.stats; const s = status[key]; // when there are too much http failures, slow down the rate to be actually re-fetched if (s?.failures && s.timestamp) { const { failures, timestamp } = s; const secondsBetweenRetries = Math.min( Math.exp(failures * 0.5), MAX_RETRY_DELAY ); const nextTarget = timestamp + 1000 * secondsBetweenRetries; if (nowDate.valueOf() < nextTarget) { log( "countervalues", `${key}@${granularity} discarded: too much HTTP failures (${failures}) retry in ~${Math.round( (nextTarget - nowDate.valueOf()) / 1000 )}s` ); return; } } let start = startDate || nowDate; const limitDate = Date.now() - limit; if (limitDate && start.valueOf() < limitDate) { start = new Date(limitDate); } const needOlderReload = s && s.oldestDateRequested && start < new Date(s.oldestDateRequested); if (needOlderReload) { log( "countervalues", `${key}@${granularity} need older reload (${start.toISOString()} < ${String( s && s.oldestDateRequested )})` ); } if (!needOlderReload) { // we do not miss datapoints in the past so we can ask the only remaining part if ( stats && stats.earliestStableDate && stats.earliestStableDate > start ) { start = stats.earliestStableDate; } } // nothing to fetch for historical if (format(start) === earliestHisto) return; histoToFetch.push([ granularity, { from, to, startDate: start, }, key, ]); }); }); log( "countervalues", `${histoToFetch.length} historical value to fetch (${settings.trackingPairs.length} pairs)` ); // Fetch it all const [histo, latest] = await Promise.all([ promiseAllBatched(10, histoToFetch, ([granularity, pair, key]) => fetchHistorical(granularity, pair) .then((rates) => { // Update status infos const id = pairId(pair); let oldestDateRequested = status[id]?.oldestDateRequested; if (pair.startDate) { if ( !oldestDateRequested || pair.startDate < new Date(oldestDateRequested) ) { oldestDateRequested = pair.startDate.toISOString(); } } status[id] = { timestamp: Date.now(), oldestDateRequested, }; return { [key]: rates, }; }) .catch((e) => { // TODO work on the semantic of failure. // do we want to opt-in for the 404 cases and make other fails it all? // do we want to be resilient on individual pulling / keep error somewhere? const id = pairId(pair); // only on HTTP error, we count the failures (not network down case) if (e && typeof e.status === "number" && e.status) { const s = status[id]; status[id] = { timestamp: Date.now(), failures: (s?.failures || 0) + 1, oldestDateRequested: s?.oldestDateRequested, }; } log( "countervalues-error", `Failed to fetch ${granularity} history for ${pair.from.ticker}-${ pair.to.ticker } ${String(e)}` ); return null; }) ), fetchLatest(latestToFetch) .then((rates) => { const out = {}; let hasData = false; latestToFetch.forEach((pair, i) => { const key = pairId(pair); const latest = rates[i]; if (data[key]?.get("latest") === latest) return; out[key] = { latest: rates[i], }; hasData = true; }); if (!hasData) return null; return out; }) .catch((e) => { log( "countervalues-error", "Failed to fetch latest for " + latestToFetch .map((p) => `${p.from.ticker}-${p.to.ticker}`) .join(",") + " " + String(e) ); return null; }), ]); const updates: any[] = histo.concat(latest).filter(Boolean); log("countervalues", updates.length + " updates to apply"); const changesKeys = {}; updates.forEach((patch) => { Object.keys(patch).forEach((key) => { changesKeys[key] = 1; if (!data[key]) { data[key] = new Map(); } Object.entries(patch[key]).forEach(([k, v]) => { if (typeof v === "number") data[key].set(k, v); }); }); }); // synchronize the cache Object.keys(changesKeys).forEach((pair) => { cache[pair] = generateCache(pair, data[pair], settings); }); return { data, cache, status, }; } export function lenseRateMap( state: CounterValuesState, pair: { from: Currency; to: Currency; } ): PairRateMapCache | null | undefined { if (!isCountervalueEnabled(pair.from) || !isCountervalueEnabled(pair.to)) { return; } const rateId = pairId(pair); return state.cache[rateId]; } export function lenseRate( { stats, fallback, map }: PairRateMapCache, query: { from: Currency; to: Currency; date?: Date | null | undefined; } ): number | null | undefined { const { date } = query; if (!date) return map.get("latest"); const { iso, hour, day } = formatCounterValueHashes(date); if (stats.earliest && iso > stats.earliest) return map.get("latest"); return map.get(hour) || map.get(day) || fallback; } export function calculate( state: CounterValuesState, initialQuery: { value: number; from: Currency; to: Currency; disableRounding?: boolean; date?: Date | null | undefined; reverse?: boolean; } ): number | null | undefined { const { from, to } = aliasPair({ from: initialQuery.from, to: initialQuery.to, }); if (from === to) return initialQuery.value; const { date, value, disableRounding, reverse } = initialQuery; const query = { date, from, to, }; const map = lenseRateMap(state, query); if (!map) return; let rate = lenseRate(map, query); if (!rate) return; const mult = reverse ? magFromTo(initialQuery.to, initialQuery.from) : magFromTo(initialQuery.from, initialQuery.to); rate = mapRate(initialQuery, rate); if (reverse && rate) { rate = 1 / rate; } const val = rate ? value * rate * mult : 0; return disableRounding ? val : Math.round(val); } export function calculateMany( state: CounterValuesState, dataPoints: Array<{ value: number; date: Date | null | undefined; }>, initialQuery: { from: Currency; to: Currency; disableRounding?: boolean; reverse?: boolean; } ): Array<number | null | undefined> { const { reverse, disableRounding } = initialQuery; const query = aliasPair(initialQuery); const { from, to } = query; if (from === to) return dataPoints.map((d) => d.value); const map = lenseRateMap(state, query); if (!map) return Array(dataPoints.length).fill(undefined); // undefined array const mult = reverse ? magFromTo(initialQuery.to, initialQuery.from) : magFromTo(initialQuery.from, initialQuery.to); return dataPoints.map(({ value, date }) => { if (from === to) return value; let rate = lenseRate(map, { from, to, date, }); if (!rate) return; rate = mapRate(initialQuery, rate); if (reverse && rate) { rate = 1 / rate; } const val = rate ? value * rate * mult : 0; return disableRounding ? val : Math.round(val); }); } function generateCache( pair: string, rateMap: RateMap, settings: CountervaluesSettings ): PairRateMapCache { const map = new Map(rateMap); const sorted = Array.from(map.keys()) .sort() .filter((k) => k !== "latest"); const oldest = sorted[0]; const earliest = sorted[sorted.length - 1]; const oldestDate = oldest ? parseFormattedDate(oldest) : null; const earliestDate = earliest ? parseFormattedDate(earliest) : null; let earliestStableDate = earliestDate; let fallback; let hasHole = false; if (oldestDate && oldest) { // we find the most recent stable day and we set it in earliestStableDate // if autofillGaps is on, shifting daily gaps (hourly don't need to be shifted as it automatically fallback on a day rate) const now = Date.now(); const oldestTime = oldestDate.getTime(); let shiftingValue = map.get(oldest) || 0; if (settings.autofillGaps) { fallback = shiftingValue; } for (let t = oldestTime; t < now; t += incrementPerGranularity.daily) { const d = new Date(t); const k = formatCounterValueDay(d); if (!map.has(k)) { if (!hasHole) { hasHole = true; earliestStableDate = d; } if (settings.autofillGaps) { map.set(k, shiftingValue); } } else { if (settings.autofillGaps) { shiftingValue = map.get(k) || 0; } } } if (!map.get("latest") && settings.autofillGaps) { map.set("latest", shiftingValue); } } else { if (settings.autofillGaps) { fallback = map.get("latest") || 0; } } const stats = { oldest, earliest, oldestDate, earliestDate, earliestStableDate, }; return { map, stats, fallback, }; } // apply dedup & aliasing logics export function resolveTrackingPairs(pairs: TrackingPair[]): TrackingPair[] { const d: Record<string, TrackingPair> = {}; pairs.map((p) => { const { from, to } = resolveTrackingPair({ from: p.from, to: p.to, }); if (!isCountervalueEnabled(from) || !isCountervalueEnabled(to)) return; if (from === to) return; // dedup and keep oldest date let date = p.startDate; const k = pairId(p); if (d[k]) { const { startDate } = d[k]; if (startDate && date) { date = date < startDate ? date : startDate; } } d[k] = { from, to, startDate: date, }; }); // $FlowFixMe -_- return Object.values(d); }
the_stack
import * as React from 'react'; import DocumentTitle from 'react-document-title'; import { Drawer, Button, Table, Space, Pagination, message, Select, Form, Input, DatePicker } from 'antd'; import { StarOutlined, StarTwoTone, PlusOutlined } from '@ant-design/icons'; import { ColumnsType } from 'antd/es/table'; import moment from 'moment'; import Header from '@/components/Header'; import Footer from '@/components/Footer'; import '@/styles/home.less'; import { queryTaskList, addTask, editTask, updateTaskStatus, updateMark, deleteTask } from '@/utils/api'; import { formatDate } from '@/utils/valid'; interface Task { id: number, title: string, content: string, gmt_expire: number, status: number, is_major: any } interface Values { id?: number, title: string, date: any, content: string } interface IState { total: number, pageNo: number, pageSize: number, loading: boolean, textBtn: string, title: string, visible: boolean, currentRowData: Values, status: any, columns: ColumnsType<Task>, dataSource: Task[] } interface IProps { title: string, textBtn: string, visible: boolean, currentRowData: Values, onSubmitDrawer: (values: Values, type: number) => void, onCloseDrawer: () => void } const AddEditTaskForm: React.FC<IProps> = ({ title, textBtn, visible, currentRowData, onSubmitDrawer, onCloseDrawer }) => { const [form] = Form.useForm(); console.log('currentRowData===', currentRowData) setTimeout(() => { form.setFieldsValue(currentRowData); }, 100) const onSubmit = () => { form.validateFields() .then((values: any) => { if (title === '添加任务') { onSubmitDrawer(values, 1); } else { onSubmitDrawer(values, 2); } }) .catch(info => { console.log('Validate Failed:', info); }) } const onReset = () => { form.resetFields(); } const onClose = () => { form.resetFields(); onCloseDrawer(); } return ( <Drawer forceRender title={ title } width={ 600 } onClose={ onClose } visible={ visible } bodyStyle={{ paddingBottom: 80 }} maskClosable={ false } footer={ <div style={{display: 'flex', justifyContent: 'space-around'}}> <Button onClick={ onSubmit } type="primary">{ textBtn }</Button> <Button onClick={ onReset }>重置</Button> <Button onClick={ onClose } danger>取消</Button> </div> } > <Form form={ form } layout="vertical" name="form_in_modal" > <Form.Item label="任务名称" name="title" rules={[{ required: true, message: '请输入任务名称' }]} > <Input placeholder="请输入任务名称" /> </Form.Item> <Form.Item label="截止日期" name="date" rules={[{ required: true, message: '请选择截止日期' }]} > <DatePicker inputReadOnly={ true } placeholder="请选择截止日期" style={{ width: '100%' }} /> </Form.Item> <Form.Item label="任务内容" name="content" rules={[{ required: true, message: '请输入任务内容' }]} > <Input.TextArea rows={ 7 } placeholder="请输入任务内容" className="textarea" /> </Form.Item> </Form> </Drawer> ) } class Home extends React.Component<any, IState> { constructor(props: any) { super(props); this.state = { total: 0, pageNo: 1, pageSize: 10, loading: false, textBtn: '提交', title: '添加任务', currentRowData: { id: -1, title: '', date: '', content: '' }, visible: false, dataSource: [], status: null, // 0:待办 1:完成 2:删除 columns: [ { title: '序号', key: 'id', align: 'center', render: (text: any, record: any, index: number) => { let num = (this.state.pageNo - 1) * 10 + index + 1; return num; } }, { title: '任务名称', dataIndex: 'title', key: 'title', render: (text: any, record: any, index: number) => { const fav = this.state.dataSource[index].is_major; const style = { cursor: 'pointer', fontSize: '16px' } const icon = fav === 0 ? <StarOutlined style={ style } /> : <StarTwoTone style={ style } twoToneColor="#f50" />; return <div><span onClick={ () => this.toggleFav(record, index) }>{ icon }</span> { record.title }</div>; } }, { title: '任务内容', dataIndex: 'content', key: 'content' }, { title: '截止日期', dataIndex: 'gmt_expire', key: 'gmt_expire', render: (text: any, record: any) => formatDate(record.gmt_expire) }, { title: '任务状态', dataIndex: 'status', key: 'status', width: 120, render: (text: any, record: any) => { const txt = record.status === 0 ? '待办' : record.status === 1 ? '完成' : '删除'; return txt; } }, { title: '操作', key: 'action', width: 300, align: 'center', render: (text: any, record: any, index: number) => ( <Space size="middle"> <Button style={{marginRight: '10px', display: record.status !== 2 ? '' : 'none' }} onClick={ () => this.editTask(record, index) }>编辑</Button> <Button type="primary" ghost style={{marginRight: '10px', display: record.status !== 2 ? '' : 'none' }} onClick={ () => this.completeTask(record) }> { record.status === 0 ? '完成' : record.status === 1 ? '待办' : null } </Button> <Button danger style={{ display: record.status !== 2 ? '' : 'none' }} onClick={ () => this.removeTask(record.id) }>删除</Button> </Space> ) } ] } } componentDidMount () { console.log('componentDidMount===') this.getTaskList(); } componentWillUnmount () { console.log('componentWillUnmount===') } // 重要或不重要 toggleFav = (record: any, index: number) => { if (record.status === 2) { message.error('数据已删除'); } else { // is_major: 0:不重要 1:重要 let data = { id: record.id, is_major: this.state.dataSource[index].is_major === 0 ? 1 : 0 } updateMark(data) .then((res: any) => { console.log('操作标记===', res); if (res.code === 0) { this.setState({ pageNo: 1 }, () => { this.getTaskList(); message.success('更新标记成功'); }) } else { message.error(res.msg); } }) } } // 获取任务列表数据 getTaskList = () => { const { pageNo, pageSize, status } = this.state; this.setState({ loading: true }) let params = { pageNo: pageNo, pageSize: pageSize, status: status } queryTaskList(params) .then((res: any) => { console.log('任务列表===', res); this.setState({ loading: false }) if (res.code === 0 && res.data) { this.setState({ dataSource: res.data.rows, total: res.data.total }) } else { this.setState({ dataSource: [], total: 0 }) } }) .catch(() => { this.setState({ loading: false }) }) } // 添加任务对话框 addTask = () => { console.log('添加任务==='); this.setState({ title: '添加任务', textBtn: '提交', visible: true, currentRowData: { id: -1, title: '', date: '', content: '' } }) } // 编辑任务对话框 editTask = (record: any, index: number) => { console.log('编辑任务===', record); this.setState({ title: '编辑任务', textBtn: '保存', visible: true, currentRowData: { id: record.id, title: record.title, date: moment(record.gmt_expire), content: record.content } }) } // 删除任务 removeTask = (id: number) => { console.log('删除任务==='); let data = { id: id, status: 2 } deleteTask(data) .then((res: any) => { console.log('删除任务===', res); if (res.code === 0) { this.setState({ pageNo: 1 }, () => { this.getTaskList(); message.success('任务删除成功'); }) } else { message.error(res.msg); } }) } // 完成/待办任务 completeTask = (record: any) => { console.log('完成/待办任务==='); let status = record.status === 0 ? 1 : record.status === 1 ? 0 : null; let data = { id: record.id, status: status } updateTaskStatus(data) .then((res: any) => { console.log('操作状态===', res); if (res.code === 0) { this.setState({ pageNo: 1 }, () => { this.getTaskList(); message.success('更新任务状态成功'); }) } else { message.error(res.msg); } }) } // 提交添加或编辑表单 onSubmit = (values: Values, type: number) => { console.log('表单提交===', values); const { currentRowData } = this.state; if (type === 1) { let data = { title: values.title, gmt_expire: moment(values.date).valueOf(), content: values.content } addTask(data) .then((res: any) => { console.log('添加任务===', res) this.setState({ visible: false }) if (res.code === 0) { this.setState({ pageNo: 1 }, () => { this.getTaskList(); message.success(`新增任务 <${values.title}> 成功`); }) } else { message.error(res.msg); } }) .catch(() => { this.setState({ visible: false }) }) } else if (type === 2) { let data = { id: currentRowData.id, title: values.title, gmt_expire: moment(values.date).valueOf(), content: values.content } editTask(data) .then((res: any) => { console.log('编辑任务===', res) this.setState({ visible: false }) if (res.code === 0) { this.setState({ pageNo: 1 }, () => { this.getTaskList(); message.success(`更新任务 <${values.title}> 成功`); }) } else { message.error(res.msg); } }) .catch(() => { this.setState({ visible: false }) }) } } // 关闭任务对话框 onClose = () => { this.setState({ visible: false, currentRowData: { id: -1, title: '', date: '', content: '' } }) } // 页码改变的回调,返回改变后的页码 changePage = (pageNo: number) => { console.log('pageNo=', pageNo) this.setState({ pageNo }, () => { this.getTaskList(); }) } // 筛选任务状态 handleChange = (value: number) => { console.log('任务状态筛选===', typeof value === 'string') this.setState({ status: typeof value === 'string' ? null : value, pageNo: 1 }, () => { this.getTaskList(); }) } render () { const { total, pageNo, pageSize, loading, dataSource, columns, visible, title, textBtn, currentRowData } = this.state; const { Option } = Select; return ( <DocumentTitle title={'首页'}> <div className="home-container"> <Header curActive={'active'} /> <div className="content clearfix"> <div className="list"> <h2>任务列表</h2> <div className="list-right"> <Space size="middle"> <Select size="large" onChange={ this.handleChange } style={{ width: 160 }} allowClear placeholder="请筛选任务状态"> <Option value=''>全部</Option> <Option value={ 0 }>待办</Option> <Option value={ 1 }>完成</Option> <Option value={ 2 }>删除</Option> </Select> <Button type="primary" size="large" onClick={ this.addTask }><PlusOutlined /> 添加任务</Button> </Space> </div> </div> <Table bordered rowKey={ record => record.id } dataSource={ dataSource } columns={ columns } loading={ loading } pagination={ false } /> <Pagination className="pagination" total={ total } style={{ display: loading && total === 0 ? 'none' : '' }} showTotal={total => `共 ${total} 条数据`} onChange={ this.changePage } current={ pageNo } showSizeChanger={ false } defaultPageSize={ pageSize } hideOnSinglePage={ false } /> </div> <Footer /> <AddEditTaskForm title={ title } textBtn={ textBtn } visible={ visible } currentRowData={ currentRowData } onSubmitDrawer={ this.onSubmit } onCloseDrawer={ this.onClose } /> </div> </DocumentTitle> ) } } export default Home
the_stack
'use strict' module altai { export const MaxNumColorAttachments = 4; export const MaxNumVertexAttribs = 16; export function some<T>(opt0: T, opt1: T): T { return opt0 != null ? opt0 : opt1; } export function some3<T>(opt0: T, opt1: T, opt2: T): T { return opt0 != null ? opt0 : (opt1 != null ? opt1 : opt2); } /** * A Buffer object for vertex- or index-data. */ export class Buffer { readonly type: BufferType; readonly usage: Usage; readonly glBuffer: WebGLBuffer; constructor(o: BufferOptions, glBuffer: WebGLBuffer) { this.type = o.Type; this.usage = some(o.Usage, Usage.Immutable); this.glBuffer = glBuffer; } } /** * A Texture object. */ export class Texture { readonly type: TextureType; readonly usage: Usage; readonly width: number; readonly height: number; readonly depth: number; readonly numMipMaps: number; readonly colorFormat: PixelFormat; readonly depthFormat: DepthStencilFormat; readonly sampleCount: number; readonly wrapU: Wrap; readonly wrapV: Wrap; readonly wrapW: Wrap; readonly minFilter: Filter; readonly magFilter: Filter; readonly glTexture: WebGLTexture; readonly glMSAARenderBuffer: WebGLRenderbuffer; readonly glDepthRenderBuffer: WebGLRenderbuffer; constructor(o: TextureOptions, gl: WebGLRenderingContext|WebGL2RenderingContext) { this.type = o.Type; this.usage = some(o.Usage, Usage.Immutable); this.width = o.Width; this.height = o.Height; this.depth = some(o.Depth, 1); this.numMipMaps = some(o.NumMipMaps, 1); this.colorFormat = o.ColorFormat; this.depthFormat = some(o.DepthFormat, DepthStencilFormat.NONE); this.sampleCount = some(o.SampleCount, 1); this.wrapU = some(o.WrapU, Wrap.ClampToEdge); this.wrapV = some(o.WrapV, Wrap.ClampToEdge); this.wrapW = some(o.WrapW, Wrap.ClampToEdge); this.minFilter = some(o.MinFilter, Filter.Nearest); this.magFilter = some(o.MagFilter, Filter.Nearest); this.glTexture = gl.createTexture(); if (this.sampleCount > 1) { this.glMSAARenderBuffer = gl.createRenderbuffer(); } else { this.glMSAARenderBuffer = null; } if (this.depthFormat != DepthStencilFormat.NONE) { this.glDepthRenderBuffer = gl.createRenderbuffer(); } else { this.glDepthRenderBuffer = null; } } } export class VertexLayout { components: [string, VertexFormat][]; stepFunc?: StepFunc; stepRate?: number; constructor(o: VertexLayoutOptions) { this.components = o.Components; this.stepFunc = some(o.StepFunc, StepFunc.PerVertex); this.stepRate = some(o.StepRate, 1); } static vertexFormatByteSize(fmt: VertexFormat): number { switch (fmt) { case VertexFormat.Float: case VertexFormat.Byte4: case VertexFormat.Byte4N: case VertexFormat.UByte4: case VertexFormat.UByte4N: case VertexFormat.Short2: case VertexFormat.Short2N: return 4; case VertexFormat.Float2: case VertexFormat.Short4: case VertexFormat.Short4N: return 8; case VertexFormat.Float3: return 12; case VertexFormat.Float4: return 16; } } byteSize(): number { let size = 0; for (let comp of this.components) { size += VertexLayout.vertexFormatByteSize(comp[1]); } return size; } componentByteOffset(compIndex: number): number { let offset = 0; for (let i = 0; i < compIndex; i++) { offset += VertexLayout.vertexFormatByteSize(this.components[i][1]); } return offset; } } export class PipelineState { blendEnabled: boolean; blendSrcFactorRGB: BlendFactor; blendDstFactorRGB: BlendFactor; blendOpRGB: BlendOp; blendSrcFactorAlpha: BlendFactor; blendDstFactorAlpha: BlendFactor; blendOpAlpha: BlendOp; colorWriteMask: [boolean, boolean, boolean, boolean]; blendColor: [number, number, number, number]; stencilEnabled: boolean; frontStencilFailOp: StencilOp; frontStencilDepthFailOp: StencilOp; frontStencilPassOp: StencilOp; frontStencilCmpFunc: CompareFunc; frontStencilReadMask: number; frontStencilWriteMask: number; frontStencilRef: number; backStencilFailOp: StencilOp; backStencilDepthFailOp: StencilOp; backStencilPassOp: StencilOp; backStencilCmpFunc: CompareFunc; backStencilReadMask: number; backStencilWriteMask: number; backStencilRef: number; depthCmpFunc: CompareFunc; depthWriteEnabled: boolean; cullFaceEnabled: boolean; cullFace: Face; scissorTestEnabled: boolean; constructor(o: PipelineOptions) { this.blendEnabled = some(o.BlendEnabled, false); this.blendSrcFactorRGB = some3(o.BlendSrcFactorRGB, o.BlendSrcFactor, BlendFactor.One); this.blendDstFactorRGB = some3(o.BlendDstFactorRGB, o.BlendDstFactor, BlendFactor.Zero); this.blendOpRGB = some3(o.BlendOpRGB, o.BlendOp, BlendOp.Add); this.blendSrcFactorAlpha = some3(o.BlendSrcFactorAlpha, o.BlendSrcFactor, BlendFactor.One); this.blendDstFactorAlpha = some3(o.BlendDstFactorAlpha, o.BlendDstFactor, BlendFactor.Zero); this.blendOpAlpha = some3(o.BlendOpAlpha, o.BlendOp, BlendOp.Add); this.colorWriteMask = some(o.ColorWriteMask, [true, true, true, true] as [boolean, boolean, boolean, boolean]); this.blendColor = some(o.BlendColor, [1.0, 1.0, 1.0, 1.0] as [number, number, number, number]); this.stencilEnabled = some(o.StencilEnabled, false); this.frontStencilFailOp = some3(o.FrontStencilFailOp, o.StencilFailOp, StencilOp.Keep); this.frontStencilDepthFailOp = some3(o.FrontStencilDepthFailOp, o.StencilDepthFailOp, StencilOp.Keep); this.frontStencilPassOp = some3(o.FrontStencilPassOp, o.StencilPassOp, StencilOp.Keep); this.frontStencilCmpFunc = some3(o.FrontStencilCmpFunc, o.StencilCmpFunc, CompareFunc.Always); this.frontStencilReadMask = some3(o.FrontStencilReadMask, o.StencilReadMask, 0xFF); this.frontStencilWriteMask = some3(o.FrontStencilWriteMask, o.StencilWriteMask, 0xFF); this.frontStencilRef = some3(o.FrontStencilRef, o.StencilRef, 0); this.backStencilFailOp = some3(o.BackStencilFailOp, o.StencilFailOp, StencilOp.Keep); this.backStencilDepthFailOp = some3(o.BackStencilDepthFailOp, o.StencilDepthFailOp, StencilOp.Keep); this.backStencilPassOp = some3(o.BackStencilPassOp, o.StencilPassOp, StencilOp.Keep); this.backStencilCmpFunc = some3(o.BackStencilCmpFunc, o.StencilCmpFunc, CompareFunc.Always); this.backStencilReadMask = some3(o.BackStencilReadMask, o.StencilReadMask, 0xFF); this.backStencilWriteMask = some3(o.BackStencilWriteMask, o.StencilWriteMask, 0xFF); this.backStencilRef = some3(o.BackStencilRef, o.StencilRef, 0); this.depthCmpFunc = some(o.DepthCmpFunc, CompareFunc.Always); this.depthWriteEnabled = some(o.DepthWriteEnabled, false); this.cullFaceEnabled = some(o.CullFaceEnabled, false); this.cullFace = some(o.CullFace, Face.Back); this.scissorTestEnabled = some(o.ScissorTestEnabled, false); } } class glAttrib { enabled: boolean = false; vbIndex: number = 0; divisor: number = 0; stride: number = 0; size: number = 0; normalized: boolean = false; offset: number = 0; type: GLenum = 0; } /** * Opaque pipeline-state-object. */ export class Pipeline { readonly vertexLayouts: VertexLayout[]; readonly shader: Shader; readonly primitiveType: PrimitiveType; readonly state: PipelineState; readonly glAttribs: glAttrib[]; readonly indexFormat: IndexFormat; readonly indexSize: number; constructor(o: PipelineOptions) { this.vertexLayouts = []; for (let vlOpt of o.VertexLayouts) { this.vertexLayouts.push(new VertexLayout(vlOpt)); } this.shader = o.Shader; this.primitiveType = some(o.PrimitiveType, PrimitiveType.Triangles); this.state = new PipelineState(o); this.glAttribs = []; for (let i = 0; i < MaxNumVertexAttribs; i++) { this.glAttribs.push(new glAttrib()); } this.indexFormat = some(o.IndexFormat, IndexFormat.None); switch (this.indexFormat) { case IndexFormat.UInt16: this.indexSize = 2; break; case IndexFormat.UInt32: this.indexSize = 4; break; default: this.indexSize = 0; break; } } } /** * Opaque shader object. */ export class Shader { readonly glProgram: WebGLProgram; constructor(glProgram: WebGLProgram) { this.glProgram = glProgram; } } /** * A DrawState object is a bundle of resource binding slots, * create with Gfx.makePass(). DrawState objects area * mutable, the resource binding slots can be * reconfigured on existing DrawState objects. */ export class DrawState { Pipeline: Pipeline; VertexBuffers: Buffer[]; IndexBuffer: Buffer; Textures: {[key: string]: Texture; }; constructor(o: DrawStateOptions) { this.Pipeline = o.Pipeline; this.VertexBuffers = o.VertexBuffers; this.IndexBuffer = some(o.IndexBuffer, null); this.Textures = some(o.Textures, null); } } export class ColorAttachment { texture: Texture; mipLevel: number; slice: number; loadAction: LoadAction; clearColor: [number, number, number, number]; readonly glMSAAResolveFramebuffer: WebGLFramebuffer; constructor(o: ColorAttachmentOptions, glMsaaFb: WebGLFramebuffer) { this.texture = some(o.Texture, null); this.mipLevel = some(o.MipLevel, 0); this.slice = some(o.Slice, 0); this.loadAction = some(o.LoadAction, LoadAction.Clear); this.clearColor = some(o.ClearColor, [0.0, 0.0, 0.0, 1.0] as [number, number, number, number]); this.glMSAAResolveFramebuffer = glMsaaFb; } } export class DepthAttachment { texture: Texture; loadAction: LoadAction; clearDepth: number; clearStencil: number; constructor(o: DepthAttachmentOptions) { this.texture = some(o.Texture, null); this.loadAction = some(o.LoadAction, LoadAction.Clear); this.clearDepth = some(o.ClearDepth, 1.0); this.clearStencil = some(o.ClearStencil, 0); } } export class Pass { ColorAttachments: ColorAttachment[]; DepthAttachment: DepthAttachment; readonly glFramebuffer: WebGLFramebuffer; constructor(o: PassOptions, glFb: WebGLFramebuffer, glMsaaFbs: WebGLFramebuffer[]) { this.glFramebuffer = glFb; this.ColorAttachments = []; if (o.ColorAttachments == null) { this.ColorAttachments.push(new ColorAttachment({}, null)); } else { for (let i = 0; i < o.ColorAttachments.length; i++) { const glMsaaFb = (glMsaaFbs && glMsaaFbs[i]) ? glMsaaFbs[i]:null; this.ColorAttachments.push(new ColorAttachment(o.ColorAttachments[i], glMsaaFb)) } } this.DepthAttachment = new DepthAttachment(some(o.DepthAttachment, {})); } } }
the_stack
import { HttpHandler, HttpResponse } from '@angular/common/http'; import { PLATFORM_ID } from '@angular/core'; import { Observable } from 'rxjs'; import { take } from 'rxjs/operators'; import { FacebookProvider } from '../providers/facebook-provider'; import { GoogleProvider } from '../providers/google-provider'; import { MicrosoftProvider } from '../providers/microsoft-provider'; import { AuthenticationService } from './authentication.service'; import { ExternalAuthProvider } from './external-auth-configs'; import { ExternalAuthRedirectUrl, ExternalAuthService } from './external-auth.service'; import { BackendInterceptor } from './fake-backend.service'; import * as JWTUtil from './jwt-util'; import { LocalStorageService } from './local-storage'; import msKeys from './microsoft-keys'; import { UserService } from './user.service'; describe('Services', () => { describe('Authentication Service', () => { const MOCK_HTTP_CLIENT = { post: () => { } } as any; const authServ = new AuthenticationService(MOCK_HTTP_CLIENT); it('Should properly initialize', async () => { expect(authServ).toBeDefined(); }); it(`Should properly call 'login'`, async () => { const loginPostSpy = spyOn<any>(authServ, 'loginPost').and.returnValue(Promise.resolve()); const dummyData = { email: 'Dummy', password: 'Data' }; await authServ.login(dummyData); expect(loginPostSpy).toHaveBeenCalled(); expect(loginPostSpy).toHaveBeenCalledWith('/login', dummyData); }); it(`Should properly call 'register'`, async () => { const loginPostSpy = spyOn<any>(authServ, 'loginPost').and.returnValue(Promise.resolve()); const dummyData = { given_name: 'Testy', family_name: 'Testington', email: 'Dummy', password: 'Data' }; await authServ.register(dummyData); expect(loginPostSpy).toHaveBeenCalled(); expect(loginPostSpy).toHaveBeenCalledWith('/register', dummyData); }); it(`Should properly call 'loginWith'`, async () => { const loginPostSpy = spyOn<any>(authServ, 'loginPost').and.returnValue(Promise.resolve()); const dummyData = { id: 'Test', name: 'Testy', email: 'Dummy', externalToken: 'Data' }; await authServ.loginWith(dummyData); expect(loginPostSpy).toHaveBeenCalled(); expect(loginPostSpy).toHaveBeenCalledWith('/extlogin', dummyData); }); it(`Should properly call 'loginPost'`, async () => { const loginPostSpy = spyOn<any>(authServ, 'loginPost').and.callThrough(); const dummyData = { email: 'Dummy', password: 'Data' }; const mockObs = { toPromise: () => { } }; spyOn(mockObs, 'toPromise').and.returnValue('TEST DATA' as any); spyOn(MOCK_HTTP_CLIENT, 'post').and.returnValue(mockObs); const parseSpy = spyOn(JWTUtil, 'parseUser').and.returnValue({ user: 'Test' } as any); await authServ.login(dummyData); expect(loginPostSpy).toHaveBeenCalledWith('/login', dummyData); expect(MOCK_HTTP_CLIENT.post).toHaveBeenCalledWith('/login', dummyData); expect(parseSpy).toHaveBeenCalledWith('TEST DATA'); }); it(`Should properly call 'loginPost' and throw error`, async () => { const dummyData = { email: 'Dummy', password: 'Data' }; const mockObs = { toPromise: () => { } }; spyOn(mockObs, 'toPromise').and.callFake(() => { throw new Error('Test Error'); }); spyOn(MOCK_HTTP_CLIENT, 'post').and.returnValue(mockObs); expect(await (authServ as any).loginPost(dummyData)).toEqual({ error: 'Test Error' }); expect(MOCK_HTTP_CLIENT.post).toHaveBeenCalled(); }); }); describe('External Authentication Service', () => { const MOCK_OIDC_SECURITY = {} as any; const MOCK_OIDC_CONFIG = {} as any; const MOCK_ROUTER = {} as any; const MOCK_LOCATION = { prepareExternalUrl: () => { } } as any; const localStorage = new LocalStorageService(PLATFORM_ID); const extAuthServ = new ExternalAuthService(MOCK_ROUTER, MOCK_OIDC_SECURITY, MOCK_OIDC_CONFIG, MOCK_LOCATION, localStorage); it(`Should properly initialize`, () => { expect(extAuthServ).toBeDefined(); }); it(`Should properly get/set 'activeProvider'`, () => { spyOn(localStorage, 'getItem').and.returnValue('test'); const testProvider = extAuthServ.activeProvider; expect(localStorage.getItem).toHaveBeenCalled(); expect(localStorage.getItem).toHaveBeenCalledWith('extActiveProvider'); expect(testProvider).toEqual('test'); spyOn(localStorage, 'setItem'); extAuthServ.activeProvider = 'ccc' as any; expect(localStorage.setItem).toHaveBeenCalled(); expect(localStorage.setItem).toHaveBeenCalledWith('extActiveProvider', 'ccc'); }); it(`Should properly call 'hasProvider'`, () => { const providersMap = new Map<any, any>(); (extAuthServ as any).providers = providersMap; expect(extAuthServ.hasProvider()).toEqual(false); providersMap.set('0', '0'); expect(extAuthServ.hasProvider()).toEqual(true); expect(extAuthServ.hasProvider('0' as any)).toEqual(true); expect(extAuthServ.hasProvider('1' as any)).toEqual(false); }); it(`Should properly call 'addGoogle'`, () => { const providersSpy = spyOn<any>((extAuthServ as any).providers, 'set'); spyOn<any>(extAuthServ, 'getAbsoluteUrl').and.returnValue('testUrl'); const configParams = { provider: ExternalAuthProvider.Google, stsServer: 'https://accounts.google.com', client_id: 'test', scope: 'openid email profile', redirect_url: 'testUrl', response_type: 'id_token token', post_logout_redirect_uri: '/', post_login_route: 'redirect', auto_userinfo: false, max_id_token_iat_offset_allowed_in_seconds: 30 }; extAuthServ.addGoogle('test'); expect(providersSpy).toHaveBeenCalled(); expect(providersSpy).toHaveBeenCalledWith('Google', new GoogleProvider(MOCK_OIDC_CONFIG, MOCK_OIDC_SECURITY, configParams)); }); it(`Should properly call 'addFacebook'`, () => { const providersSpy = spyOn<any>((extAuthServ as any).providers, 'set'); const configParams = { client_id: 'test', redirect_url: ExternalAuthRedirectUrl.Facebook } as any; extAuthServ.addFacebook('test'); expect(providersSpy).toHaveBeenCalled(); expect(providersSpy).toHaveBeenCalledWith('Facebook', new FacebookProvider(configParams, MOCK_ROUTER)); }); it(`Should properly call 'addMicrosoft'`, () => { const providersSpy = spyOn<any>((extAuthServ as any).providers, 'set'); spyOn<any>(extAuthServ, 'getAbsoluteUrl').and.returnValue('testUrl'); const configParams = { provider: ExternalAuthProvider.Microsoft, stsServer: 'https://login.microsoftonline.com/consumers/v2.0/', client_id: 'test', scope: 'openid email profile', redirect_url: 'testUrl', response_type: 'id_token token', post_logout_redirect_uri: '/', post_login_route: '', auto_userinfo: false, max_id_token_iat_offset_allowed_in_seconds: 1000 } as any; extAuthServ.addMicrosoft('test'); expect(providersSpy).toHaveBeenCalled(); expect(providersSpy).toHaveBeenCalledWith('Microsoft', new MicrosoftProvider(MOCK_OIDC_CONFIG, MOCK_OIDC_SECURITY, configParams)); }); it(`Should properly call 'getUserInfo'`, async () => { const providersMap = new Map<any, any>(); const mockObj = { getUserInfo: () => { return { name: 'test' }; } }; spyOn(mockObj, 'getUserInfo').and.callThrough(); const providersGetSpy = spyOn(providersMap, 'get').and.returnValue(false); providersMap.set(ExternalAuthProvider.Facebook, mockObj); (extAuthServ as any).providers = providersMap; spyOn(Promise, 'reject').and.returnValue(Promise.resolve(null)); expect(await extAuthServ.getUserInfo(ExternalAuthProvider.Facebook)).toBeNull(); expect(providersGetSpy).toHaveBeenCalledTimes(1); providersGetSpy.and.returnValue(mockObj); expect(await extAuthServ.getUserInfo(ExternalAuthProvider.Facebook)).toEqual({ name: 'test', externalProvider: ExternalAuthProvider.Facebook } as any); expect(providersGetSpy).toHaveBeenCalledTimes(2); }); it(`Should properly call 'login'`, () => { const providersMap = new Map<any, any>(); const mockObj = { login: () => { } } as any; spyOn(mockObj, 'login'); const providersGetSpy = spyOn(providersMap, 'get').and.returnValue(false); providersMap.set(ExternalAuthProvider.Facebook, mockObj); (extAuthServ as any).providers = providersMap; const setActiveProvider = spyOnProperty(extAuthServ, 'activeProvider', 'set'); extAuthServ.login(ExternalAuthProvider.Facebook); expect(mockObj.login).not.toHaveBeenCalled(); expect(setActiveProvider).not.toHaveBeenCalled(); providersGetSpy.and.returnValue(mockObj); extAuthServ.login(ExternalAuthProvider.Facebook); expect(mockObj.login).toHaveBeenCalled(); expect(setActiveProvider).toHaveBeenCalledWith(ExternalAuthProvider.Facebook); }); it(`Should properly call 'logout'`, () => { const providersMap = new Map<any, any>(); const mockObj = { logout: () => { } } as any; spyOn(mockObj, 'logout'); providersMap.set(ExternalAuthProvider.Facebook, mockObj); spyOn(providersMap, 'get').and.returnValue(mockObj); (extAuthServ as any).providers = providersMap; const setActiveProviderSpy = spyOnProperty(extAuthServ, 'activeProvider', 'get').and.returnValue(false); extAuthServ.logout(); expect(mockObj.logout).not.toHaveBeenCalled(); expect(providersMap.get).not.toHaveBeenCalled(); expect(setActiveProviderSpy).toHaveBeenCalledTimes(1); setActiveProviderSpy.and.returnValue('MOCK TOKEN'); extAuthServ.logout(); expect(mockObj.logout).toHaveBeenCalled(); expect(providersMap.get).toHaveBeenCalled(); expect(providersMap.get).toHaveBeenCalledWith('MOCK TOKEN'); expect(setActiveProviderSpy).toHaveBeenCalledTimes(3); }); it(`Should properly call 'getAbsoluteUrl'`, () => { const currentOrigin = window.location.origin; spyOn(MOCK_LOCATION, 'prepareExternalUrl').and.returnValue('test_href_2'); expect((extAuthServ as any).getAbsoluteUrl('mock_path')).toEqual(`${currentOrigin}test_href_2`); expect(MOCK_LOCATION.prepareExternalUrl).toHaveBeenCalledWith('mock_path'); }); }); describe(`MOCK Backend Service`, () => { describe(`public`, () => { it(`Should properly call 'intercept'`, () => { const mockLocalStorage: LocalStorageService = new LocalStorageService({}); const provider = new BackendInterceptor(mockLocalStorage); const mockRequest = { method: 'POST', url: '/login', version: 'test' } as any; const mockUsers: any[] = []; const mockNext = { handle: () => new Observable<any>() } as HttpHandler; // endpoint /login // mocked method in intercept still need to return observable, otherwise rxjs pipe throws spyOn(provider, 'loginHandle').and.returnValue(new Observable()); spyOn(JSON, 'parse').and.returnValue(mockUsers); spyOn(mockLocalStorage, 'getItem').and.returnValue('[]'); provider.intercept(mockRequest, mockNext).pipe(take(1)).subscribe(() => { }); expect(JSON.parse).toHaveBeenCalledWith('[]'); expect(JSON.parse).toHaveBeenCalledTimes(1); expect(provider.loginHandle).toHaveBeenCalledWith(mockRequest); expect(provider.loginHandle).toHaveBeenCalledTimes(1); // endpoint /register mockRequest.url = '/register'; const getStorageUserSpy = spyOn<any>(provider, 'getStorageUser').and.returnValue({ name: 'Mock user' }); spyOn(provider, 'registerHandle').and.returnValue(new Observable()); provider.intercept(mockRequest, mockNext).pipe(take(1)).subscribe(() => { }); expect(JSON.parse).toHaveBeenCalledTimes(2); expect(getStorageUserSpy).toHaveBeenCalledWith(mockRequest); expect(getStorageUserSpy).toHaveBeenCalledTimes(1); expect(provider.registerHandle).toHaveBeenCalledWith({ name: 'Mock user' } as any); expect(provider.registerHandle).toHaveBeenCalledTimes(1); // endpoint /register mockRequest.url = '/extlogin'; const getStorageExtUserSpy = spyOn<any>(provider, 'getStorageExtUser').and.returnValue({ name: 'Mock user' }); provider.intercept(mockRequest, mockNext).pipe(take(1)).subscribe(() => { }); expect(JSON.parse).toHaveBeenCalledTimes(3); expect(getStorageExtUserSpy).toHaveBeenCalledWith(mockRequest); expect(getStorageExtUserSpy).toHaveBeenCalledTimes(1); expect(provider.registerHandle).toHaveBeenCalledWith({ name: 'Mock user' } as any, true); expect(provider.registerHandle).toHaveBeenCalledTimes(2); // microsoft keys mockRequest.method = 'GET'; mockRequest.url = '/ms-discovery/keys'; const expectedOutput = new HttpResponse({ status: 200, body: msKeys }); let output: any; provider.intercept(mockRequest, mockNext).pipe(take(1)).subscribe((e) => { output = e; }); expect(output).toEqual(expectedOutput); expect(JSON.parse).toHaveBeenCalledTimes(4); // no change in number of calls expect(getStorageUserSpy).toHaveBeenCalledTimes(1); expect(getStorageExtUserSpy).toHaveBeenCalledTimes(1); expect(provider.registerHandle).toHaveBeenCalledTimes(2); // no intercept scenario mockRequest.method = 'POST'; mockRequest.url = '/test'; spyOn(mockNext, 'handle').and.callThrough(); provider.intercept(mockRequest, mockNext).pipe(take(1)).subscribe(() => { }); expect(mockNext.handle).toHaveBeenCalledWith(mockRequest); expect(mockNext.handle).toHaveBeenCalledTimes(1); // test invalid case combiantions mockRequest.method = 'GET'; mockRequest.url = '/register'; provider.intercept(mockRequest, mockNext).pipe(take(1)).subscribe(() => { }); mockRequest.url = '/login'; provider.intercept(mockRequest, mockNext).pipe(take(1)).subscribe(() => { }); mockRequest.url = '/extlogin'; provider.intercept(mockRequest, mockNext).pipe(take(1)).subscribe(() => { }); mockRequest.method = 'POST'; mockRequest.url = '/ms-discovery/keys'; provider.intercept(mockRequest, mockNext).pipe(take(1)).subscribe(() => { }); expect(mockNext.handle).toHaveBeenCalledTimes(5); // no change in number of calls expect(getStorageUserSpy).toHaveBeenCalledTimes(1); expect(getStorageExtUserSpy).toHaveBeenCalledTimes(1); expect(provider.registerHandle).toHaveBeenCalledTimes(2); }); it(`Should properly call 'registerHandle'`, () => { const provider = new BackendInterceptor(new LocalStorageService({})); const localStorage = (provider as any).localStorage; const mockUser = { email: 'test_user' } as any; provider.users = [mockUser]; let output; let expectedOutput = { error: { message: 'Account with email "test_user" already exists' } } as any; provider.registerHandle(mockUser, false).pipe(take(1)).subscribe(() => { }, (e) => { output = e; }); expect(output).toEqual(expectedOutput); spyOn(localStorage, 'setItem'); spyOn(JSON, 'stringify').and.returnValue('MOCK OBJ'); const generateBodySpy = spyOn<any>(provider, 'getUserJWT').and.returnValue('MOCK BODY'); const tokenSpy = spyOn<any>(provider, 'generateToken').and.returnValue('MOCK TOKEN'); expectedOutput = new HttpResponse({ status: 200, body: 'MOCK TOKEN' }); provider.registerHandle({ email: 'test_user', customProp: 'very_custom ' } as any, true) .pipe(take(1)).subscribe((e) => { output = e; }); expect(output).toEqual(expectedOutput); expect(generateBodySpy).toHaveBeenCalledWith(mockUser); expect(generateBodySpy).toHaveBeenCalledTimes(1); expect(tokenSpy).toHaveBeenCalledWith('MOCK BODY'); expect(tokenSpy).toHaveBeenCalledTimes(1); expect(localStorage.setItem).toHaveBeenCalledTimes(1); expect(localStorage.setItem).toHaveBeenCalledWith('users', 'MOCK OBJ'); expect(JSON.stringify).toHaveBeenCalledTimes(1); expect(JSON.stringify).toHaveBeenCalledWith([{ email: 'test_user', customProp: 'very_custom ' }]); expect(provider.users).toEqual([{ email: 'test_user', customProp: 'very_custom ' }] as any); output = ''; provider.registerHandle({ email: 'new_user', customProp: 'test' } as any) .pipe(take(1)).subscribe((e) => { output = e; }); expect(output).toEqual(expectedOutput); expect(generateBodySpy).toHaveBeenCalledWith({ email: 'new_user', customProp: 'test' }); expect(generateBodySpy).toHaveBeenCalledTimes(2); expect(tokenSpy).toHaveBeenCalledWith('MOCK BODY'); expect(tokenSpy).toHaveBeenCalledTimes(2); expect(localStorage.setItem).toHaveBeenCalledTimes(2); expect(localStorage.setItem).toHaveBeenCalledWith('users', 'MOCK OBJ'); expect(JSON.stringify).toHaveBeenCalledTimes(2); expect(JSON.stringify) .toHaveBeenCalledWith([{ email: 'test_user', customProp: 'very_custom ' }, { email: 'new_user', customProp: 'test' }]); expect(provider.users) .toEqual([{ email: 'test_user', customProp: 'very_custom ' }, { email: 'new_user', customProp: 'test' }] as any); }); it(`Should properly call 'loginHandle'`, () => { const provider = new BackendInterceptor(new LocalStorageService({})); const mockUser = { email: 'test_email' } as any; provider.users = [mockUser]; const mockRequest = { body: { email: 'test_email' } } as any; spyOn(Array.prototype, 'find').and.callThrough(); const jwtSpy = spyOn<any>(provider, 'getUserJWT').and.returnValue('MOCK BODY'); const tokenSpy = spyOn<any>(provider, 'generateToken').and.returnValue('MOCK TOKEN'); const expectedOutput = new HttpResponse({ status: 200, body: 'MOCK TOKEN' }); provider.loginHandle(mockRequest).pipe(take(1)).subscribe((e) => { expect(e).toEqual(expectedOutput); }); expect(jwtSpy).toHaveBeenCalledWith(mockUser); expect(tokenSpy).toHaveBeenCalledWith('MOCK BODY'); const expectedError = { status: 401, error: { message: 'User does not exist!' } }; (provider.loginHandle({ body: { email: 'missing user' } } as any) as any).pipe(take(1)) .subscribe(() => { }, (e: any) => { expect(e).toEqual(expectedError); }, () => { }); }); }); describe(`private`, () => { it(`Should properly call 'getStorageUser'`, () => { const provider = new BackendInterceptor(new LocalStorageService({})); const mockInput = { body: { name: 'test_name', email: 'test_email', given_name: 'test_giver_name', family_name: 'test_family_name', } }; provider.users = []; expect((provider as any).getStorageUser(mockInput)).toEqual({ id: `1`, name: mockInput.body.given_name + ' ' + mockInput.body.family_name, email: mockInput.body.email, given_name: mockInput.body.given_name, family_name: mockInput.body.family_name, picture: '', }); }); it(`Should properly call 'getStorageExtUser'`, () => { const provider = new BackendInterceptor(new LocalStorageService({})); const mockInput = { body: { id: 'test_id', name: 'test_name', email: 'test_email', given_name: 'test_giver_name', family_name: 'test_family_name', picture: 'test_picture', externalToken: 'test_externalToken', externalProvider: 'test_externalProvider' } }; expect((provider as any).getStorageExtUser(mockInput)).toEqual({ id: mockInput.body.id, name: mockInput.body.name, email: mockInput.body.email, given_name: mockInput.body.given_name, family_name: mockInput.body.family_name, picture: mockInput.body.picture, externalToken: mockInput.body.externalToken, externalProvider: mockInput.body.externalProvider }); }); it(`Should properly call 'getUserJWT'`, () => { const provider = new BackendInterceptor(new LocalStorageService({})); const mockInput = { name: 'test_name', given_name: 'test_given_name', family_name: 'test_family_name', email: 'test_email', picture: 'test_picture' }; spyOn(Math, 'floor').and.returnValue(1000); spyOn(Date.prototype, 'getTime').and.returnValue(1000); const expectedExp = 1000 + (7 * 24 * 60 * 60); expect((provider as any).getUserJWT(mockInput)).toEqual({ exp: expectedExp, name: mockInput.name, given_name: mockInput.given_name, family_name: mockInput.family_name, email: mockInput.email, picture: mockInput.picture }); expect(Date.prototype.getTime).toHaveBeenCalled(); expect(Math.floor).toHaveBeenCalledWith(1); }); it(`Should properly call 'generateToken'`, () => { const provider = new BackendInterceptor(new LocalStorageService({})); const inputString = 'testString1'; const expectedOutput = 'g.g.mockSignature'; spyOn(JWTUtil, 'encodeBase64Url').and.returnValue('g'); expect((provider as any).generateToken(inputString)).toEqual(expectedOutput); }); }); }); describe(`User Service`, () => { const mockUser = { exp: 111, name: 'Testy Testington', given_name: 'Testy', family_name: 'Testington', email: 't-testing@test.test', picture: `testy-boy.png`, token: `mock token`, externalToken: `mock token` }; const localStorage = new LocalStorageService(PLATFORM_ID); beforeEach(() => { spyOn(JSON, 'parse').and.returnValue(mockUser); spyOn(localStorage, 'getItem').and.returnValue('MOCK JSON'); }); it(`Should properly initialize`, () => { const userServ = new UserService(localStorage); expect(userServ).toBeDefined(); expect(localStorage.getItem).toHaveBeenCalledWith('currentUser'); expect(JSON.parse).toHaveBeenCalledWith('MOCK JSON'); // get current user expect(userServ.currentUser).toEqual(mockUser); }); it(`Should properly get 'initials'`, () => { const userServ = new UserService(localStorage); const currentUserSpy = spyOnProperty(userServ, 'currentUser', 'get').and.returnValue(null); expect(userServ.initials).toEqual(null); currentUserSpy.and.returnValue({ given_name: '' }); expect(userServ.initials).toEqual(''); currentUserSpy.and.returnValue({ given_name: '', family_name: '' }); expect(userServ.initials).toEqual(''); currentUserSpy.and.returnValue({ given_name: '', family_name: 'g' }); expect(userServ.initials).toEqual('g'); currentUserSpy.and.returnValue({ given_name: 'h3ll0' }); expect(userServ.initials).toEqual('h'); currentUserSpy.and.returnValue({ given_name: 'h3ll0', family_name: 'g' }); expect(userServ.initials).toEqual('hg'); currentUserSpy.and.returnValue({ given_name: 'h3ll0', family_name: '' }); expect(userServ.initials).toEqual('h'); }); it(`Should properly 'setCurrentUser'`, () => { const userServ = new UserService(localStorage); const mockUser2 = { exp: 111, name: 'Qually T', given_name: 'Qually', family_name: 'Testington', email: 'q-t@test.test', picture: `qt-pie.png`, token: `mock token`, externalToken: `mock token 2` }; spyOn(JSON, 'stringify').and.returnValue('MOCK STRING'); spyOn(localStorage, 'setItem'); userServ.setCurrentUser(mockUser2); expect(userServ.currentUser).toEqual(mockUser2); expect(JSON.stringify).toHaveBeenCalledWith(mockUser2); expect(localStorage.setItem).toHaveBeenCalledWith('currentUser', 'MOCK STRING'); userServ.setCurrentUser(mockUser); expect(userServ.currentUser).toEqual(mockUser); }); it(`Should properly call 'clearCurrentUser'`, () => { const userServ = new UserService(localStorage); spyOn(localStorage, 'removeItem'); expect(userServ.currentUser).toBeTruthy(); userServ.clearCurrentUser(); expect(localStorage.removeItem).toHaveBeenCalledWith('currentUser'); expect(userServ.currentUser).toEqual(null); }); }); });
the_stack
declare function NSStringFromTWTRMediaEntitySizeResizingMode(resizingMode: TWTRMediaEntitySizeResizingMode): string; declare class TWTRAPIClient extends NSObject { static alloc(): TWTRAPIClient; // inherited from NSObject static clientWithCurrentUser(): TWTRAPIClient; static new(): TWTRAPIClient; // inherited from NSObject readonly userID: string; constructor(o: { userID: string; }); URLRequestWithMethodURLStringParametersError(method: string, URLString: string, parameters: NSDictionary<any, any>): NSURLRequest; initWithUserID(userID: string): this; loadTweetWithIDCompletion(tweetID: string, completion: (p1: TWTRTweet, p2: NSError) => void): void; loadTweetsWithIDsCompletion(tweetIDStrings: NSArray<any> | any[], completion: (p1: NSArray<TWTRTweet>, p2: NSError) => void): void; loadUserWithIDCompletion(userID: string, completion: (p1: TWTRUser, p2: NSError) => void): void; requestEmailForCurrentUser(completion: (p1: string, p2: NSError) => void): void; sendTweetWithTextCompletion(tweetText: string, completion: (p1: TWTRTweet, p2: NSError) => void): void; sendTweetWithTextImageCompletion(tweetText: string, image: UIImage, completion: (p1: TWTRTweet, p2: NSError) => void): void; sendTweetWithTextVideoDataCompletion(tweetText: string, videoData: NSData, completion: (p1: TWTRTweet, p2: NSError) => void): void; sendTwitterRequestCompletion(request: NSURLRequest, completion: (p1: NSURLResponse, p2: NSData, p3: NSError) => void): NSProgress; uploadMediaContentTypeCompletion(media: NSData, contentType: string, completion: (p1: string, p2: NSError) => void): void; } declare var TWTRCancelledShareTweetNotification: string; declare class TWTRCollectionTimelineDataSource extends NSObject implements TWTRTimelineDataSource { static alloc(): TWTRCollectionTimelineDataSource; // inherited from NSObject static new(): TWTRCollectionTimelineDataSource; // inherited from NSObject readonly collectionID: string; readonly maxTweetsPerRequest: number; APIClient: TWTRAPIClient; // inherited from TWTRTimelineDataSource 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 timelineFilter: TWTRTimelineFilter; // inherited from TWTRTimelineDataSource readonly timelineType: TWTRTimelineType; // inherited from TWTRTimelineDataSource readonly // inherited from NSObjectProtocol constructor(o: { collectionID: string; APIClient: TWTRAPIClient; }); constructor(o: { collectionID: string; APIClient: TWTRAPIClient; maxTweetsPerRequest: number; }); class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; initWithCollectionIDAPIClient(collectionID: string, client: TWTRAPIClient): this; initWithCollectionIDAPIClientMaxTweetsPerRequest(collectionID: string, client: TWTRAPIClient, maxTweetsPerRequest: number): this; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; loadPreviousTweetsBeforePositionCompletion(position: string, completion: (p1: NSArray<TWTRTweet>, p2: TWTRTimelineCursor, p3: NSError) => void): 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; } declare class TWTRComposer extends NSObject { static alloc(): TWTRComposer; // inherited from NSObject static new(): TWTRComposer; // inherited from NSObject setImage(image: UIImage): boolean; setText(text: string): boolean; setURL(url: NSURL): boolean; showFromViewControllerCompletion(fromController: UIViewController, completion: (p1: TWTRComposerResult) => void): void; } declare const enum TWTRComposerResult { Cancelled = 0, Done = 1 } declare class TWTRComposerViewController extends UIViewController { static alloc(): TWTRComposerViewController; // inherited from NSObject static emptyComposer(): TWTRComposerViewController; static new(): TWTRComposerViewController; // inherited from NSObject delegate: TWTRComposerViewControllerDelegate; constructor(o: { initialText: string; image: UIImage; videoData: NSData; }); constructor(o: { initialText: string; image: UIImage; videoURL: NSURL; }); initWithInitialTextImageVideoData(initialText: string, image: UIImage, videoData: NSData): this; initWithInitialTextImageVideoURL(initialText: string, image: UIImage, videoURL: NSURL): this; } interface TWTRComposerViewControllerDelegate extends NSObjectProtocol { composerDidCancel?(controller: TWTRComposerViewController): void; composerDidFailWithError?(controller: TWTRComposerViewController, error: NSError): void; composerDidSucceedWithTweet?(controller: TWTRComposerViewController, tweet: TWTRTweet): void; } declare var TWTRComposerViewControllerDelegate: { prototype: TWTRComposerViewControllerDelegate; }; declare var TWTRDidDismissVideoNotification: string; declare var TWTRDidLikeTweetNotification: string; declare var TWTRDidSelectTweetNotification: string; declare var TWTRDidShareTweetNotification: string; declare var TWTRDidShowTweetDetailNotification: string; declare var TWTRDidUnlikeTweetNotification: string; interface TWTRJSONConvertible extends NSObjectProtocol { initWithJSONDictionary?(dictionary: NSDictionary<any, any>): TWTRJSONConvertible; } declare var TWTRJSONConvertible: { prototype: TWTRJSONConvertible; }; declare class TWTRListTimelineDataSource extends NSObject implements TWTRTimelineDataSource { static alloc(): TWTRListTimelineDataSource; // inherited from NSObject static new(): TWTRListTimelineDataSource; // inherited from NSObject readonly includeRetweets: boolean; readonly listID: string; readonly listOwnerScreenName: string; readonly listSlug: string; readonly maxTweetsPerRequest: number; APIClient: TWTRAPIClient; // inherited from TWTRTimelineDataSource 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 timelineFilter: TWTRTimelineFilter; // inherited from TWTRTimelineDataSource readonly timelineType: TWTRTimelineType; // inherited from TWTRTimelineDataSource readonly // inherited from NSObjectProtocol constructor(o: { listID: string; APIClient: TWTRAPIClient; }); constructor(o: { listID: string; listSlug: string; listOwnerScreenName: string; APIClient: TWTRAPIClient; maxTweetsPerRequest: number; includeRetweets: boolean; }); constructor(o: { listSlug: string; listOwnerScreenName: string; APIClient: TWTRAPIClient; }); class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; initWithListIDAPIClient(listID: string, client: TWTRAPIClient): this; initWithListIDListSlugListOwnerScreenNameAPIClientMaxTweetsPerRequestIncludeRetweets(listID: string, listSlug: string, listOwnerScreenName: string, client: TWTRAPIClient, maxTweetsPerRequest: number, includeRetweets: boolean): this; initWithListSlugListOwnerScreenNameAPIClient(listSlug: string, listOwnerScreenName: string, client: TWTRAPIClient): this; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; loadPreviousTweetsBeforePositionCompletion(position: string, completion: (p1: NSArray<TWTRTweet>, p2: TWTRTimelineCursor, p3: NSError) => void): 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; } declare class TWTRLogInButton extends UIButton { static alloc(): TWTRLogInButton; // inherited from NSObject static appearance(): TWTRLogInButton; // inherited from UIAppearance static appearanceForTraitCollection(trait: UITraitCollection): TWTRLogInButton; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TWTRLogInButton; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): TWTRLogInButton; // inherited from UIAppearance static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TWTRLogInButton; // inherited from UIAppearance static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): TWTRLogInButton; // inherited from UIAppearance static buttonWithLogInCompletion(completion: (p1: TWTRSession, p2: NSError) => void): TWTRLogInButton; static buttonWithType(buttonType: UIButtonType): TWTRLogInButton; // inherited from UIButton static buttonWithTypePrimaryAction(buttonType: UIButtonType, primaryAction: UIAction): TWTRLogInButton; // inherited from UIButton static new(): TWTRLogInButton; // inherited from NSObject static systemButtonWithImageTargetAction(image: UIImage, target: any, action: string): TWTRLogInButton; // inherited from UIButton static systemButtonWithPrimaryAction(primaryAction: UIAction): TWTRLogInButton; // inherited from UIButton logInCompletion: (p1: TWTRSession, p2: NSError) => void; } declare var TWTRLoggedInUserIDKey: string; declare var TWTRLoggedOutUserIDKey: string; declare class TWTRMediaEntitySize extends NSObject implements NSCoding { static alloc(): TWTRMediaEntitySize; // inherited from NSObject static mediaEntitySizesWithJSONDictionary(dictionary: NSDictionary<any, any>): NSDictionary<any, any>; static new(): TWTRMediaEntitySize; // inherited from NSObject readonly name: string; readonly resizingMode: TWTRMediaEntitySizeResizingMode; readonly size: CGSize; constructor(o: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { name: string; resizingMode: TWTRMediaEntitySizeResizingMode; size: CGSize; }); encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; initWithNameResizingModeSize(name: string, resizingMode: TWTRMediaEntitySizeResizingMode, size: CGSize): this; isEqualToMediaEntitySize(otherSize: TWTRMediaEntitySize): boolean; } declare const enum TWTRMediaEntitySizeResizingMode { Fit = 0, Crop = 1 } declare function TWTRMediaEntitySizeResizingModeFromString(resizingModeString: string): TWTRMediaEntitySizeResizingMode; declare var TWTRMediaTypeM3u8: string; declare var TWTRMediaTypeMP4: string; declare class TWTRMoPubAdConfiguration extends NSObject { static alloc(): TWTRMoPubAdConfiguration; // inherited from NSObject static new(): TWTRMoPubAdConfiguration; // inherited from NSObject readonly adUnitID: string; readonly keywords: string; constructor(o: { adUnitID: string; keywords: string; }); initWithAdUnitIDKeywords(adUnitID: string, keywords: string): this; } declare class TWTRMoPubNativeAdContainerView extends UIView implements UIAppearanceContainer { static alloc(): TWTRMoPubNativeAdContainerView; // inherited from NSObject static appearance(): TWTRMoPubNativeAdContainerView; // inherited from UIAppearance static appearanceForTraitCollection(trait: UITraitCollection): TWTRMoPubNativeAdContainerView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TWTRMoPubNativeAdContainerView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): TWTRMoPubNativeAdContainerView; // inherited from UIAppearance static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TWTRMoPubNativeAdContainerView; // inherited from UIAppearance static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): TWTRMoPubNativeAdContainerView; // inherited from UIAppearance static new(): TWTRMoPubNativeAdContainerView; // inherited from NSObject adBackgroundColor: UIColor; buttonBackgroundColor: UIColor; primaryTextColor: UIColor; theme: TWTRNativeAdTheme; 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; } declare const enum TWTRNativeAdTheme { Light = 0, Dark = 1 } declare var TWTRNotificationInfoTweet: string; declare class TWTROAuthSigning extends NSObject implements TWTRCoreOAuthSigning { static alloc(): TWTROAuthSigning; // inherited from NSObject static new(): TWTROAuthSigning; // 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 constructor(o: { authConfig: TWTRAuthConfig; authSession: TWTRSession; }); OAuthEchoHeadersForRequestMethodURLStringParametersError(method: string, URLString: string, parameters: NSDictionary<any, any>): NSDictionary<any, any>; OAuthEchoHeadersToVerifyCredentials(): NSDictionary<any, any>; class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; initWithAuthConfigAuthSession(authConfig: TWTRAuthConfig, authSession: TWTRSession): 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 TWTRSearchTimelineDataSource extends NSObject implements TWTRTimelineDataSource { static alloc(): TWTRSearchTimelineDataSource; // inherited from NSObject static new(): TWTRSearchTimelineDataSource; // inherited from NSObject filterSensitiveTweets: boolean; geocodeSpecifier: string; readonly languageCode: string; readonly maxTweetsPerRequest: number; resultType: string; readonly searchQuery: string; APIClient: TWTRAPIClient; // inherited from TWTRTimelineDataSource 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 timelineFilter: TWTRTimelineFilter; // inherited from TWTRTimelineDataSource readonly timelineType: TWTRTimelineType; // inherited from TWTRTimelineDataSource readonly // inherited from NSObjectProtocol constructor(o: { searchQuery: string; APIClient: TWTRAPIClient; }); constructor(o: { searchQuery: string; APIClient: TWTRAPIClient; languageCode: string; maxTweetsPerRequest: number; resultType: string; }); class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; initWithSearchQueryAPIClient(searchQuery: string, client: TWTRAPIClient): this; initWithSearchQueryAPIClientLanguageCodeMaxTweetsPerRequestResultType(searchQuery: string, client: TWTRAPIClient, languageCode: string, maxTweetsPerRequest: number, resultType: string): this; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; loadPreviousTweetsBeforePositionCompletion(position: string, completion: (p1: NSArray<TWTRTweet>, p2: TWTRTimelineCursor, p3: NSError) => void): 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; } declare class TWTRTimelineCursor extends NSObject { static alloc(): TWTRTimelineCursor; // inherited from NSObject static new(): TWTRTimelineCursor; // inherited from NSObject readonly maxPosition: string; readonly minPosition: string; constructor(o: { maxPosition: string; minPosition: string; }); initWithMaxPositionMinPosition(maxPosition: string, minPosition: string): this; } interface TWTRTimelineDataSource extends NSObjectProtocol { APIClient: TWTRAPIClient; timelineFilter: TWTRTimelineFilter; timelineType: TWTRTimelineType; loadPreviousTweetsBeforePositionCompletion(position: string, completion: (p1: NSArray<TWTRTweet>, p2: TWTRTimelineCursor, p3: NSError) => void): void; } declare var TWTRTimelineDataSource: { prototype: TWTRTimelineDataSource; }; interface TWTRTimelineDelegate extends NSObjectProtocol { timelineDidBeginLoading?(timeline: TWTRTimelineViewController): void; timelineDidFinishLoadingTweetsError?(timeline: TWTRTimelineViewController, tweets: NSArray<any> | any[], error: NSError): void; } declare var TWTRTimelineDelegate: { prototype: TWTRTimelineDelegate; }; declare class TWTRTimelineFilter extends NSObject implements NSCopying { static alloc(): TWTRTimelineFilter; // inherited from NSObject static new(): TWTRTimelineFilter; // inherited from NSObject handles: NSSet<any>; hashtags: NSSet<any>; keywords: NSSet<any>; urls: NSSet<any>; constructor(o: { JSONDictionary: NSDictionary<any, any>; }); copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; filterCount(): number; initWithJSONDictionary(dictionary: NSDictionary<any, any>): this; } declare const enum TWTRTimelineType { User = 1, Search = 2, Collection = 3, List = 4 } declare class TWTRTimelineViewController extends UITableViewController { static alloc(): TWTRTimelineViewController; // inherited from NSObject static new(): TWTRTimelineViewController; // inherited from NSObject adConfiguration: TWTRMoPubAdConfiguration; dataSource: TWTRTimelineDataSource; showTweetActions: boolean; timelineDelegate: TWTRTimelineDelegate; tweetViewDelegate: TWTRTweetViewDelegate; constructor(o: { dataSource: TWTRTimelineDataSource; }); constructor(o: { dataSource: TWTRTimelineDataSource; adConfiguration: TWTRMoPubAdConfiguration; }); countOfTweets(): number; initWithDataSource(dataSource: TWTRTimelineDataSource): this; initWithDataSourceAdConfiguration(dataSource: TWTRTimelineDataSource, adConfiguration: TWTRMoPubAdConfiguration): this; refresh(): void; snapshotTweets(): NSArray<any>; tweetAtIndex(index: number): TWTRTweet; } declare class TWTRTweet extends NSObject implements NSCoding, TWTRJSONConvertible { static alloc(): TWTRTweet; // inherited from NSObject static new(): TWTRTweet; // inherited from NSObject static tweetsWithJSONArray(array: NSArray<any> | any[]): NSArray<any>; readonly author: TWTRUser; readonly createdAt: Date; readonly inReplyToScreenName: string; readonly inReplyToTweetID: string; readonly inReplyToUserID: string; readonly isLiked: boolean; readonly isQuoteTweet: boolean; readonly isRetweet: boolean; readonly isRetweeted: boolean; readonly languageCode: string; readonly likeCount: number; readonly permalink: NSURL; readonly perspectivalUserID: string; readonly quotedTweet: TWTRTweet; readonly retweetCount: number; readonly retweetID: string; readonly retweetedTweet: TWTRTweet; readonly text: string; readonly tweetID: 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: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { JSONDictionary: NSDictionary<any, any>; }); // inherited from TWTRJSONConvertible class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; initWithJSONDictionary(dictionary: NSDictionary<any, 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; tweetWithLikeToggled(): TWTRTweet; } declare class TWTRTweetCashtagEntity extends TWTRTweetEntity implements NSCoding, TWTRJSONConvertible { static alloc(): TWTRTweetCashtagEntity; // inherited from NSObject static new(): TWTRTweetCashtagEntity; // inherited from NSObject readonly text: 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: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { JSONDictionary: NSDictionary<any, any>; }); // inherited from TWTRJSONConvertible class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; initWithJSONDictionary(dictionary: NSDictionary<any, 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 TWTRTweetEntity extends NSObject implements NSCoding, NSCopying, TWTRJSONConvertible { static alloc(): TWTRTweetEntity; // inherited from NSObject static new(): TWTRTweetEntity; // inherited from NSObject readonly endIndex: number; readonly startIndex: number; readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol readonly superclass: typeof NSObject; // inherited from NSObjectProtocol readonly // inherited from NSObjectProtocol constructor(o: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { JSONDictionary: NSDictionary<any, any>; }); // inherited from TWTRJSONConvertible constructor(o: { startIndex: number; endIndex: number; }); accessibilityValue(): string; class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; initWithJSONDictionary(dictionary: NSDictionary<any, any>): this; initWithStartIndexEndIndex(startIndex: number, endIndex: 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 TWTRTweetHashtagEntity extends TWTRTweetEntity implements NSCoding, TWTRJSONConvertible { static alloc(): TWTRTweetHashtagEntity; // inherited from NSObject static new(): TWTRTweetHashtagEntity; // inherited from NSObject readonly text: 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: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { JSONDictionary: NSDictionary<any, any>; }); // inherited from TWTRJSONConvertible class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; initWithJSONDictionary(dictionary: NSDictionary<any, 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 TWTRTweetTableViewCell extends UITableViewCell { static alloc(): TWTRTweetTableViewCell; // inherited from NSObject static appearance(): TWTRTweetTableViewCell; // inherited from UIAppearance static appearanceForTraitCollection(trait: UITraitCollection): TWTRTweetTableViewCell; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TWTRTweetTableViewCell; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): TWTRTweetTableViewCell; // inherited from UIAppearance static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TWTRTweetTableViewCell; // inherited from UIAppearance static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): TWTRTweetTableViewCell; // inherited from UIAppearance static heightForTweetStyleWidthShowingActions(tweet: TWTRTweet, style: TWTRTweetViewStyle, width: number, showActions: boolean): number; static new(): TWTRTweetTableViewCell; // inherited from NSObject readonly tweetView: TWTRTweetView; configureWithTweet(tweet: TWTRTweet): void; } declare class TWTRTweetUrlEntity extends TWTRTweetEntity implements NSCoding, TWTRJSONConvertible { static alloc(): TWTRTweetUrlEntity; // inherited from NSObject static new(): TWTRTweetUrlEntity; // inherited from NSObject readonly displayUrl: string; readonly expandedUrl: string; readonly url: 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: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { JSONDictionary: NSDictionary<any, any>; }); // inherited from TWTRJSONConvertible class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; initWithJSONDictionary(dictionary: NSDictionary<any, 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 TWTRTweetUserMentionEntity extends TWTRTweetEntity implements NSCoding, TWTRJSONConvertible { static alloc(): TWTRTweetUserMentionEntity; // inherited from NSObject static new(): TWTRTweetUserMentionEntity; // inherited from NSObject readonly name: string; readonly screenName: string; readonly userID: 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: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { JSONDictionary: NSDictionary<any, any>; }); // inherited from TWTRJSONConvertible class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; initWithJSONDictionary(dictionary: NSDictionary<any, 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 TWTRTweetView extends UIView implements UIAppearanceContainer { static alloc(): TWTRTweetView; // inherited from NSObject static appearance(): TWTRTweetView; // inherited from UIAppearance static appearanceForTraitCollection(trait: UITraitCollection): TWTRTweetView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TWTRTweetView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): TWTRTweetView; // inherited from UIAppearance static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TWTRTweetView; // inherited from UIAppearance static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): TWTRTweetView; // inherited from UIAppearance static new(): TWTRTweetView; // inherited from NSObject delegate: TWTRTweetViewDelegate; linkTextColor: UIColor; presenterViewController: UIViewController; primaryTextColor: UIColor; shouldPlayVideoMuted: boolean; showActionButtons: boolean; showBorder: boolean; readonly style: TWTRTweetViewStyle; theme: TWTRTweetViewTheme; readonly tweet: TWTRTweet; 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: { tweet: TWTRTweet; }); constructor(o: { tweet: TWTRTweet; style: TWTRTweetViewStyle; }); class(): typeof NSObject; configureWithTweet(tweet: TWTRTweet): void; conformsToProtocol(aProtocol: any /* Protocol */): boolean; initWithTweet(tweet: TWTRTweet): this; initWithTweetStyle(tweet: TWTRTweet, style: TWTRTweetViewStyle): this; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; pauseVideo(): void; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; playVideo(): void; respondsToSelector(aSelector: string): boolean; retainCount(): number; self(): this; } interface TWTRTweetViewDelegate extends NSObjectProtocol { tweetViewDidChangePlaybackState?(tweetView: TWTRTweetView, newState: TWTRVideoPlaybackState): void; tweetViewDidTapImageWithURL?(tweetView: TWTRTweetView, image: UIImage, imageURL: NSURL): void; tweetViewDidTapProfileImageForUser?(tweetView: TWTRTweetView, user: TWTRUser): void; tweetViewDidTapTweet?(tweetView: TWTRTweetView, tweet: TWTRTweet): void; tweetViewDidTapURL?(tweetView: TWTRTweetView, url: NSURL): void; tweetViewDidTapVideoWithURL?(tweetView: TWTRTweetView, videoURL: NSURL): void; } declare var TWTRTweetViewDelegate: { prototype: TWTRTweetViewDelegate; }; declare const enum TWTRTweetViewStyle { Regular = 0, Compact = 1 } declare const enum TWTRTweetViewTheme { Light = 0, Dark = 1 } declare var TWTRTweetsNotLoadedKey: string; declare class TWTRTwitter extends NSObject { static alloc(): TWTRTwitter; // inherited from NSObject static new(): TWTRTwitter; // inherited from NSObject static sharedInstance(): TWTRTwitter; readonly authConfig: TWTRAuthConfig; readonly sessionStore: TWTRSessionStore; readonly version: string; applicationOpenURLOptions(application: UIApplication, url: NSURL, options: NSDictionary<any, any>): boolean; logInWithCompletion(completion: (p1: TWTRSession, p2: NSError) => void): void; logInWithViewControllerCompletion(viewController: UIViewController, completion: (p1: TWTRSession, p2: NSError) => void): void; sceneOpenURLContexts(scene: UIScene, URLContexts: NSSet<UIOpenURLContext>): void; startWithConsumerKeyConsumerSecret(consumerKey: string, consumerSecret: string): void; startWithConsumerKeyConsumerSecretAccessGroup(consumerKey: string, consumerSecret: string, accessGroup: string): void; } declare class TWTRUser extends NSObject implements NSCoding, NSCopying, TWTRJSONConvertible { static alloc(): TWTRUser; // inherited from NSObject static new(): TWTRUser; // inherited from NSObject readonly formattedScreenName: string; readonly isProtected: boolean; readonly isVerified: boolean; readonly name: string; readonly profileImageLargeURL: string; readonly profileImageMiniURL: string; readonly profileImageURL: string; readonly profileURL: NSURL; readonly screenName: string; readonly userID: 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: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { JSONDictionary: NSDictionary<any, any>; }); // inherited from TWTRJSONConvertible class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; initWithJSONDictionary(dictionary: NSDictionary<any, 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 var TWTRUserDidLogInNotification: string; declare var TWTRUserDidLogOutNotification: string; declare class TWTRUserTimelineDataSource extends NSObject implements TWTRTimelineDataSource { static alloc(): TWTRUserTimelineDataSource; // inherited from NSObject static new(): TWTRUserTimelineDataSource; // inherited from NSObject readonly includeReplies: boolean; readonly includeRetweets: boolean; readonly maxTweetsPerRequest: number; readonly screenName: string; readonly userID: string; APIClient: TWTRAPIClient; // inherited from TWTRTimelineDataSource 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 timelineFilter: TWTRTimelineFilter; // inherited from TWTRTimelineDataSource readonly timelineType: TWTRTimelineType; // inherited from TWTRTimelineDataSource readonly // inherited from NSObjectProtocol constructor(o: { screenName: string; APIClient: TWTRAPIClient; }); constructor(o: { screenName: string; userID: string; APIClient: TWTRAPIClient; maxTweetsPerRequest: number; includeReplies: boolean; includeRetweets: boolean; }); class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; initWithScreenNameAPIClient(screenName: string, client: TWTRAPIClient): this; initWithScreenNameUserIDAPIClientMaxTweetsPerRequestIncludeRepliesIncludeRetweets(screenName: string, userID: string, client: TWTRAPIClient, maxTweetsPerRequest: number, includeReplies: boolean, includeRetweets: boolean): this; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; loadPreviousTweetsBeforePositionCompletion(position: string, completion: (p1: NSArray<TWTRTweet>, p2: TWTRTimelineCursor, p3: NSError) => void): 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; } declare class TWTRVideoMetaData extends NSObject implements NSCoding, NSCopying, TWTRJSONConvertible { static alloc(): TWTRVideoMetaData; // inherited from NSObject static new(): TWTRVideoMetaData; // inherited from NSObject readonly aspectRatio: number; readonly duration: number; readonly variants: NSArray<any>; readonly videoURL: NSURL; 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: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { JSONDictionary: NSDictionary<any, any>; }); // inherited from TWTRJSONConvertible class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; initWithJSONDictionary(dictionary: NSDictionary<any, 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 TWTRVideoMetaDataVariant extends NSObject implements NSCoding, NSCopying, TWTRJSONConvertible { static alloc(): TWTRVideoMetaDataVariant; // inherited from NSObject static new(): TWTRVideoMetaDataVariant; // inherited from NSObject readonly URL: NSURL; readonly bitrate: number; readonly contentType: 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: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { JSONDictionary: NSDictionary<any, any>; }); // inherited from TWTRJSONConvertible class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; initWithJSONDictionary(dictionary: NSDictionary<any, 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 const enum TWTRVideoPlaybackState { Paused = 0, Playing = 1, Completed = 2 } declare var TWTRVideoPlaybackStateChangedNotification: string; declare var TWTRVideoPlaybackStateKey: string; declare var TWTRVideoStateValueCompleted: string; declare var TWTRVideoStateValuePaused: string; declare var TWTRVideoStateValuePlaying: string; declare var TWTRVideoTypeGIF: string; declare var TWTRVideoTypeKey: string; declare var TWTRVideoTypeStandard: string; declare var TWTRVideoTypeVine: string; declare var TWTRWillPresentVideoNotification: string; declare var TWTRWillShareTweetNotification: string;
the_stack
import { PageRange } from "../generated/artifacts/models"; import { PersistencyPageRange, ZERO_EXTENT_ID } from "../persistence/IBlobMetadataStore"; import IPageBlobRangesManager from "./IPageBlobRangesManager"; /********** Ranges Merging Strategy ************/ // // Example: // Existing ranges: |---| |------| |---------| |-----| // New range : |----------------------| // // 4 existing ranges, and one new request range. // Above 4 existing ranges, 3 existing ranges are get impacted. // // We have 2 merging strategies: // #1 Merge all impacted ranges // : |---| |**------------------------****| // #2 Split first and last impacted existing ranges: // : |---| |**|----------------------|****| // // Question: // Every range has a pointer to a chunk in one persistency layer extent. // When implementing Get Page Ranges Diff request, we will assume 2 (sub)ranges // are same if they pointing to same range of an extent. (Or we can comparing the // persistency layer payload, but it's not efficiency.) // // For #1 strategy, Get Page Ranges Diff will return a larger range scope than // the actual changed. Above ranges marked as * will point to new allocated extent, // while in previous snapshot, they still point to old extent. // One potential workaround is to update these ranges in snapshot blob to pointing // to same new allocated extent. But this will make implementation of update ranges // more complex, and also makes snapshot mutable. // Another concern is that, the * ranges may have large footprint, which is // time consuming. // // For #2 strategy, there will be more and more small ranges. See the |**| and |****|. // But it's able . We can make the "merging" work to future GC. // // We choose #2 strategy, and leave the merging work to future GC, which will merging // small ranges in background. // // TODO for #2 strategy: // * Resize API: Should remove additional ranges // * Download Page Blob API after resize (shift): Should taking resize into consideration // * Clean Ranges API: Same strategy like update ranges // * Page Blob GC for Ranges Merger: Merge small ranges and extent chunks for page blob and snapshots // * GC for un-referred extents export default class PageBlobRangesManager implements IPageBlobRangesManager { public mergeRange( ranges: PersistencyPageRange[], range: PersistencyPageRange ): void { const start = range.start; // Inclusive const end = range.end; // Inclusive const persistency = range.persistency; const impactedScope = this.selectImpactedRanges(ranges, start, end); // Find out first and last impacted range index const impactedStartIndex = impactedScope[0]; const impactedEndIndex = impactedScope[1]; const impactedRangesCount = impactedStartIndex > impactedEndIndex // No impacted ranges ? 0 : impactedEndIndex - impactedStartIndex + 1; // New created range for this request payload const newRange: PersistencyPageRange = { start, end, persistency }; if (impactedRangesCount === 0) { // If there is no existing impacted range, just insert the new range ranges.splice(impactedStartIndex, 0, newRange); } else { // Otherwise, try to split the first and last impacted ranges const firstImpactedRange = ranges[impactedStartIndex]; const lastImpactedRange = ranges[impactedEndIndex]; // Ranges to be inserted const newRanges = []; // If first range needs to be split, push the split range if (firstImpactedRange.end >= start && firstImpactedRange.start < start) { newRanges.push({ start: firstImpactedRange.start, end: start - 1, persistency: { id: firstImpactedRange.persistency.id, offset: firstImpactedRange.persistency.offset, count: start - firstImpactedRange.start } }); } newRanges.push(newRange); // If last impacted range needs to be split, push the split range if (end >= lastImpactedRange.start && end < lastImpactedRange.end) { newRanges.push({ start: end + 1, end: lastImpactedRange.end, persistency: { id: lastImpactedRange.persistency.id, offset: lastImpactedRange.persistency.offset + (end + 1 - lastImpactedRange.start), count: lastImpactedRange.end - end } }); } ranges.splice(impactedStartIndex, impactedRangesCount, ...newRanges); } } public clearRange(ranges: PersistencyPageRange[], range: PageRange): void { const start = range.start; // Inclusive const end = range.end; // Inclusive // Find out existing impacted ranges list const impactedScope = this.selectImpactedRanges(ranges, start, end); // Find out first and last impacted range index const impactedStartIndex = impactedScope[0]; const impactedEndIndex = impactedScope[1]; const impactedRangesCount = impactedStartIndex > impactedEndIndex // No impacted ranges ? 0 : impactedEndIndex - impactedStartIndex + 1; if (impactedRangesCount > 0) { // Try to split the first and last impacted ranges const firstImpactedRange = ranges[impactedStartIndex]; const lastImpactedRange = ranges[impactedEndIndex]; // Ranges to be inserted const newRanges = []; // If first range needs to be split, push the split range if (firstImpactedRange.end >= start && firstImpactedRange.start < start) { newRanges.push({ start: firstImpactedRange.start, end: start - 1, persistency: { id: firstImpactedRange.persistency.id, offset: firstImpactedRange.persistency.offset, count: start - firstImpactedRange.start } }); } // If last impacted range needs to be split, push the split range if (end >= lastImpactedRange.start && end < lastImpactedRange.end) { newRanges.push({ start: end + 1, end: lastImpactedRange.end, persistency: { id: lastImpactedRange.persistency.id, offset: lastImpactedRange.persistency.offset + (end + 1 - lastImpactedRange.start), count: lastImpactedRange.end - end } }); } ranges.splice(impactedStartIndex, impactedRangesCount, ...newRanges); } } /** * This method will not modify values of parameter ranges. * * @param {PersistencyPageRange[]} ranges * @param {PageRange} range * @returns {PersistencyPageRange[]} * @memberof PageBlobRangesManager */ public cutRanges( ranges: PersistencyPageRange[], range: PageRange ): PersistencyPageRange[] { const start = range.start; // Inclusive const end = range.end; // Inclusive const impactedScope = this.selectImpactedRanges(ranges, start, end); // Find out first and last impacted range index const impactedStartIndex = impactedScope[0]; const impactedEndIndex = impactedScope[1]; const impactedRangesCount = impactedStartIndex > impactedEndIndex ? 0 // No impacted ranges : impactedEndIndex - impactedStartIndex + 1; let impactedRanges: PersistencyPageRange[] = []; if (impactedRangesCount > 0) { impactedRanges = ranges.slice(impactedStartIndex, impactedEndIndex + 1); // If first range needs to be split const firstImpactedRange = impactedRanges[0]; if (firstImpactedRange.end >= start && firstImpactedRange.start < start) { impactedRanges[0] = { start, end: firstImpactedRange.end, persistency: { offset: start - firstImpactedRange.start + firstImpactedRange.persistency.offset, count: firstImpactedRange.persistency.count - (start - firstImpactedRange.start), id: firstImpactedRange.persistency.id } }; } const lastImpactedRange = impactedRanges[impactedRanges.length - 1]; // If last impacted range needs to be split if (end >= lastImpactedRange.start && end < lastImpactedRange.end) { impactedRanges[impactedRanges.length - 1] = { start: lastImpactedRange.start, end, persistency: { offset: lastImpactedRange.persistency.offset, count: lastImpactedRange.persistency.count - (lastImpactedRange.end - end), id: lastImpactedRange.persistency.id } }; } } return impactedRanges; } public fillZeroRanges( ranges: PersistencyPageRange[], range: PageRange ): PersistencyPageRange[] { ranges = this.cutRanges(ranges, range); const filledRanges: PersistencyPageRange[] = []; if (ranges.length === 0) { return [ { start: range.start, end: range.end, persistency: { offset: 0, count: range.end + 1 - range.start, id: ZERO_EXTENT_ID } } ]; } const firstRange = ranges[0]; const lastRange = ranges[ranges.length - 1]; if (range.start < firstRange.start) { filledRanges.push({ start: range.start, end: firstRange.start - 1, persistency: { offset: 0, count: firstRange.start - range.start, id: ZERO_EXTENT_ID } }); } // TODO: fill in zero ranges in the middle for (let i = 0; i < ranges.length - 1; i++) { const nextRange = ranges[i + 1]; const currentRange = ranges[i]; filledRanges.push(currentRange); const gap = nextRange.start - 1 - currentRange.end; if (gap > 0) { filledRanges.push({ start: currentRange.end + 1, end: nextRange.start - 1, persistency: { offset: 0, count: gap, id: ZERO_EXTENT_ID } }); } } filledRanges.push(ranges[ranges.length - 1]); if (lastRange.end < range.end) { filledRanges.push({ start: lastRange.end + 1, end: range.end, persistency: { offset: 0, count: range.end - lastRange.end, id: ZERO_EXTENT_ID } }); } return filledRanges; } /** * Select overlapped ranges based on binary search. * * @public * @param {PersistencyPageRange[]} ranges Existing ranges * @param {number} start Start offset of the new range, inclusive * @param {number} end End offset of the new range, inclusive * @returns {[number, number]} Impacted start and end ranges indexes tuple * When no impacted ranges found, will return indexes * for 2 closet existing ranges * [FirstLargerRangeIndex, FirstSmallerRangeIndex] * @memberof PageBlobRangesManager */ public selectImpactedRanges( ranges: PersistencyPageRange[], start: number, end: number ): [number, number] { if (ranges.length === 0) { return [Infinity, -1]; } if (start > end || start < 0) { throw new RangeError( // tslint:disable-next-line:max-line-length "PageBlobRangesManager:selectImpactedRanges() start must less equal than end parameter, start must larger equal than 0." ); } const impactedRangeStartIndex = this.locateFirstImpactedRange( ranges, 0, ranges.length, start ); const impactedRangesEndIndex = this.locateLastImpactedRange( ranges, 0, ranges.length, end ); return [impactedRangeStartIndex, impactedRangesEndIndex]; } /** * Locate first impacted range for a given position. * * @public * @param {PersistencyPageRange[]} ranges * @param {number} searchStart Index of start range in ranges array, inclusive * @param {number} searchEnd Index of end range in ranges array, exclusive * @param {number} position First range index covers or larger than position will be returned * @returns {number} Index of first impacted range or Infinity for no results * @memberof PageBlobHandler */ public locateFirstImpactedRange( ranges: PersistencyPageRange[], searchStart: number, searchEnd: number, position: number ): number { searchStart = searchStart < 0 ? 0 : searchStart; searchEnd = searchEnd > ranges.length ? searchEnd : searchEnd; if (ranges.length === 0 || searchStart >= searchEnd) { return Infinity; } // Only last element to check if (searchStart === searchEnd - 1) { return this.positionInRange(ranges[searchStart], position) || position < ranges[searchStart].start ? searchStart : Infinity; } // 2 or more elements left const searchMid = Math.floor((searchStart + searchEnd) / 2); const indexInLeft = this.locateFirstImpactedRange( ranges, searchStart, searchMid, position ); if (indexInLeft !== Infinity) { return indexInLeft; } if ( this.positionInRange(ranges[searchMid], position) || position < ranges[searchMid].start ) { return searchMid; } else { return this.locateFirstImpactedRange( ranges, searchMid + 1, // Remove searchMid range from searching scope searchEnd, position ); } } /** * Locate last impacted range for a given position. * * @public * @param {PersistencyPageRange[]} ranges * @param {number} searchStart Index of start range in ranges array, inclusive * @param {number} searchEnd Index of end range in ranges array, exclusive * @param {number} position Last range index covers or less than position will be returned * @returns {number} Index of first impacted range or -1 for no results * @memberof PageBlobHandler */ public locateLastImpactedRange( ranges: PersistencyPageRange[], searchStart: number, searchEnd: number, position: number ): number { searchStart = searchStart < 0 ? 0 : searchStart; searchEnd = searchEnd > ranges.length ? searchEnd : searchEnd; if (ranges.length === 0 || searchStart >= searchEnd) { return -1; } // Only last element to check if (searchStart === searchEnd - 1) { return this.positionInRange(ranges[searchStart], position) || position > ranges[searchStart].end ? searchStart : -1; } // 2 or more elements left const searchMid = Math.floor((searchStart + searchEnd) / 2); const indexInRight = this.locateLastImpactedRange( ranges, searchMid + 1, // Remove searchMid range from searching scope searchEnd, position ); if (indexInRight > -1) { return indexInRight; } if ( this.positionInRange(ranges[searchMid], position) || position > ranges[searchMid].end ) { return searchMid; } else { return this.locateLastImpactedRange( ranges, searchStart, searchMid, position ); } } public positionInRange( range: PersistencyPageRange, position: number ): boolean { return position >= range.start && position <= range.end; } }
the_stack
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="ru_RU"> <context> <name>AboutDialog</name> <message> <location filename="../../src/dialogs/aboutdialog.cpp" line="45"/> <source>About &lt;AppName&gt;</source> <translation>О программе &lt;AppName&gt;</translation> </message> <message> <location filename="../../src/dialogs/aboutdialog.cpp" line="59"/> <source>Version</source> <translation>Версия</translation> </message> <message> <location filename="../../src/dialogs/aboutdialog.cpp" line="60"/> <source>A customizable launcher for &lt;ParentName&gt; using Qt.</source> <translation>Настраиваемый интерфейс для &lt;ParentName&gt;, написанный на Qt.</translation> </message> <message> <location filename="../../src/dialogs/aboutdialog.cpp" line="64"/> <source>&lt;ParentName&gt; website</source> <translation>Сайт &lt;ParentName&gt;</translation> </message> <message> <location filename="../../src/dialogs/aboutdialog.cpp" line="66"/> <source>GitHub repository</source> <translation>Репозиторий GitHub</translation> </message> </context> <context> <name>ConfigEditor</name> <message> <location filename="../../src/dialogs/configeditor.cpp" line="49"/> <source>&lt;ParentName&gt; Config Editor</source> <translation>Редактор настроек &lt;ParentName&gt;</translation> </message> <message> <location filename="../../src/dialogs/configeditor.cpp" line="72"/> <source>Key Codes Reference</source> <translation>Таблица кодов клавиш</translation> </message> <message> <location filename="../../src/dialogs/configeditor.cpp" line="75"/> <source>Mupen64Plus Documentation</source> <translation>Документация Mupen64Plus</translation> </message> <message> <location filename="../../src/dialogs/configeditor.cpp" line="83"/> <source>Save</source> <translation>Сохранить</translation> </message> <message> <location filename="../../src/dialogs/configeditor.cpp" line="84"/> <source>Cancel</source> <translation>Отмена</translation> </message> </context> <context> <name>ControlInfo</name> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="45"/> <source>Mupen64Plus Default Controls</source> <translation>Клавиши Mupen64Plus по умолчанию</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="51"/> <source>These are the default controls for Mupen64Plus. </source> <translation>Это клавиши Mupen64Plus по умолчанию. </translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="52"/> <source>They can be modified using Settings-&gt;Edit mupen64plus.cfg...</source> <translation>Их можно модифицировать в меню Настройки-&gt;Изменить mupen64plus.cfg...</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="54"/> <source>For more information see the &lt;link&gt;Mupen64Plus Documentation&lt;linkend&gt;. </source> <translation>Для получения более подробной информации изучите &lt;link&gt;Документацию Mupen64Plus&lt;linkend&gt;. </translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="57"/> <source>For setting up a gamepad controller see &lt;link&gt;this page&lt;linkend&gt;. </source> <translation>Для настройки контроллера перейдите на &lt;link&gt;эту страницу&lt;linkend&gt;. </translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="60"/> <source>Note that Mupen64Plus output can be viewed with Emulation-&gt;View Log.</source> <translation>Примечание: вывод можно посмотреть в меню Эмуляция-&gt;Просмотреть журнал.</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="92"/> <source>N64 Input</source> <translation>Ввод N64</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="92"/> <location filename="../../src/dialogs/controlinfodialog.cpp" line="142"/> <source>Key</source> <translation>Клавиша</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="122"/> <source>Quit the emulator</source> <translation>Выйти из эмулятора</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="123"/> <source>Select virtual &apos;slot&apos; for save/load state commands</source> <translation>Выбрать виртуальный &apos;слот&apos; для команд сохранения/загрузки состояния</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="124"/> <source>Save emulator state</source> <translation>Сохранить состояние эмулятора</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="125"/> <source>Load emulator state</source> <translation>Загрузить состояние эмулятора</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="126"/> <source>Reset emulator</source> <translation>Сбросить эмулятор</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="127"/> <source>Slow down emulator by 5%</source> <translation>Замедлить эмулятор на 5%</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="128"/> <source>Speed up emulator by 5%</source> <translation>Ускорить эмулятор на 5%</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="129"/> <source>Take screenshot</source> <translation>Снять скриншот</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="130"/> <source>Toggle between windowed and fullscreen</source> <translation>Переключиться между оконным и полноэкранным режимами</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="131"/> <source>Pause on/off</source> <translation>Пауза</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="132"/> <source>Mute/unmute sound</source> <translation>Включить/выключить звук</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="133"/> <source>Press &quot;Game Shark&quot; button (only if cheats are enabled)</source> <translation>Нажать кнопку &quot;Game Shark&quot; (только если читы включены)</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="134"/> <source>Single frame advance while paused</source> <translation>Перейти на один кадр вперед во время паузы</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="135"/> <source>Fast forward (playback at 250% normal speed while pressed)</source> <translation>Быстрая перемотка вперед (воспроизведение на 250% от нормальной скорости при удерживании)</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="136"/> <source>Decrease volume</source> <translation>Уменьшить громкость</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="137"/> <source>Increase volume</source> <translation>Увеличить громкость</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="142"/> <source>Action</source> <translation>Действие</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="160"/> <source>Close</source> <translation>Закрыть</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="165"/> <source>Controller Input</source> <translation>Ввод контроллера</translation> </message> <message> <location filename="../../src/dialogs/controlinfodialog.cpp" line="166"/> <source>Hotkeys</source> <translation>Горячие клавиши</translation> </message> </context> <context> <name>DownloadDialog</name> <message> <location filename="../../src/dialogs/downloaddialog.cpp" line="50"/> <source>Search Game Information</source> <translation>Найти информацию об игре</translation> </message> <message> <location filename="../../src/dialogs/downloaddialog.cpp" line="54"/> <source>File</source> <translation>Файл</translation> </message> <message> <location filename="../../src/dialogs/downloaddialog.cpp" line="56"/> <source>Name of Game:</source> <translation>Название игры:</translation> </message> <message> <location filename="../../src/dialogs/downloaddialog.cpp" line="57"/> <source>or Game ID:</source> <translation>или идентификатор игры:</translation> </message> <message> <location filename="../../src/dialogs/downloaddialog.cpp" line="63"/> <source>From thegamesdb.net URL of game</source> <translation>URL игры на thegamesdb.net</translation> </message> <message> <location filename="../../src/dialogs/downloaddialog.cpp" line="66"/> <source>Search</source> <translation>Найти</translation> </message> <message> <location filename="../../src/dialogs/downloaddialog.cpp" line="67"/> <source>Cancel</source> <translation>Отмена</translation> </message> </context> <context> <name>EmulatorHandler</name> <message> <location filename="../../src/emulation/emulatorhandler.cpp" line="56"/> <location filename="../../src/emulation/emulatorhandler.cpp" line="189"/> <location filename="../../src/emulation/emulatorhandler.cpp" line="196"/> <location filename="../../src/emulation/emulatorhandler.cpp" line="206"/> <source>Warning</source> <translation>Внимание</translation> </message> <message> <location filename="../../src/emulation/emulatorhandler.cpp" line="57"/> <source>&lt;ParentName&gt; quit unexpectedly. Check the log for more information.</source> <translation>&lt;ParentName&gt; неожиданно прекратил работу. Просмотрите журнал для получения более подробной информации.</translation> </message> <message> <location filename="../../src/emulation/emulatorhandler.cpp" line="61"/> <source>View Log</source> <translation>Просмотреть журнал</translation> </message> <message> <location filename="../../src/emulation/emulatorhandler.cpp" line="126"/> <source>There was no output. If you were expecting Mupen64Plus to run, try copying</source> <translation>Нет вывода. Если вы думали, что Mupen64Plus запущен, попробуйте скопировать</translation> </message> <message> <location filename="../../src/emulation/emulatorhandler.cpp" line="127"/> <source>the above command into a command prompt to see if you get an error.</source> <translation>команду выше в командную строку и проверить вывод на наличие ошибок.</translation> </message> <message> <location filename="../../src/emulation/emulatorhandler.cpp" line="190"/> <source>&lt;ParentName&gt; executable not found.</source> <translation>Исполняемый файл &lt;ParentName&gt; не найден.</translation> </message> <message> <location filename="../../src/emulation/emulatorhandler.cpp" line="206"/> <source>Not a valid ROM File.</source> <translation>Некорректный файл ROM.</translation> </message> <message> <location filename="../../src/emulation/emulatorhandler.cpp" line="196"/> <source>ROM file not found.</source> <translation>Файл ROM не найден.</translation> </message> </context> <context> <name>GameSettingsDialog</name> <message> <location filename="../../src/dialogs/gamesettingsdialog.ui" line="20"/> <source>Game Settings</source> <translation>Настройки игры</translation> </message> <message> <location filename="../../src/dialogs/gamesettingsdialog.ui" line="26"/> <source>Game settings for:</source> <translation>Настройки игры для:</translation> </message> <message> <location filename="../../src/dialogs/gamesettingsdialog.ui" line="33"/> <source>These settings will override any global settings. If there&apos;s a setting you want to modify for this game, but it doesn&apos;t appear here, add the parameter for it to &quot;Other Parameters.&quot;</source> <translation>Данные настройки будут иметь приоритет над общими. Если вы хотите изменить какую-либо настройку для данной игры, но ее здесь нет, добавьте ее в &quot;Другие настройки.&quot;</translation> </message> <message> <location filename="../../src/dialogs/gamesettingsdialog.ui" line="43"/> <source>Plugins</source> <translation>Плагины</translation> </message> <message> <location filename="../../src/dialogs/gamesettingsdialog.ui" line="57"/> <source>Audio Plugin:</source> <translation>Плагин аудио:</translation> </message> <message> <location filename="../../src/dialogs/gamesettingsdialog.ui" line="64"/> <source>Input Plugin:</source> <translation>Плагин ввода:</translation> </message> <message> <location filename="../../src/dialogs/gamesettingsdialog.ui" line="71"/> <source>RSP Plugin:</source> <translation>Плагин RSP:</translation> </message> <message> <location filename="../../src/dialogs/gamesettingsdialog.ui" line="78"/> <source>Video Plugin:</source> <translation>Плагин видео:</translation> </message> <message> <location filename="../../src/dialogs/gamesettingsdialog.ui" line="86"/> <location filename="../../src/dialogs/gamesettingsdialog.ui" line="95"/> <location filename="../../src/dialogs/gamesettingsdialog.ui" line="104"/> <location filename="../../src/dialogs/gamesettingsdialog.ui" line="113"/> <source>default</source> <translation>По умолчанию</translation> </message> <message> <location filename="../../src/dialogs/gamesettingsdialog.ui" line="126"/> <source>Additional Settings</source> <translation>Дополнительные настройки</translation> </message> <message> <location filename="../../src/dialogs/gamesettingsdialog.ui" line="137"/> <source>Config Directory:</source> <translation>Каталог настроек:</translation> </message> <message> <location filename="../../src/dialogs/gamesettingsdialog.ui" line="144"/> <source>Other Parameters:</source> <translation>Другие настройки:</translation> </message> <message> <location filename="../../src/dialogs/gamesettingsdialog.ui" line="151"/> <source>Browse...</source> <translation>Обзор...</translation> </message> <message> <location filename="../../src/dialogs/gamesettingsdialog.cpp" line="92"/> <source>OK</source> <translation>OK</translation> </message> <message> <location filename="../../src/dialogs/gamesettingsdialog.cpp" line="93"/> <source>Cancel</source> <translation>Отмена</translation> </message> <message> <location filename="../../src/dialogs/gamesettingsdialog.cpp" line="110"/> <source>Config Directory</source> <translation>Каталог настроек</translation> </message> </context> <context> <name>GridView</name> <message> <location filename="../../src/views/gridview.cpp" line="145"/> <source>No Cart</source> <translation>Нет картриджа</translation> </message> </context> <context> <name>KeyCodes</name> <message> <location filename="../../src/dialogs/keycodesdialog.cpp" line="43"/> <source>SDL Key Codes</source> <translation>Коды клавиш SDL</translation> </message> <message> <location filename="../../src/dialogs/keycodesdialog.cpp" line="189"/> <source>Key</source> <translation>Клавиша</translation> </message> <message> <location filename="../../src/dialogs/keycodesdialog.cpp" line="189"/> <source>SDL Code</source> <translation>Код SDL</translation> </message> <message> <location filename="../../src/dialogs/keycodesdialog.cpp" line="202"/> <source>Close</source> <translation>Закрыть</translation> </message> </context> <context> <name>ListView</name> <message> <location filename="../../src/views/listview.cpp" line="159"/> <source>No Cart</source> <translation>Нет картриджа</translation> </message> </context> <context> <name>LogDialog</name> <message> <location filename="../../src/dialogs/logdialog.cpp" line="44"/> <source>&lt;ParentName&gt; Log</source> <translation>Журнал &lt;ParentName&gt;</translation> </message> <message> <location filename="../../src/dialogs/logdialog.cpp" line="59"/> <source>Close</source> <translation>Закрыть</translation> </message> </context> <context> <name>MainWindow</name> <message> <location filename="../../src/mainwindow.cpp" line="254"/> <source>&amp;File</source> <translation>&amp;Файл</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="255"/> <source>&amp;Open ROM...</source> <translation>&amp;Открыть ROM...</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="257"/> <source>&amp;Refresh List</source> <translation>О&amp;бновить список</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="258"/> <location filename="../../src/mainwindow.cpp" line="912"/> <source>&amp;Download/Update Info...</source> <translation>&amp;Загрузить/обновить информацию...</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="259"/> <location filename="../../src/mainwindow.cpp" line="913"/> <source>D&amp;elete Current Info...</source> <translation>&amp;Удалить текущую информацию...</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="263"/> <source>&amp;Quit</source> <translation>&amp;Выйти</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="282"/> <source>&amp;Emulation</source> <translation>&amp;Эмуляция</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="283"/> <location filename="../../src/mainwindow.cpp" line="902"/> <source>&amp;Start</source> <translation>&amp;Запустить</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="284"/> <source>St&amp;op</source> <translation>&amp;Остановить</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="302"/> <source>&amp;Settings</source> <translation>&amp;Настройки</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="303"/> <source>Edit mupen64plus.cfg...</source> <translation>Изменить mupen64plus.cfg...</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="305"/> <location filename="../../src/mainwindow.cpp" line="905"/> <source>Configure &amp;Game...</source> <translation>Настроить &amp;игру...</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="309"/> <source>&amp;Configure...</source> <translation>&amp;Параметры...</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="738"/> <source>There is no log. Either &lt;ParentName&gt; has not yet run or there was no output from the last run.</source> <translation>Журнал отсутствует. &lt;ParentName&gt; не был запущен или не выводил информацию с момента последнего запуска.</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="323"/> <source>&amp;Layout</source> <translation>&amp;Расположение</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="286"/> <source>View Log</source> <translation>Просмотреть журнал</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="322"/> <source>&amp;View</source> <translation>&amp;Вид</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="327"/> <source>None</source> <translation>Нет</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="328"/> <source>Table View</source> <translation>Таблица</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="329"/> <source>Grid View</source> <translation>Сетка</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="330"/> <source>List View</source> <translation>Список</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="357"/> <source>&amp;Full-screen</source> <translation>В&amp;о весь экран</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="373"/> <source>&amp;Help</source> <translation>&amp;Помощь</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="374"/> <source>Documentation</source> <translation>Документация</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="375"/> <source>Mupen64Plus Docs</source> <translation>Документы Mupen64Plus</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="377"/> <source>Default Controls</source> <translation>Управление по умолчанию</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="379"/> <source>&amp;About</source> <translation>&amp;О программе...</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="461"/> <source>Add a directory containing ROMs under </source> <translation>Добавьте каталог, содержащий файлы ROM, с помощью </translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="462"/> <source>Settings-&gt;Configure-&gt;Paths to use this view.</source> <translation>Настройки-&gt;Параметры-&gt;Пути, чтобы их показать.</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="715"/> <source>Not Found</source> <translation>Не найдено</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="715"/> <source>Editor requires config directory to be </source> <translation>Для работы редактора нужно задать каталог </translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="716"/> <source>set to a directory with mupen64plus.cfg.</source> <translation>с файлом mupen64plus.cfg в качестве каталога настроек.</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="717"/> <source>See here for the default config location:</source> <translation>Посмотрите здесь, чтобы узнать местоположение файла настроек по умолчанию:</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="737"/> <source>No Output</source> <translation>Нет вывода результатов</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="796"/> <source>All Files</source> <translation>Все файлы</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="802"/> <source>Open ROM File</source> <translation>Открыть файл ROM</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="820"/> <source>No ROMs</source> <translation>Нет файлов ROM</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="820"/> <source>No ROMs found in ZIP file.</source> <translation>Не найдены файлы ROM в файле ZIP.</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="835"/> <source>Select ROM</source> <translation>Выбрать ROM</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="852"/> <source>Launch</source> <translation>Запустить</translation> </message> <message> <location filename="../../src/mainwindow.cpp" line="853"/> <source>Cancel</source> <translation>Отмена</translation> </message> </context> <context> <name>QObject</name> <message> <location filename="../../src/common.cpp" line="328"/> <source>GoodName</source> <translation>GoodName</translation> </message> <message> <location filename="../../src/common.cpp" line="329"/> <source>Filename</source> <translation>Имя файла</translation> </message> <message> <location filename="../../src/common.cpp" line="330"/> <source>Filename (extension)</source> <translation>Имя файла (расширение)</translation> </message> <message> <location filename="../../src/common.cpp" line="331"/> <source>Zip File</source> <translation>Файл Zip</translation> </message> <message> <location filename="../../src/common.cpp" line="332"/> <source>Internal Name</source> <translation>Внутреннее имя</translation> </message> <message> <location filename="../../src/common.cpp" line="333"/> <source>Size</source> <translation>Размер</translation> </message> <message> <location filename="../../src/common.cpp" line="334"/> <source>MD5</source> <translation>MD5</translation> </message> <message> <location filename="../../src/common.cpp" line="335"/> <source>CRC1</source> <translation>CRC1</translation> </message> <message> <location filename="../../src/common.cpp" line="336"/> <source>CRC2</source> <translation>CRC2</translation> </message> <message> <location filename="../../src/common.cpp" line="337"/> <source>Players</source> <translation>Игроки</translation> </message> <message> <location filename="../../src/common.cpp" line="338"/> <source>Rumble</source> <translation>Rumble</translation> </message> <message> <location filename="../../src/common.cpp" line="339"/> <source>Save Type</source> <translation>Тип сохранений</translation> </message> <message> <location filename="../../src/common.cpp" line="340"/> <source>Game Title</source> <translation>Название игры</translation> </message> <message> <location filename="../../src/common.cpp" line="341"/> <source>Release Date</source> <translation>Дата выпуска</translation> </message> <message> <location filename="../../src/common.cpp" line="342"/> <source>Overview</source> <translation>Обзор</translation> </message> <message> <location filename="../../src/common.cpp" line="343"/> <source>ESRB</source> <translation>ESRB</translation> </message> <message> <location filename="../../src/common.cpp" line="344"/> <source>Genre</source> <translation>Жанр</translation> </message> <message> <location filename="../../src/common.cpp" line="345"/> <source>Publisher</source> <translation>Издатель</translation> </message> <message> <location filename="../../src/common.cpp" line="346"/> <source>Developer</source> <translation>Разработчик</translation> </message> <message> <location filename="../../src/common.cpp" line="347"/> <source>Rating</source> <translation>Рейтинг</translation> </message> <message> <location filename="../../src/common.cpp" line="348"/> <source>Game Cover</source> <translation>Обложка игры</translation> </message> <message> <location filename="../../src/common.cpp" line="349"/> <source>Unknown ROM</source> <translation>Неизвестный ROM</translation> </message> <message> <location filename="../../src/common.cpp" line="350"/> <source>Requires catalog file</source> <translation>Требуется файл каталога</translation> </message> <message> <location filename="../../src/common.cpp" line="351"/> <source>Not found</source> <translation>Не найдено</translation> </message> <message> <location filename="../../src/roms/romcollection.cpp" line="358"/> <source>%1 MB</source> <translation>%1 МБ</translation> </message> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="249"/> <location filename="../../src/roms/thegamesdbscraper.cpp" line="322"/> <location filename="../../src/roms/thegamesdbscraper.cpp" line="362"/> <source>Game Information Download</source> <translation>Загрузка информации об игре</translation> </message> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="318"/> <source>No results found.</source> <translation>Результатов нет.</translation> </message> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="320"/> <source>No more results found.</source> <translation>Больше результатов нет.</translation> </message> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="363"/> <source>Download Complete!</source> <translation>Загрузка завершена!</translation> </message> </context> <context> <name>RomCollection</name> <message> <location filename="../../src/roms/romcollection.cpp" line="190"/> <location filename="../../src/roms/romcollection.cpp" line="196"/> <source>Warning</source> <translation>Внимание</translation> </message> <message> <location filename="../../src/roms/romcollection.cpp" line="190"/> <source>No ROMs found in </source> <translation>Файлы ROM не найдены в </translation> </message> <message> <location filename="../../src/roms/romcollection.cpp" line="196"/> <source>No ROMs found.</source> <translation>Файлы ROM не найдены.</translation> </message> <message> <location filename="../../src/roms/romcollection.cpp" line="463"/> <source>Database Not Loaded</source> <translation>База данных не загружена</translation> </message> <message> <location filename="../../src/roms/romcollection.cpp" line="464"/> <source>Could not connect to Sqlite database. Application may misbehave.</source> <translation>Не удалось подключиться к базе данных SQLite. Некоторые функции программы могут не работать.</translation> </message> <message> <location filename="../../src/roms/romcollection.cpp" line="493"/> <source>Loading ROMs...</source> <translation>Загрузка файлов ROM...</translation> </message> <message> <location filename="../../src/roms/romcollection.cpp" line="493"/> <source>Cancel</source> <translation>Отмена</translation> </message> </context> <context> <name>SettingsDialog</name> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="20"/> <source>Settings</source> <translation>Настройки</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="43"/> <source>Paths</source> <translation>Пути</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="60"/> <location filename="../../src/dialogs/settingsdialog.ui" line="67"/> <location filename="../../src/dialogs/settingsdialog.ui" line="87"/> <location filename="../../src/dialogs/settingsdialog.ui" line="101"/> <location filename="../../src/dialogs/settingsdialog.ui" line="712"/> <source>Browse...</source> <translation>Обзор...</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="49"/> <source>Mupen64Plus Files</source> <translation>Файлы Mupen64Plus</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="108"/> <source>Mupen64Plus executable: </source> <translation>Исполняемый файл Mupen64Plus :</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="149"/> <source>ROM Directories</source> <translation>Каталоги файлов ROM</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="191"/> <source>Add...</source> <translation>Добавить...</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="198"/> <source>Remove</source> <translation>Удалить</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="214"/> <source>Emulation</source> <translation>Эмуляция</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="80"/> <source>Config directory:</source> <translation>Каталог настроек:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="94"/> <source>Plugins directory:</source> <translation>Каталог плагинов:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="118"/> <source>Data directory:</source> <translation>Каталог данных:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="175"/> <source>Mupen64Plus-Qt will search for all .z64, .v64, .n64, and .zip files in these directories</source> <translation>Mupen64Plus-Qt будет искать все файлы Z64, V64, N64 и ZIP в этих каталогах</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="225"/> <source>Cached Interpreter</source> <translation>Кэшируемый интерпретатор</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="232"/> <source>Pure Interpreter</source> <translation>Чистый интерпретатор</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="239"/> <source>Dynamic Recompiler</source> <translation>Динамический рекомпилятор</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="275"/> <source>Graphics</source> <translation>Графика</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="286"/> <source>On Screen Display:</source> <translation>Наэкранный дисплей:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="293"/> <source>Fullscreen:</source> <translation>Полный экран:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="300"/> <source>Resolution:</source> <translation>Разрешение:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="360"/> <source>Plugins</source> <translation>Плагины</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="368"/> <source>Video Plugin:</source> <translation>Плагин видео:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="375"/> <source>Audio Plugin:</source> <translation>Плагин аудио:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="382"/> <source>Input Plugin:</source> <translation>Плагин ввода:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="389"/> <source>RSP Plugin:</source> <translation>Плагин RSP:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="424"/> <source>Table</source> <translation>Таблица</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="438"/> <source>Image:</source> <translation>Изображение:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="475"/> <location filename="../../src/dialogs/settingsdialog.ui" line="485"/> <location filename="../../src/dialogs/settingsdialog.ui" line="527"/> <location filename="../../src/dialogs/settingsdialog.ui" line="537"/> <location filename="../../src/dialogs/settingsdialog.ui" line="949"/> <location filename="../../src/dialogs/settingsdialog.ui" line="959"/> <location filename="../../src/dialogs/settingsdialog.ui" line="995"/> <location filename="../../src/dialogs/settingsdialog.ui" line="1005"/> <source>...</source> <translation>...</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="552"/> <source>Current Columns:</source> <translation>Текущие столбцы:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="566"/> <source>Stretch First Column</source> <translation>Растягивать первый столбец</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="559"/> <source>Available Columns:</source> <translation>Доступные столбцы:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="615"/> <source>Grid</source> <translation>Сетка</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="621"/> <source>ROM Label</source> <translation>Метка ROM</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="632"/> <source>Show Label:</source> <translation>Показать метку:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="655"/> <source>Label Text:</source> <translation>Текст метки:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="669"/> <source>Label Color:</source> <translation>Цвет метки:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="704"/> <location filename="../../src/dialogs/settingsdialog.ui" line="1134"/> <source>Other</source> <translation>Другое</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="719"/> <source>Custom Background:</source> <translation>Пользовательский фон:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="726"/> <location filename="../../src/dialogs/settingsdialog.ui" line="1051"/> <source>Sorting:</source> <translation>Сортировка:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="736"/> <location filename="../../src/dialogs/settingsdialog.ui" line="1044"/> <source>Descending</source> <translation>По убыванию</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="753"/> <source>Background:</source> <translation>Фон:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="768"/> <source>ROM Image</source> <translation>Изображение ROM</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="801"/> <source>Shadow Inactive Color:</source> <translation>Цвет неактивной тени:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="808"/> <source>Shadow Active Color:</source> <translation>Цвет активной тени: </translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="815"/> <source>Columns:</source> <translation>Столбцы:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="822"/> <location filename="../../src/dialogs/settingsdialog.ui" line="1037"/> <source>Image Size:</source> <translation>Размер изображения:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="878"/> <source>Adjust Automatically</source> <translation>Выравнивать автоматически</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="904"/> <source>List</source> <translation>Список</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="1071"/> <source>First Item as Header</source> <translation>Первый элемент в качестве заголовка</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="931"/> <source>Current Items:</source> <translation>Текущие элементы:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="1030"/> <source>Available Items:</source> <translation>Доступные элементы:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="1078"/> <source>Display Cover Image</source> <translation>Отображать изображение обложки</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="1085"/> <source>Text Size:</source> <translation>Размер текста:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="1092"/> <source>Theme:</source> <translation>Тема:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="1168"/> <source>Additional Parameters:</source> <translation>Дополнительные настройки:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="1188"/> <source>Save Options:</source> <translation>Сохранять настройки:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="1181"/> <source>Download Game Information (thegamesdb.net):</source> <translation>Загружать информацию об игре (thegamesdb.net):</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="1195"/> <source>Language:</source> <translation>Язык:</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="1205"/> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Use to pass additional parameters to Mupen64Plus (cheats, etc.). See &lt;a href=&quot;http://mupen64plus.org/wiki/index.php?title=UIConsoleUsage&quot;&gt;&lt;span style=&quot; text-decoration: underline; color:#0057ae;&quot;&gt;http://mupen64plus.org/wiki/index.php?title=UIConsoleUsage&lt;/span&gt;&lt;/a&gt; for more information.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;используйте для передачи дополнительных параметров (читов и т.д.). Смотрите &lt;a href=&quot;http://mupen64plus.org/wiki/index.php?title=UIConsoleUsage&quot;&gt;&lt;span style=&quot; text-decoration: underline; color:#0057ae;&quot;&gt;http://mupen64plus.org/wiki/index.php?title=UIConsoleUsage&lt;/span&gt;&lt;/a&gt; для получения более подробной информации.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.ui" line="1240"/> <source>&lt;b&gt;Note:&lt;/b&gt; Language changes will not take place until application restart.</source> <translation>&lt;b&gt;Примечание:&lt;/b&gt; Язык изменится только после перезапуска программы.</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="86"/> <source>default</source> <translation>По умолчанию</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="179"/> <source>Extra Small</source> <translation>Очень маленький</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="180"/> <source>Small</source> <translation>Маленький</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="181"/> <source>Medium</source> <translation>Средний</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="182"/> <source>Large</source> <translation>Большой</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="183"/> <source>Extra Large</source> <translation>Очень большой</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="184"/> <source>Super</source> <translation>Супер</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="218"/> <source>Black</source> <translation>Черный</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="219"/> <source>White</source> <translation>Белый</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="220"/> <source>Light Gray</source> <translation>Светло-серый</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="221"/> <source>Dark Gray</source> <translation>Темно-серый</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="222"/> <source>Green</source> <translation>Зеленый</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="223"/> <source>Cyan</source> <translation>Голубой</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="224"/> <source>Blue</source> <translation>Синий</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="225"/> <source>Purple</source> <translation>Пурпурный</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="226"/> <source>Red</source> <translation>Красный</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="227"/> <source>Pink</source> <translation>Розовый</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="228"/> <source>Orange</source> <translation>Оранжевый</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="229"/> <source>Yellow</source> <translation>Желтый</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="230"/> <source>Brown</source> <translation>Коричневый</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="233"/> <location filename="../../src/dialogs/settingsdialog.cpp" line="312"/> <source>Light</source> <translation>Светлый</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="234"/> <source>Normal</source> <translation>Обычный</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="235"/> <location filename="../../src/dialogs/settingsdialog.cpp" line="313"/> <source>Dark</source> <translation>Темный</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="394"/> <source>OK</source> <translation>OK</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="395"/> <source>Cancel</source> <translation>Отмена</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="424"/> <source>ROM Directory</source> <translation>Каталог файлов ROM</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="448"/> <source>&lt;ParentName&gt; Executable</source> <translation>Исполняемый файл &lt;ParentName&gt;</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="466"/> <source>Plugin Directory</source> <translation>Каталог плагинов</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="475"/> <source>Data Directory</source> <translation>Каталог данных</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="483"/> <source>Config Directory</source> <translation>Каталог настроек</translation> </message> <message> <location filename="../../src/dialogs/settingsdialog.cpp" line="440"/> <source>Background Image</source> <translation>Фоновое изображение</translation> </message> </context> <context> <name>TableView</name> <message> <location filename="../../src/views/tableview.cpp" line="78"/> <location filename="../../src/views/tableview.cpp" line="81"/> <source>No Cart</source> <translation>Нет картриджа</translation> </message> </context> <context> <name>TheGamesDBScraper</name> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="103"/> <source>&lt;b&gt;NOTE:&lt;/b&gt; If you are deleting this game&apos;s information because the game doesn&apos;t </source> <translation>&lt;b&gt;Примечание:&lt;/b&gt; Если вы удаляете информацию об этой игре, поскольку ее </translation> </message> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="105"/> <source>better to create an account on</source> <translation>лучше создать аккаунт на</translation> </message> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="106"/> <source>and add the game so other users can benefit as well.</source> <translation>и добавить игру. Это поможет другим пользователям.</translation> </message> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="104"/> <source>exist on TheGamesDB and &lt;AppName&gt; pulled the information for different game, it&apos;s </source> <translation>нет на TheGamesDB и &lt;AppName&gt; выдает информацию о другой игре, </translation> </message> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="108"/> <source>This will cause &lt;AppName&gt; to not update the information for this game until you </source> <translation>&lt;AppName&gt; не будет обновлять информацию для этой игры, пока вы </translation> </message> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="109"/> <source>force it with &quot;Download/Update Info...&quot;</source> <translation>не выполните &quot;Загрузка/Обновить информацию...&quot;</translation> </message> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="111"/> <source>Delete the current information for</source> <translation>Удалить текущую информацию для</translation> </message> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="114"/> <source>Delete Game Information</source> <translation>Удалить информацию об игре</translation> </message> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="223"/> <source>The following error from TheGamesDB occured while downloading:</source> <translation>Во время загрузки с TheGamesDB произошла ошибка:</translation> </message> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="246"/> <source>Released on: </source> <translation>Выпущено на:</translation> </message> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="247"/> <source>Does this look correct?</source> <translation>Все верно?</translation> </message> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="402"/> <source>Request timed out. Check your network settings.</source> <translation>Время запроса истекло. Проверьте настройки сети.</translation> </message> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="410"/> <source>Continue scraping information?</source> <translation>Продолжить получение информации?</translation> </message> <message> <location filename="../../src/roms/thegamesdbscraper.cpp" line="413"/> <location filename="../../src/roms/thegamesdbscraper.cpp" line="415"/> <source>Network Error</source> <translation>Ошибка сети</translation> </message> </context> </TS>
the_stack
import * as monaco from "../monaco/monaco" import "./editor-themes" // for side-effects import { Script, ScriptMeta } from "./script" import { EventEmitter } from "./event" import { db } from "./data" import { config } from "./config" import { scriptsData } from "./script-data" import { ViewZones } from "./viewzones" import * as Eval from "./eval" import * as warningMessage from "./warning-message" import toolbar from "./toolbar" import { print, dlog, isMac } from "./util" import { menu } from "./menu" import { LoadScriptMsg } from "../common/messages" import resources from "./resources" import { NavigationHistory, HistoryEntry, NavigationHistorySnapshot } from "./history" import app from "./app" const DEBUG_HIDDEN_AREAS = DEBUG && false const ts = monaco.languages.typescript // some extensions to monaco, defined in src/monaco/monaco-editor/esm/vs/editor/scripter.js declare var __scripterMonaco : { patchEditorService( openCodeEditor:(input :OpenCodeEditorInput, editor :MonacoEditor)=>Promise<MonacoEditor|null> ) :void patchEditorModelResolverService( findModel:(editor :MonacoEditor, resource :monaco.Uri) => EditorModel|null ) :void patchUriLabelService( // returns a label for a resource. // Shows up as a tool tip and small text next to the filename getUriLabel:(resource :monaco.Uri, options? :{relative?:boolean}) => string ) :void patchBasenameOrAuthority(f? :(resource :monaco.Uri) => string|null|undefined) } interface OpenCodeEditorInput { resource? :monaco.Uri options? : { selection :monaco.IRange, } } type EditorModel = monaco.editor.ITextModel type EditorOptions = monaco.editor.IEditorOptions type MonacoEditor = monaco.editor.IStandaloneCodeEditor interface ScriptProgram { code :string sourceMap :string } interface EditorHistoryEntry extends HistoryEntry { readonly scriptGUID :string } const kLocked = Symbol("Locked") const kOnUnlock = Symbol("OnUnlock") const defaultFontSize = 12 // sync with --editorFontSize in app.css const varspaceFontFamily = "iaw-quattro-var, iaw-quattro, monospace, 'Inter var'" const monospaceFontFamily = "jbmono, monospace, 'Inter var'" // default monaco editor options const defaultOptions :EditorOptions = { // automaticLayout: true, lineDecorationsWidth: 16, // margin on left side, in pixels lineNumbers: "off", lineNumbersMinChars: 3, wordWrap: "off", // off | on | bounded | wordWrapColumn wrappingIndent: "same", // none | same | indent | deepIndent scrollBeyondLastLine: false, scrollBeyondLastColumn: 2, smoothScrolling: true, // animate scrolling to a position useTabStops: true, // fontLigatures: true, showUnused: false, // fade out unused variables folding: false, // must be off since July 2020 (messes with hidden wrapper) cursorBlinking: "smooth", // solid | blink | smooth | phase renderLineHighlight: "none", renderWhitespace: "selection", // none | boundary | selection | all (default: none) renderControlCharacters: false, multiCursorModifier: isMac ? 'ctrlCmd' : 'alt', dragAndDrop: true, fontSize: defaultFontSize, fontFamily: varspaceFontFamily, disableMonospaceOptimizations: false, // required for non-monospace fonts extraEditorClassName: 'scripter-light', // disable links since they can't be clicked in Figma anyways links: false, // disable code lens, which is not well documented, but a way to add stuff inline. codeLens: false, // not sure what this is, but we probably don't need it lightbulb: { enabled: false }, quickSuggestions: true, quickSuggestionsDelay: 800, // ms acceptSuggestionOnEnter: "smart", suggestSelection: "recentlyUsedByPrefix", // first | recentlyUsed | recentlyUsedByPrefix tabCompletion: "on", // "hover" configures the hover cards shown on pointer hover hover: { enabled: true, // Defaults to true. // Delay for showing the hover. delay: 1000, // Is the hover sticky such that it can be clicked and its contents selected? // sticky?: boolean; // Defaults to true. }, suggest: { // Enable graceful matching. Defaults to true. // filterGraceful?: boolean; // Prevent quick suggestions when a snippet is active. Defaults to true. // snippetsPreventQuickSuggestions?: boolean; // Favours words that appear close to the cursor. localityBonus: true, // Enable using global storage for remembering suggestions. shareSuggestSelections: true, // Enable or disable icons in suggestions. Defaults to true. // showIcons: false, // Max suggestions to show in suggestions. Defaults to 12. // maxVisibleSuggestions: 9, // Names of suggestion types to filter. // filteredTypes?: Record<string, boolean>; hideStatusBar: false, }, scrollbar: { useShadows: false, verticalScrollbarSize: 9, verticalSliderSize: 5, horizontalScrollbarSize: 9, horizontalSliderSize: 5, }, minimap: { enabled: false, }, } const typescriptCompilerOptions :monaco.languages.typescript.CompilerOptions = { // Note: When we set compiler options, we _override_ the default ones. // This is why we need to set allowNonTsExtensions. allowNonTsExtensions: true, // make "in-memory source" work target: ts.ScriptTarget.ES2019, allowUnreachableCode: true, allowUnusedLabels: true, removeComments: true, module: ts.ModuleKind.ES2015, sourceMap: true, // note: inlineSourceMap must not be true (we rely on this in eval) strictNullChecks: true, newLine: ts.NewLineKind.LineFeed, // scripter-env.js relies on this noImplicitAny: false, suppressImplicitAnyIndexErrors: true, jsx: ts.JsxEmit.React, jsxFactory: "DOM.createElement", // Note on source maps: Since we use eval, and eval in chrome does not interpret sourcemaps, // we disable sourcemaps for now (since it's pointless). // However, we could use the sourcemap lib to decorate error stack traces a la // evanw's sourcemap-support. The plugin could do this, so that the stack trace in Figma's // console is updated as well as what we display in the Scripter UI. Upon error, the plugin // process could request sourcemap from Scripter, so that we only have to transmit it on error. // inlineSourceMap: true, } export enum ModelChangeFlags { // bitflags NONE = 0, ADD_LINE = 1 << 0, REMOVE_LINE = 1 << 1, LAST_LINE_INTACT = 1 << 2, } export function ModelChangeFlagsString(flags :ModelChangeFlags) :string { let s = [] if (flags & ModelChangeFlags.ADD_LINE) { s.push("ADD_LINE") } if (flags & ModelChangeFlags.REMOVE_LINE) { s.push("REMOVE_LINE") } if (flags & ModelChangeFlags.LAST_LINE_INTACT) { s.push("LAST_LINE_INTACT") } return s.length == 0 ? "NONE" : s.join("|") } type DecoratedTextChangedCallback = (d :monaco.editor.IModelDecoration) => void interface EditorStateEvents { "init": undefined "modelchange": undefined "decorationchange": undefined } const kScript = Symbol("script") export class EditorState extends EventEmitter<EditorStateEvents> { readonly defaultFontSize = defaultFontSize editor :MonacoEditor options :EditorOptions = {...defaultOptions} editorPromise :Promise<MonacoEditor> _editorPromiseResolve: (e:MonacoEditor)=>void viewZones = new ViewZones(this) _currentModel :EditorModel _currentScript :Script _currentScriptId :number|null = -1 _nextModelId = 0 _saveViewStateTimer :any = null _lineNumberOffset = 0 // for hiddenAreas readonly hiddenAreas :ReadonlyArray<monaco.Range> = [] // maintained by updateHiddenAreas editorDecorationIds = [] decorationCallbacks = new Map<string,DecoratedTextChangedCallback>() changeObservationEnabled = false changeObservationActive = false changeObservationLastLineCount = 0 isInitialized = false constructor() { super() this.editorPromise = new Promise<MonacoEditor>(resolve => { this._editorPromiseResolve = resolve }) } fmtLineNumber(lineNumber: number) :string { // offset by 1 because of the hidden return (lineNumber - this._lineNumberOffset).toString(10) } // ---------------------------------------------------------------------------------- // Managing scripts get currentModel() :EditorModel { return this._currentModel } get currentScript() :Script { return this._currentScript } get currentScriptId() :number { return this._currentScript ? this._currentScript.id : -1 } onCurrentScriptSave = (_ :Script) => { dlog("script saved") this._currentScriptId = this._currentScript.id // may have been assigned one config.lastOpenScriptGUID = this._currentScript.guid // in case GUID changed // menu.updateScriptList() if (this._currentScript.modelVersion == 0) { // change caused not by the editor but by something else. Update editor when ready. let scriptId = this._currentScriptId this.editorPromise.then(() => { if (scriptId == this._currentScriptId) { this._currentModel.setValue(this._currentScript.body) } }) } } //models = new Map<Script,EditorModel>() getModel(script :Script) :EditorModel { if (this._currentScript === script) { return this._currentModel } let uri = this.modelURIForScript(script) let model = monaco.editor.getModel(uri) if (model) { dlog(`editor/getModel: using exising model for ${uri}`) return model } dlog(`editor/getModel: creating new model for ${uri}`) model = monaco.editor.createModel(script.body, "typescript", uri) model.updateOptions({ tabSize: config.tabSize, indentSize: config.tabSize, insertSpaces: !config.useTabs, trimAutoWhitespace: true, }) model[kScript] = script let onDeleteScript = (script :Script) => { this.disposeModel(script) script.removeListener("delete", onDeleteScript) } script.on("delete", onDeleteScript) // init new model right away so that we receive events for things like TS feedback this.initEditorModel(model) return model } disposeModel(script :Script) { // monaco.editor.getModels() let uri = this.modelURIForScript(script) let model = monaco.editor.getModel(uri) if (!model) { console.warn(`editor/disposeModel ${script}: no active model`) return } if (this._currentModel === model) { console.warn(`editor/disposeModel attempting to dispose active model (ignoring)`) return } dlog(`editor/disposeModel ${script}`) model.dispose() } modelURIForScript(script :Script) :monaco.Uri { let filename = script.guid if (!filename.endsWith(".d.ts")) { filename = "scripter." + filename + ".tsx" } return monaco.Uri.file(filename) // return monaco.Uri.from({scheme:"scripter", path:filename}) } setCurrentScriptFromUserAction(script :Script) { this.setCurrentScript(script) this.historyPush() } setCurrentScript(script :Script) :EditorModel { let model = this.getModel(script) if (model === this._currentModel) { return model } if (!script.isLoaded) { console.warn("editor/setCurrentScript with not-yet-loaded script", script) } if (this._currentScript) { this._currentScript.removeListener("save", this.onCurrentScriptSave) } this._currentModel = model if (this.editor) { // path taken in all cases except during app initialization this.clearAllMetaInfo() this.setModel(model) this.updateOptions({ readOnly: script.isROLib, }) let layoutAndFocus = () => { this.editor.layout() this.editor.focus() } layoutAndFocus() requestAnimationFrame(() => { layoutAndFocus() this.restoreViewState() setTimeout(layoutAndFocus, 1) setTimeout(layoutAndFocus, 100) this.updateHiddenAreas() }) this.updateHiddenAreas() } this._currentScript = script this._currentScriptId = script.id this._currentScript.on("save", this.onCurrentScriptSave) // config.lastOpenScript = script.id config.lastOpenScriptGUID = script.guid return model } setModel(model :EditorModel) { let prevModel = this.editor.getModel() if (prevModel !== model) { // // Note: Monaco only has a single TypeScript instance, so we can't have multiple // // models in Scripter as they would share scope, which causes errors like // // "can not redeclare x". So, we dispose any previous model before setting a new one. // // Disposing of a model causes the TypeScript instance to "forget". // if (prevModel) { // prevModel.dispose() // } this.editor.setModel(model) } this._currentModel = model if (this.editor) { this.updateHiddenAreas() } } _isSwitchingModel = false // used to avoid recording edits to scripts async switchToScript(script :Script) :Promise<Script> { let editor = await this.editorPromise // wait for editor to initialize this.stopCurrentScript() this.setCurrentScriptFromUserAction(script) return this._currentScript } async newScript(meta? :Partial<ScriptMeta>, body :string = "") :Promise<Script> { let script = Script.create(meta, body) return this.switchToScript(script) } // Attempts to open script. // Returns null if another open action won the natural race condition. async openScript(script :Script) :Promise<Script|null> { if (this._currentScript.guid == script.guid || this._currentScriptId == script.id) { this.editor.focus() return this._currentScript } dlog(`open script ${script}`) this._currentScriptId = script.id this.stopCurrentScript() if (this._currentScriptId != script.id) { // another openScript call was made -- discard return null } return this.switchToScript(script) } async openScriptByID(id :number) :Promise<Script|null> { if (DEBUG) { console.warn("legacy access to editor/openScriptByID") } if (this._currentScript && this._currentScript.id == id) { this.editor.focus() return this._currentScript } let script = await scriptsData.getScript(id) if (!script) { // TODO: move error reporting to callers console.error(`openScriptByID(${id}) failed (not found)`) return null } return this.openScript(script) } async openScriptByGUID(guid :string) :Promise<Script|null> { if (!guid) { return null } if (typeof guid != "string") { throw new Error("invalid guid") } if (this._currentScript && this._currentScript.guid == guid) { this.editor.focus() return this._currentScript } let script = await scriptsData.getScriptByGUID(guid) if (!script) { return null } return this.openScript(script) } // save current script to Figma canvas in a new node async saveScriptToFigma() { this.currentScript.saveToFigma({ createIfMissing: true }) editor.focus() requestAnimationFrame(() => editor.focus()) } async loadScriptFromFigma(msg :LoadScriptMsg) { let s = msg.script dlog("editor.loadScriptFromFigma", s.guid, s.name) let script = await this.openScriptByGUID(s.guid) if (script) { dlog("editor.loadScriptFromFigma found local version of script") // a script with the same GUID was found in local database if (script.body != s.body && script.body.trim() != s.body.trim()) { // Body of local version != body of script on canvas. // Unless the local version is empty, ask user what to do and if acceptable, // update local script body. if (script.body.trim() == "" || confirm( "Replace script?\n" + "The script in the Figma file differs from the script stored locally. " + "Would you like to update your local version with the script?") ) { script.body = s.body // will trigger save } } } else { dlog("editor.loadScriptFromFigma no local version; creating new") script = await this.newScript({ guid: s.guid, name: s.name }, s.body) } } // ---------------------------------------------------------------------------------- // Editor configuration restoreViewState() { let viewState = this._currentScript.editorViewState if (viewState) { this.editor.restoreViewState(viewState) // setTimeout(() => { this.editor.restoreViewState(viewState) }, 0) } // // workaround for a bug in monaco: // // Flipping disableMonospaceOptimizations fixes bug with variable-width fonts // // where line length is incorrectly computed. // // The wordWrap change causes Monaco to shrink its viewport to fit the content. // // For some reason the Monaco viewport never shrinks, even when editing. // if (this.options.disableMonospaceOptimizations) { // let wordWrap = this.options.wordWrap // this.updateOptions({ disableMonospaceOptimizations: false, wordWrap: "on" }) // setTimeout(() => { // this.updateOptions({ disableMonospaceOptimizations: true, wordWrap }) // }, 1) // // Note: requestAnimationFrame doesn't seem to work. // } } saveViewState() { clearTimeout(this._saveViewStateTimer as number) this._saveViewStateTimer = null this._currentScript.editorViewState = this.editor.saveViewState() } setNeedsSaveViewState() { if (this._saveViewStateTimer === null) { this._saveViewStateTimer = setTimeout(() => this.saveViewState(), 200) } } getEffectiveOptions() :EditorOptions { let options :EditorOptions = { lineNumbers: config.showLineNumbers ? this.fmtLineNumber.bind(this) : "off", wordWrap: config.wordWrap ? "on" : "off", quickSuggestions: config.quickSuggestions, quickSuggestionsDelay: config.quickSuggestionsDelay, //folding: config.codeFolding, renderWhitespace: config.showWhitespace ? "all" : "selection", renderControlCharacters: config.showWhitespace, renderIndentGuides: config.indentGuides, fontSize: defaultFontSize * config.uiScale, } options.minimap = {...this.options.minimap, enabled: config.minimap } options.hover = {...this.options.hover, enabled: config.hoverCards } if (config.monospaceFont) { options.fontFamily = monospaceFontFamily options.disableMonospaceOptimizations = false document.body.classList.toggle("font-ligatures", config.fontLigatures) } else { options.fontFamily = varspaceFontFamily options.disableMonospaceOptimizations = true document.body.classList.add("font-ligatures") } return options } updateOptionsFromConfig() { this.updateOptions(this.getEffectiveOptions()) this.currentModel.updateOptions({ tabSize: config.tabSize, indentSize: config.tabSize, insertSpaces: !config.useTabs, }) } updateOptions(options :EditorOptions) :boolean { let updated = false for (let k in options) { let v = options[k] if (k == "extraEditorClassName") { // prefix with current theme v = `scripter-light ${v}`.trim() } if (this.options[k] !== v) { this.options[k] = v updated = true } } if (updated && this.editor) { this.editor.updateOptions(this.options) } return updated } // focuses keyboard input focus() { this.editor.focus() } // ---------------------------------------------------------------------------------- // Running scripts runDebounceTimer :any = null currentEvalPromise :Eval.EvalPromise|null = null // non-null while script is running async runCurrentScript() :Promise<void> { if (this.runDebounceTimer !== null) { return } this.runDebounceTimer = setTimeout(()=>{ this.runDebounceTimer = null }, 100) if (this._currentScript.isROLib) { return } // stop any currently-running script this.stopCurrentScript() this.clearAllMetaInfo() let stopCallback = () => { this.stopCurrentScript() } toolbar.addStopCallback(stopCallback) // let runqItem = runqueue.push() // compiling a script may take a long time when run just after Scripter is opened, // as the typescript worker sometimes takes a little while to start. toolbar.incrWaitCount() let prog :ScriptProgram try { prog = await this.compileCurrentScript() } finally { toolbar.decrWaitCount() } if (prog.code.length > 0) { try { this.currentEvalPromise = Eval.run(prog.code, prog.sourceMap) await this.currentEvalPromise // runqItem.clearWithStatus("ok") } catch (err) { // runqItem.clearWithStatus("error") } this.currentEvalPromise = null this.viewZones.clearAllUIInputs() } toolbar.removeStopCallback(stopCallback) clearTimeout(this.runDebounceTimer) this.runDebounceTimer = null this.editor.focus() } isScriptRunning() :bool { return !!this.currentEvalPromise } stopCurrentScript() { dlog("stopCurrentScript") if (this.currentEvalPromise) { this.currentEvalPromise.cancel() } this.viewZones.clearAllUIInputs() // Note: Intentionally not calling clearHoverCards() } async compileCurrentScript() :Promise<ScriptProgram> { interface EmitOutput { outputFiles: { name: string; writeByteOrderMark: boolean; text: string; }[]; emitSkipped: boolean; } // interface OutputFile { // name: string; // writeByteOrderMark: boolean; // text: string; // } let result :EmitOutput let model = this.currentModel try { lockModel(model) let tsworkerForModel = await monaco.languages.typescript.getTypeScriptWorker() let tsclient = await tsworkerForModel(model.uri) result = await tsclient.getEmitOutput(model.uri.toString()) as EmitOutput } finally { unlockModel(model) } let prog :ScriptProgram = { code: "", sourceMap: "" } if (result.outputFiles && result.outputFiles.length) { for (let f of result.outputFiles) { if (/\.map$/.test(f.name)) { prog.sourceMap = f.text } else { prog.code = f.text } } } return prog } // ---------------------------------------------------------------------------------- // Decorations clearAllMetaInfo() { warningMessage.hide() this.clearAllDecorations() this.viewZones.clearAll() this.clearHoverCards() } clearMessages() { this.clearAllDecorations() this.viewZones.clearAll() this.editor.focus() } clearHoverCards() { if (this.options.hover.enabled) { let options = { ...this.options, hover: { enabled: false } } this.editor.updateOptions(options) requestAnimationFrame(() => this.editor.updateOptions(this.options)) } } clearAllDecorations() { this.decorationCallbacks.clear() this.editor.deltaDecorations(this.editorDecorationIds, []) this.editorDecorationIds = [] this.triggerEvent("decorationchange") } removeDecorations(ids :string[]) { let idset = new Set(ids) this.editorDecorationIds = this.editorDecorationIds.filter(id => !idset.has(id)) for (let id of ids) { this.decorationCallbacks.delete(id) } this.editor.deltaDecorations(ids, []) this.triggerEvent("decorationchange") } addDecorations( decorations :monaco.editor.IModelDeltaDecoration[], callback? :DecoratedTextChangedCallback, ) { let ids = this.editor.deltaDecorations([], decorations) if (this.editorDecorationIds.length > 0) { this.editorDecorationIds = this.editorDecorationIds.concat(ids) } else { this.editorDecorationIds = ids this.startObservingChanges() } if (callback) { for (let id of ids) { this.decorationCallbacks.set(id, callback) } } this.triggerEvent("decorationchange") } decorateError(pos :SourcePos, message :string) { setTimeout(() => { this.editor.revealLineInCenterIfOutsideViewport(pos.line, monaco.editor.ScrollType.Smooth) }, 1) this.addDecorations([{ range: new monaco.Range( pos.line, pos.column + 1, pos.line, pos.column + 999 ), options: { className: 'runtimeErrorDecoration', stickiness: monaco.editor.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges, hoverMessage: { // markdown value: "**Runtime error:** `" + message + "`", isTrusted: true, }, overviewRuler: { position: monaco.editor.OverviewRulerLane.Full, color: "rgba(255,200,0,0.5)", }, // isWholeLine: true, // glyphMarginClassName: 'errorGlyphMargin', } }], (d :monaco.editor.IModelDecoration) => { // decorated text changed this.removeDecorations([d.id]) warningMessage.hide() }) } // ---------------------------------------------------------------------------------- // Observing changes to the script code _changeObservationRefCount = 0 stopObservingChanges() { if (this._changeObservationRefCount == 0) { throw new Error("unbalanced call to stopObservingChanges") } this._changeObservationRefCount-- if (this._changeObservationRefCount == 0) { this.changeObservationActive = false this.changeObservationLastLineCount = 0 } } startObservingChanges() { this._changeObservationRefCount++ if (this._changeObservationRefCount > 1) { return } if (!this.changeObservationActive) { this.changeObservationActive = true this.changeObservationLastLineCount = this.currentModel.getLineCount() } if (this.changeObservationEnabled) { return } this.changeObservationEnabled = true this.editor.onDidChangeModelContent((e: monaco.editor.IModelContentChangedEvent) => { this.updateHiddenAreas() if (e.isFlush) { // is reset this.clearAllMetaInfo() return } if (!this.changeObservationActive) { // inactive return } // compute line delta (effective number of lines added or removed) let lineCount = this.currentModel.getLineCount() let lineDelta = lineCount - this.changeObservationLastLineCount this.changeObservationLastLineCount = lineCount // compute maxium line range of all changes let startLine = Infinity let startColumn = 0 let endLine = 0 let endColumn = 999999 for (let c of e.changes) { if (c.range.startLineNumber < startLine) { startLine = c.range.startLineNumber startColumn = c.range.startColumn } if (c.range.endLineNumber > endLine) { endLine = c.range.endLineNumber endColumn = c.range.endColumn } } let flags :ModelChangeFlags = ModelChangeFlags.NONE // single simple change? if (e.changes.length == 1) { let c = e.changes[0] let r = c.range if (c.text == "") { // Deletion // TODO: check for actual line removal and set ModelChangeFlags.REMOVE_LINE // Currently we don't use REMOVE_LINE apart from in conjunction with LAST_LINE_INTACT, // but maybe on day we will. if (endColumn == 1) { // dlog("removed line(s) at the beginning of a line") // reduce change to lastLine -1 flags |= ModelChangeFlags.REMOVE_LINE flags |= ModelChangeFlags.LAST_LINE_INTACT if (endLine == startLine) { console.warn("[scripter] unexpected condition: endLine == startLine") } } } else /*if (c.rangeLength == 0)*/ { // let endLineEndCol = this.currentModel.getLineLength(endLine) // dlog("endLineEndCol", endLineEndCol) // if (endColumn == 1) { let lastch = c.text.charCodeAt(c.text.length - 1) if (lastch == 0x0A || lastch == 0x0D) { // \n || \r flags |= ModelChangeFlags.ADD_LINE if (endColumn == 1) { // dlog("added line(s) at the beginning") flags |= ModelChangeFlags.LAST_LINE_INTACT } } // } // Note: We don't track adding lines at the end } } // dlog("change flags", ModelChangeFlagsString(flags)) // update zones this.viewZones.updateAfterEdit(startLine, startColumn, endLine, endColumn, lineDelta, flags) // update decorations for (let c of e.changes) { // expand change range to whole line let range = { startLineNumber: c.range.startLineNumber, startColumn: 0, endLineNumber: c.range.endLineNumber, endColumn: 99999, } let decorations = this.currentModel.getDecorationsInRange(range) // let decorations = this.editor.getLineDecorations(e.changes[0].range.startLineNumber) for (let d of decorations) { let callback = this.decorationCallbacks.get(d.id) if (callback) { callback(d) } } } }) } // -------------------------------------------------------------------------------------------- // Diagnostics _semdiag = new Map<EditorModel,any[]>() async getSemanticDiagnostics(model :EditorModel) :Promise<any[]> { let d = this._semdiag.get(model) if (!d) { try { lockModel(model) // request diagnostics from TypeScript. // This usually takes a few milliseconds unfortunatently, leading to a // "blinking" effect of error markers. let tsworker = await monaco.languages.typescript.getTypeScriptWorker() let tsclient = await tsworker(model.uri) d = await tsclient.getSemanticDiagnostics(model.uri.toString()) this._semdiag.set(model, d) } finally { unlockModel(model) } } return d } async invalidateDiagnostics(model :EditorModel) { this._semdiag.delete(model) } // -------------------------------------------------------------------------------------------- // Helper functions _measureEl :HTMLElement|null = null // measureHTMLElement places el into a hidden element of the editor that is as large as the // editor itself with absolute positioning. // Returns the effective clientWidth and clientHeight of el. // // You can set el.style.width or el.style.height before calling this if you want to constrain // one of the axes. // measureHTMLElement(el :HTMLElement) :{width:number, height:number} { let measureEl = this._measureEl if (!measureEl) { measureEl = document.createElement("div") measureEl.style.position = "absolute" measureEl.style.visibility = "hidden" measureEl.style.pointerEvents = "none" document.getElementById("editor").appendChild(measureEl) this._measureEl = measureEl } if (measureEl.children.length > 0) { measureEl.innerText = "" } let position = el.style.position el.style.position = "absolute" measureEl.appendChild(el) let size = { width: el.clientWidth, height: el.clientHeight } measureEl.removeChild(el) el.style.position = position return size } // -------------------------------------------------------------------------------------------- // history & file navigation readonly navigationHistory = new NavigationHistory<EditorHistoryEntry>() historyLoadVersion = 0 // used to avoid races to unloaded scripts async initHistory() { // load preexisting history type Snapshot = NavigationHistorySnapshot<EditorHistoryEntry> const snap = await db.get<Snapshot>("history", "navigationHistory") if (snap) { dlog("editor restoring navigationHistory", snap) this.navigationHistory.restoreSnapshot(snap) } // save history let storeTimer :any = null let storeNow = () => { clearTimeout(storeTimer) storeTimer = null const snap = this.navigationHistory.createSnapshot() db.put("history", snap, "navigationHistory").then(() => { dlog("editor saved navigationHistory") }) } app.on("close", storeNow) this.navigationHistory.on("change", () => { if (storeTimer === null) { storeTimer = setTimeout(storeNow, 300) } }) // // when built in debug mode, visualize the history stack as it changes // if (DEBUG) this.navigationHistory.on("change", () => { // dlog(`current history stack: (cursor=${this.navigationHistory.cursor})\n` + // this.navigationHistory.stack.map((e, i) => { // let s = i == this.navigationHistory.cursor ? ">" : " " // return `${s} stack[${i}] = ${e.scriptGUID}` // }).join("\n")) // }) } historySwitchToScript(guid :string) :boolean { let script = scriptsData.scriptsByGUID.get(guid) if (!script) { return false } let v = ++this.historyLoadVersion script.whenLoaded(() => { if (this.historyLoadVersion == v) { this.setCurrentScript(script) } }) return true } historyBack() { if (!this.navigationHistory.canGoBack()) { return } while (1) { let e = this.navigationHistory.goBack() dlog("editor/historyBack; this.navigationHistory.goBack() =>", e) if (!e) { break } if (this.historySwitchToScript(e.scriptGUID)) { break } // else "keep going back" until there's is back entry with a valid script } } historyForward() { if (!this.navigationHistory.canGoForward()) { return } while (1) { let e = this.navigationHistory.goForward() dlog("editor/historyForward; this.navigationHistory.goForward() =>", e) if (!e) { break } if (this.historySwitchToScript(e.scriptGUID)) { break } // else "keep going forward" until there's is back entry with a valid script } } historyPush() { let e = this.navigationHistory.currentEntry if (!e || e.scriptGUID != this._currentScript.guid) { e = { scriptGUID: this._currentScript.guid } dlog("editor/historyPush =>", e) this.navigationHistory.push(e) } else { dlog("editor/historyPush ignore (script already current)") } } async monacoOpenCodeEditor( input :OpenCodeEditorInput, editor :MonacoEditor, ) :Promise<MonacoEditor|null> { // This function is called by the Monaco EditorService when a user requests to switch // to a file, for example via "Jump to Definition". if (editor !== this.editor) { dlog("monacoOpenCodeEditor got unexpected editor object (!== this.editor)", editor) return null } //dlog("onOpenCodeEditor", input, editor) if (!input.resource) { return null } let model = monaco.editor.getModel(input.resource) if (!model) { return null } let script = model[kScript] as Script|undefined if (!script) { return null } this.setCurrentScriptFromUserAction(script) // this block lifted from monaco's StandaloneCodeEditorServiceImpl: let selection = (input.options && input.options.selection) || null if (selection) { // dlog("set selection in model", model.uri.toString()) let setSelection = () => { if (typeof selection.endLineNumber === 'number' && typeof selection.endColumn === 'number' ) { editor.setSelection(selection); editor.revealRangeInCenter(selection, monaco.editor.ScrollType.Immediate); } else { let pos = { lineNumber: selection.startLineNumber, column: selection.startColumn } editor.setPosition(pos); editor.revealPositionInCenter(pos, monaco.editor.ScrollType.Immediate) } } setSelection() // workaround for bug in monaco where if the position of a model has been set // recently without edits, then "Immediate" mode setPosition has no effect in same // runloop frame. Oh, web technology... setTimeout(setSelection, 1) } return editor } // -------------------------------------------------------------------------------------------- // editor initialization async init() { this.initTypescript() // intentionally not awaiting const initHistoryPromise = this.initHistory() // load past code buffer let script = await loadLastOpenedScript() let model = this.setCurrentScript(script) // add the script to history. Note that this has no effect if the current script // is already at the top of the history stack. initHistoryPromise.then(() => this.historyPush()) // setup options from config this.updateOptionsFromConfig() // Monaco is created to be a stand-alone single editor, but really it is VSCode, a // full-featured multi-file editor. Patch the StaticServices.codeEditorService component of // monaco. // Note: With Monaco v0.20.0 there appears to be a bug in the meachnics underlying the // third argument "override" to editor.create. Internally (StaticServices.init) a Map is used // instead of an object with keys that are wrapped in functions with a toString method. // That implementation assumes the toString method is called implicitly by the map container, // but the new Map object keys on any object! This means that services can not be overridden. // Thus, we patch the prototype of the editor service instead of using service overrides. __scripterMonaco.patchEditorService(this.monacoOpenCodeEditor.bind(this)) // This patch enables "Find All References" __scripterMonaco.patchEditorModelResolverService((editor, uri) => { return monaco.editor.getModel(uri) }) // returns a label for a resource. // Shows up as a tool tip and small text next to the filename __scripterMonaco.patchUriLabelService((uri, options) => { let model = monaco.editor.getModel(uri) if (model) { let script = model[kScript] as Script|undefined if (script) { return script.name } } if (uri.scheme === 'file') { return uri.fsPath } return uri.path }) // Show script names instead of their filenames __scripterMonaco.patchBasenameOrAuthority(uri => { if (uri && uri.path.indexOf("scripter.") != -1) { let model = monaco.editor.getModel(uri) let script = model[kScript] as Script|undefined if (script) { return script.name } } }) // create editor this.editor = monaco.editor.create(document.getElementById('editor')!, { model, theme: 'scripter-light', ...this.options, readOnly: script.isROLib, }) this.updateHiddenAreas() this.initEditorActions() // restore editor view state this.restoreViewState() // initialize model this.initEditorModel(model) // layout and focus const layoutAndFocus = () => { monaco.editor.remeasureFonts() this.editor.layout() this.editor.focus() } layoutAndFocus() // OH COME ON MONACO... setTimeout(layoutAndFocus, 100) setTimeout(layoutAndFocus, 500) // initialize event handlers this.initEditorEventHandlers() // load libs await scriptsData.libLoadPromise for (let s of scriptsData.referenceScripts) { this.getModel(s) } // // if we made a new script for the first time, save it immediately // if (this._currentScript.id == 0) { // this._currentScript.save() // } // hook up config config.on("change", () => { this.updateOptionsFromConfig() }) menu.menuUIMountPromise.then(() => { menu.scrollToActiveItem() requestAnimationFrame(() => { menu.scrollToActiveItem() }) }) // // DEBUG print compiled JS code // compileCurrentScript().then(r => print(r.outputFiles[0].text)) // // DEBUG ts // ;(async () => { // let model = this.editor.getModel() // let tsworker = await monaco.languages.typescript.getTypeScriptWorker() // let tsclient = await tsworker(model.uri) // print("tsworker", tsworker) // print("tsclient", tsclient) // let uri = model.uri.toString() // print("tsclient.getCompilerOptionsDiagnostics()", // await tsclient.getCompilerOptionsDiagnostics(uri)) // print("tsclient.getSemanticDiagnostics()", await tsclient.getSemanticDiagnostics(uri)) // // print("tsclient.getCompilationSettings()", await tsclient.getCompilationSettings(uri)) // })() this.isInitialized = true this.triggerEvent("init") this.triggerEvent("modelchange") this._editorPromiseResolve(this.editor) ;(this as any)._editorPromiseResolve = null } // init() updateHiddenAreas() { // Sad hack to work around isolating scripts. // Many many hours went into finding a better solution than this. // Ultimately this is the simples and most reliable approach. Monaco synchronizes // state with the TS worker, so simply patching the code in the TS worker would cause // the editor to go bananas. // // IMPORTANT: This function MUST NOT MODIFY THE MODEL CONTENTS. // If it does, it would cause an infinite loop. // If this is ever needed, change onDidChangeModelContent as appropriate. // if (DEBUG) { if (!(this.editor as any).setHiddenAreas) { console.error("MONACO issue: editor.setHiddenAreas not found!") } } let hiddenAreas :monaco.Range[] = [] this._lineNumberOffset = 0 if (!this._currentScript.isROLib) { let model = this._currentModel let lastLine = model.getLineCount() hiddenAreas = [ // Range(startLineNumber, startColumn, endLineNumber, endColumn) new monaco.Range(1, 1, 1, 1), new monaco.Range(lastLine, 1, lastLine, 1), ] this._lineNumberOffset = 1 } ;(this as any).hiddenAreas = hiddenAreas // since readonly for outside if (!DEBUG_HIDDEN_AREAS) { ;(this.editor as any).setHiddenAreas(hiddenAreas) } this.adjustSelection() } // makes sure there is a line break after the last line; an extra blank line at the end // for view zones, like print output on last line ensureTrailingNewline() { const lastVisibleLineno = this.currentModel.getLineCount() - 1 const lastVisibleLineContent = this.currentModel.getLineContent(lastVisibleLineno) if (lastVisibleLineContent.trim().length > 0) { console.log({lastVisibleLineContent}) // add linebreak after last visible line. // save & restore view state to avoid persisting temporary scroll & selection changes const viewState = this.editor.saveViewState() this.currentModel.applyEdits([{ // IIdentifiedSingleEditOperation[] range: new monaco.Range(lastVisibleLineno, Infinity, lastVisibleLineno, Infinity), text: "\n", forceMoveMarkers: false, }]) this.editor.restoreViewState(viewState) } } initEditorActions() { this.editor.addAction({ id: 'scripter-run-script', label: 'Run Script', keybindings: [ monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter, ], contextMenuGroupId: "navigation", // 1_modification contextMenuOrder: 0, run: editor => { this.runCurrentScript() return null } }) // // var myCondition1 = this.editor.createContextKey('editorHasCompletionItemProvider', false) // // var myCondition2 = this.editor.createContextKey('editorReadonly', false) // // this.editor.createContextKey('textInputFocus', false) // this.editor.addCommand(monaco.KeyCode.Escape, (ctx :any) => { // // services available in `ctx` // console.log('my command is executing!', {ctx}) // // editor.getSupportedActions() // }, 'editorHasCompletionItemProvider && !editorReadonly && textInputFocus') // monaco.languages.registerCompletionItemProvider('typescript', { // provideCompletionItems(model, position, context, token) { // token.onCancellationRequested(e => { // dlog("CANCEL") // }) // dlog("SUGGEST", model) // return new Promise(r => {}) // } // }) // this.editor.addAction({ // id: "scripter-stop-script", // label: "Stop Script", // // precondition: "scripter-script-running", // TODO: figure out how this works // keybindings: [ // // Note: There's a bug in monaco where the following causes cmd-X to stop working: // // monaco.KeyMod.CtrlCmd | monaco.KeyCode.Shift | monaco.KeyCode.KEY_X, // ], // contextMenuGroupId: "navigation", // contextMenuOrder: 0, // run: editor => { // this.stopCurrentScript() // return null // } // }) } adjustSelection() { const hiddenAreas = this.hiddenAreas if (hiddenAreas.length == 0 || !this.editor) { return } // Note: This assumes hiddenAreas.length == 2 let sels = this.editor.getSelections() // Selection[] | null; if (!sels || sels.length == 0) { return } let [header, ] = hiddenAreas let changed = false let footerLine = this._currentModel.getLineCount() for (let i = 0; i < sels.length; i++) { let sel = sels[i] if (sel.startLineNumber <= header.endLineNumber) { // inside header if (DEBUG_HIDDEN_AREAS) { dlog("sel.startLineNumber <= header.endLineNumber", sel.startLineNumber, "<=", header.endLineNumber) } sels[i] = sel = sel.setStartPosition(header.endLineNumber + 1, 1) changed = true } if (sel.endLineNumber >= footerLine) { // inside footer if (DEBUG_HIDDEN_AREAS) { dlog("sel.endLineNumber >= footerLine", sel.endLineNumber, "<=", footerLine) } sels[i] = sel = sel.setEndPosition(footerLine - 1, 1) changed = true } } if (changed) { if (DEBUG_HIDDEN_AREAS) { dlog("patch selection (DEBUG_HIDDEN_AREAS)", this.editor.getSelections(), "=>", sels) } else { dlog("patch selection (set DEBUG_HIDDEN_AREAS=true to debug)", sels) } this.editor.setSelections(sels) } } initEditorEventHandlers() { const editor = this.editor let isRestoringViewState = false let isRestoringModel = false editor.onDidChangeModelContent((e: monaco.editor.IModelContentChangedEvent) :void => { // Note: getAlternativeVersionId is a version number that tracks undo/redo. // i.e. version=1; edit -> version=2; undo -> version=1. if (!isRestoringModel && !this._isSwitchingModel) { const script = this._currentScript if (script.isUserScript) { script.updateBody( this._currentModel.getValue(), this._currentModel.getAlternativeVersionId() ) } else { // create a new script that is a duplicate let s2 = script.duplicate({ name: "Copy of " + script.name }) // apply the edit to the new user script copy, but use the "no dirty" variant of // the updateBody function. This has the effect that a new _unsaved_ script is added // containing the edits that triggered this code here to run. s2.updateBodyNoDirty( this._currentModel.getValue(), this._currentModel.getAlternativeVersionId() ) // undo the edit in the example script model isRestoringModel = true editor.trigger('', 'undo', {}) isRestoringModel = false // set the new duplicate script this.setCurrentScriptFromUserAction(s2) } } if (e.isFlush) { this.updateHiddenAreas() } }) editor.onDidChangeCursorSelection((e: monaco.editor.ICursorSelectionChangedEvent) :void => { // possibly correct for hiddenAreas this.adjustSelection() if (!isRestoringViewState && !isRestoringModel) { this.setNeedsSaveViewState() } }) editor.onDidChangeModel((e: monaco.editor.IModelChangedEvent) :void => { if (e.newModelUrl) { this.triggerEvent("modelchange") } // this.stopObservingChanges() }) // some key presses causes the toolbar to fade out (only when menu is closed) const ignoreKeyPresses = { [monaco.KeyCode.Alt]:1, [monaco.KeyCode.Shift]:1, [monaco.KeyCode.Ctrl]:1, [monaco.KeyCode.Meta]:1, [monaco.KeyCode.ContextMenu]:1, } editor.onKeyDown((e: monaco.IKeyboardEvent) => { // fade out toolbar if (!(e.keyCode in ignoreKeyPresses)) { toolbar.fadeOut() } }) // // DEBUG dump all actions // setTimeout(() => { // dlog("editor.getSupportedActions():", editor.getSupportedActions()) // },1000) // shift-cmd-P / shift-ctrl-P for quick command in addition to F1 editor.addCommand( monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.KEY_P, (ctx :any) => { editor.trigger('', 'editor.action.quickCommand', {}) } ) // built-in key command is buggy editor.addCommand( monaco.KeyCode.F1, (ctx :any) => { editor.trigger('', 'editor.action.quickCommand', {}) } ) // cmd-P -- go to symbol editor.addCommand( monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_P, (ctx :any) => { editor.trigger('', 'editor.action.quickOutline', {}) } ) // go to definition // Note: shows "peek definition" instead when there are many defs. editor.addCommand( monaco.KeyCode.F12, (ctx :any) => { editor.trigger('', 'editor.action.revealDefinition', {}) } ) editor.addCommand( monaco.KeyCode.F11, (ctx :any) => { editor.trigger('', 'editor.action.peekDefinition', {}) } ) // cmd-alt-/ -- toggle block comment editor.addCommand( monaco.KeyMod.CtrlCmd | monaco.KeyMod.Alt | monaco.KeyCode.US_SLASH, (ctx :any) => { editor.trigger('', 'editor.action.blockComment', {}) } ) // handle changes to the database that were made by another tab db.on("remotechange", async ev => { if (ev.type == "update") { if (ev.store == "scriptViewState" && ev.key == this._currentScript.id) { // view state of currently-open script changed in another tab let viewState = await this._currentScript.reloadEditorViewState() isRestoringViewState = true editor.restoreViewState(viewState) isRestoringViewState = false } else if (ev.store == "scriptBody" && ev.key == this._currentScript.id) { // script data of currently-open script changed await this._currentScript.load() isRestoringModel = true isRestoringViewState = true this._currentModel.setValue(this._currentScript.body) editor.restoreViewState(this._currentScript.editorViewState) isRestoringModel = false isRestoringViewState = false } else if (ev.store == "scripts") { // script index changed. e.g. a script was added or removed scriptsData.refresh() } } }) window.addEventListener("resize", () => { this.editor.layout() setTimeout(() => this.editor.layout(), 100) }) } async initTypescript() { let ts = monaco.languages.typescript.typescriptDefaults ts.setMaximumWorkerIdleTime(1000 * 60 * 60 * 24) // kill worker after 1 day ts.setCompilerOptions(typescriptCompilerOptions) // ts.setDiagnosticsOptions({noSemanticValidation:true}) ts.setEagerModelSync(true) // ts.onDidChange(e => { // dlog("ts onDidChange", e) // }) } initEditorModel(model :EditorModel) { // filter out some errors let lastSeenMarkers :monaco.editor.IMarker[] = [] let onDidChangeDecorationsCallbackRunning = false model.onWillDispose(() => { model.onDidChangeDecorations(() => {}) model.onWillDispose(() => {}) editor.invalidateDiagnostics(model) }) model.onDidChangeDecorations(async ev => { if (onDidChangeDecorationsCallbackRunning) { // print("onDidChangeDecorations: onDidChangeDecorationsCallbackRunning -- ignore") return } onDidChangeDecorationsCallbackRunning = true try { // print("model.onDidChangeDecorations", ev) // let decs = model.getAllDecorations(0/* 0 = owner id of primary editor */) // if (decs.length == 0) { // return // } // print("decs", decs) // check if markers have changed let markers = monaco.editor.getModelMarkers({ owner: "typescript" }) if (markers.length == 0 || markers === lastSeenMarkers) { return } if (markers.length == lastSeenMarkers.length) { let diff = false for (let i = 0; i < markers.length; i++) { if (markers[i] !== lastSeenMarkers[i]) { diff = true break } } if (!diff) { // print("no change to markers") return } } lastSeenMarkers = markers // okay, markers did change. // filter out certain diagnostics const filterRe = /['"]?return['"]? statement can only be used within a function body/i let initialLen = markers.length let semdiag :any[]|null = null let origIndex = 0 for (let i = 0; i < markers.length; origIndex++) { let m = markers[i] if (filterRe.test(m.message)) { markers.splice(i, 1) continue } // await at top level is tricky to identify as the same TS code is used for both // top-level and function-level, the latter which is a valid error in Scripter. if (m.message.indexOf("'await'") != -1) { if (semdiag === null) { // request diagnostics from TypeScript semdiag = await editor.getSemanticDiagnostics(model) } // here, we rely on the fact that markers in Monaco are ordered the same as // semantic diagnostics in TypeScript, which _might_ not be true. let diag :any for (let d of semdiag) { if (d.messageText == m.message) { diag = d break } } if (diag && diag.code == 1308 && !diag.relatedInformation) { // TS1308 is "'await' expression is only allowed within an async function." // when this is at the top-level, there's no related information. markers.splice(i, 1) continue } } else if (m.message.indexOf("'for-await-of'") != -1) { // top-level for-await-of e.g. "for await (let r of asyncIterable()) { ... }" markers.splice(i, 1) continue } // keep i++ } // print("markers", markers, initialLen != markers.length) if (initialLen != markers.length) { monaco.editor.setModelMarkers(model, "typescript", markers) } // TODO: consider enriching the hover thingy. // The following _adds_ information to a hover card. // monaco.languages.registerHoverProvider('typescript', { // provideHover: function (model, position) { // // note: can return a promise // // return null // dlog("position", position) // return { // range: new monaco.Range( // position.lineNumber, position.column, // position.lineNumber, position.column + 999, // // 1, 1, // // model.getLineCount(), model.getLineMaxColumn(model.getLineCount()) // ), // contents: [ // { value: '**SOURCE**' }, // { value: '```html\nHELLO <WORLD>\n```' } // ] // } // } // }) } finally { onDidChangeDecorationsCallbackRunning = false } }) // onDidChangeDecorations } // initEditorModel() } export const editor = new EditorState() async function loadLastOpenedScript() :Promise<Script> { let script :Script|null = null let guid = config.lastOpenScriptGUID try { if (guid != "") { script = await scriptsData.getScriptByGUID(guid) } else if (config.lastOpenScript != 0) { // try legacy numeric id script = await scriptsData.getScript(config.lastOpenScript) } } catch (err) { console.error(`failed to reopen last open script:`, err.stack) } if (!script) { if (scriptsData.scripts.length) { let id = 0 for (let s of scriptsData.scripts) { if (s.id != 0) { id = s.id break } } if (id != 0) { script = await scriptsData.getScript(id) } } } if (!script) { script = scriptsData.defaultSampleScript // script = Script.createDefault() } return script } // prevents model from being disposed. Must be balanced with a later call to unlockModel(). function lockModel(m :EditorModel) { // dlog(`lockModel ${m.id}`) // ;(m as any)[kLocked] = true // ;(m as any)[kOnUnlock] = [] } // function awaitUnlockedModel(m :EditorModel) :Promise<void> { // return new Promise(resolve => { // if (!(m as any)[kLocked]) { // resolve() // } else { // (m as any)[kOnUnlock].push(resolve) // } // }) // } // allows model to be disposed. function unlockModel(m :EditorModel) { // dlog(`unlockModel ${m.id}`) // if ((m as any)[kLocked]) { // for (let f of (m as any)[kOnUnlock]) { // try { f() } catch(err) { console.error(err.stack||String(err)) } // } // delete (m as any)[kLocked] // delete (m as any)[kOnUnlock] // } }
the_stack
import { BufferGeometry, Matrix3, Mesh, Object3D, Vector3 } from 'three' /** * https://github.com/gkjohnson/ply-exporter-js * * Usage: * const exporter = new PLYExporter(); * * // second argument is a list of options * exporter.parse(mesh, data => console.log(data), { binary: true, excludeAttributes: [ 'color' ], littleEndian: true }); * * Format Definition: * http://paulbourke.net/dataformats/ply/ */ export interface PLYExporterOptions { binary?: boolean excludeAttributes?: string[] littleEndian?: boolean } class PLYExporter { public parse( object: Object3D, onDone: ((res: string) => void) | undefined, options: PLYExporterOptions, ): string | ArrayBuffer | null { if (onDone && typeof onDone === 'object') { console.warn( 'THREE.PLYExporter: The options parameter is now the third argument to the "parse" function. See the documentation for the new API.', ) options = onDone onDone = undefined } // Default options const defaultOptions = { binary: false, excludeAttributes: [], // normal, uv, color, index littleEndian: false, } options = Object.assign(defaultOptions, options) const excludeAttributes = options.excludeAttributes let includeNormals = false let includeColors = false let includeUVs = false // count the vertices, check which properties are used, // and cache the BufferGeometry let vertexCount = 0 let faceCount = 0 object.traverse(function (child) { if (child instanceof Mesh && child.isMesh) { const mesh = child const geometry = mesh.geometry if (!geometry.isBufferGeometry) { throw new Error('THREE.PLYExporter: Geometry is not of type THREE.BufferGeometry.') } const vertices = geometry.getAttribute('position') const normals = geometry.getAttribute('normal') const uvs = geometry.getAttribute('uv') const colors = geometry.getAttribute('color') const indices = geometry.getIndex() if (vertices === undefined) { return } vertexCount += vertices.count faceCount += indices ? indices.count / 3 : vertices.count / 3 if (normals !== undefined) includeNormals = true if (uvs !== undefined) includeUVs = true if (colors !== undefined) includeColors = true } }) const includeIndices = excludeAttributes?.indexOf('index') === -1 includeNormals = includeNormals && excludeAttributes?.indexOf('normal') === -1 includeColors = includeColors && excludeAttributes?.indexOf('color') === -1 includeUVs = includeUVs && excludeAttributes?.indexOf('uv') === -1 if (includeIndices && faceCount !== Math.floor(faceCount)) { // point cloud meshes will not have an index array and may not have a // number of vertices that is divisble by 3 (and therefore representable // as triangles) console.error( 'PLYExporter: Failed to generate a valid PLY file with triangle indices because the ' + 'number of indices is not divisible by 3.', ) return null } const indexByteCount = 4 let header = 'ply\n' + `format ${ options.binary ? (options.littleEndian ? 'binary_little_endian' : 'binary_big_endian') : 'ascii' } 1.0\n` + `element vertex ${vertexCount}\n` + // position 'property float x\n' + 'property float y\n' + 'property float z\n' if (includeNormals) { // normal header += 'property float nx\n' + 'property float ny\n' + 'property float nz\n' } if (includeUVs) { // uvs header += 'property float s\n' + 'property float t\n' } if (includeColors) { // colors header += 'property uchar red\n' + 'property uchar green\n' + 'property uchar blue\n' } if (includeIndices) { // faces header += `${`element face ${faceCount}\n`}property list uchar int vertex_index\n` } header += 'end_header\n' // Generate attribute data const vertex = new Vector3() const normalMatrixWorld = new Matrix3() let result: string | ArrayBuffer | null = null if (options.binary) { // Binary File Generation const headerBin = new TextEncoder().encode(header) // 3 position values at 4 bytes // 3 normal values at 4 bytes // 3 color channels with 1 byte // 2 uv values at 4 bytes const vertexListLength = vertexCount * (4 * 3 + (includeNormals ? 4 * 3 : 0) + (includeColors ? 3 : 0) + (includeUVs ? 4 * 2 : 0)) // 1 byte shape desciptor // 3 vertex indices at ${indexByteCount} bytes const faceListLength = includeIndices ? faceCount * (indexByteCount * 3 + 1) : 0 const output = new DataView(new ArrayBuffer(headerBin.length + vertexListLength + faceListLength)) new Uint8Array(output.buffer).set(headerBin, 0) let vOffset = headerBin.length let fOffset = headerBin.length + vertexListLength let writtenVertices = 0 this.traverseMeshes(object, function (mesh, geometry) { const vertices = geometry.getAttribute('position') const normals = geometry.getAttribute('normal') const uvs = geometry.getAttribute('uv') const colors = geometry.getAttribute('color') const indices = geometry.getIndex() normalMatrixWorld.getNormalMatrix(mesh.matrixWorld) for (let i = 0, l = vertices.count; i < l; i++) { vertex.x = vertices.getX(i) vertex.y = vertices.getY(i) vertex.z = vertices.getZ(i) vertex.applyMatrix4(mesh.matrixWorld) // Position information output.setFloat32(vOffset, vertex.x, options.littleEndian) vOffset += 4 output.setFloat32(vOffset, vertex.y, options.littleEndian) vOffset += 4 output.setFloat32(vOffset, vertex.z, options.littleEndian) vOffset += 4 // Normal information if (includeNormals) { if (normals != null) { vertex.x = normals.getX(i) vertex.y = normals.getY(i) vertex.z = normals.getZ(i) vertex.applyMatrix3(normalMatrixWorld).normalize() output.setFloat32(vOffset, vertex.x, options.littleEndian) vOffset += 4 output.setFloat32(vOffset, vertex.y, options.littleEndian) vOffset += 4 output.setFloat32(vOffset, vertex.z, options.littleEndian) vOffset += 4 } else { output.setFloat32(vOffset, 0, options.littleEndian) vOffset += 4 output.setFloat32(vOffset, 0, options.littleEndian) vOffset += 4 output.setFloat32(vOffset, 0, options.littleEndian) vOffset += 4 } } // UV information if (includeUVs) { if (uvs != null) { output.setFloat32(vOffset, uvs.getX(i), options.littleEndian) vOffset += 4 output.setFloat32(vOffset, uvs.getY(i), options.littleEndian) vOffset += 4 } else if (!includeUVs) { output.setFloat32(vOffset, 0, options.littleEndian) vOffset += 4 output.setFloat32(vOffset, 0, options.littleEndian) vOffset += 4 } } // Color information if (includeColors) { if (colors != null) { output.setUint8(vOffset, Math.floor(colors.getX(i) * 255)) vOffset += 1 output.setUint8(vOffset, Math.floor(colors.getY(i) * 255)) vOffset += 1 output.setUint8(vOffset, Math.floor(colors.getZ(i) * 255)) vOffset += 1 } else { output.setUint8(vOffset, 255) vOffset += 1 output.setUint8(vOffset, 255) vOffset += 1 output.setUint8(vOffset, 255) vOffset += 1 } } } if (includeIndices) { // Create the face list if (indices !== null) { for (let i = 0, l = indices.count; i < l; i += 3) { output.setUint8(fOffset, 3) fOffset += 1 output.setUint32(fOffset, indices.getX(i + 0) + writtenVertices, options.littleEndian) fOffset += indexByteCount output.setUint32(fOffset, indices.getX(i + 1) + writtenVertices, options.littleEndian) fOffset += indexByteCount output.setUint32(fOffset, indices.getX(i + 2) + writtenVertices, options.littleEndian) fOffset += indexByteCount } } else { for (let i = 0, l = vertices.count; i < l; i += 3) { output.setUint8(fOffset, 3) fOffset += 1 output.setUint32(fOffset, writtenVertices + i, options.littleEndian) fOffset += indexByteCount output.setUint32(fOffset, writtenVertices + i + 1, options.littleEndian) fOffset += indexByteCount output.setUint32(fOffset, writtenVertices + i + 2, options.littleEndian) fOffset += indexByteCount } } } // Save the amount of verts we've already written so we can offset // the face index on the next mesh writtenVertices += vertices.count }) result = output.buffer } else { // Ascii File Generation // count the number of vertices let writtenVertices = 0 let vertexList = '' let faceList = '' this.traverseMeshes(object, function (mesh, geometry) { const vertices = geometry.getAttribute('position') const normals = geometry.getAttribute('normal') const uvs = geometry.getAttribute('uv') const colors = geometry.getAttribute('color') const indices = geometry.getIndex() normalMatrixWorld.getNormalMatrix(mesh.matrixWorld) // form each line for (let i = 0, l = vertices.count; i < l; i++) { vertex.x = vertices.getX(i) vertex.y = vertices.getY(i) vertex.z = vertices.getZ(i) vertex.applyMatrix4(mesh.matrixWorld) // Position information let line = vertex.x + ' ' + vertex.y + ' ' + vertex.z // Normal information if (includeNormals) { if (normals != null) { vertex.x = normals.getX(i) vertex.y = normals.getY(i) vertex.z = normals.getZ(i) vertex.applyMatrix3(normalMatrixWorld).normalize() line += ' ' + vertex.x + ' ' + vertex.y + ' ' + vertex.z } else { line += ' 0 0 0' } } // UV information if (includeUVs) { if (uvs != null) { line += ' ' + uvs.getX(i) + ' ' + uvs.getY(i) } else if (includeUVs) { line += ' 0 0' } } // Color information if (includeColors) { if (colors != null) { line += ' ' + Math.floor(colors.getX(i) * 255) + ' ' + Math.floor(colors.getY(i) * 255) + ' ' + Math.floor(colors.getZ(i) * 255) } else { line += ' 255 255 255' } } vertexList += line + '\n' } // Create the face list if (includeIndices) { if (indices !== null) { for (let i = 0, l = indices.count; i < l; i += 3) { faceList += `3 ${indices.getX(i + 0) + writtenVertices}` faceList += ` ${indices.getX(i + 1) + writtenVertices}` faceList += ` ${indices.getX(i + 2) + writtenVertices}\n` } } else { for (let i = 0, l = vertices.count; i < l; i += 3) { faceList += `3 ${writtenVertices + i} ${writtenVertices + i + 1} ${writtenVertices + i + 2}\n` } } faceCount += indices ? indices.count / 3 : vertices.count / 3 } writtenVertices += vertices.count }) result = `${header}${vertexList}${includeIndices ? `${faceList}\n` : '\n'}` } if (typeof onDone === 'function') { requestAnimationFrame(() => onDone && onDone(typeof result === 'string' ? result : '')) } return result } // Iterate over the valid meshes in the object private traverseMeshes(object: Object3D, cb: (mesh: Mesh, geometry: BufferGeometry) => void): void { object.traverse(function (child) { if (child instanceof Mesh && child.isMesh) { const mesh = child const geometry = mesh.geometry if (!geometry.isBufferGeometry) { throw new Error('THREE.PLYExporter: Geometry is not of type THREE.BufferGeometry.') } if (geometry.hasAttribute('position')) { cb(mesh, geometry) } } }) } } export { PLYExporter }
the_stack
import * as should from "should"; import { ContinuationPoint, nodesets, StatusCodes } from "node-opcua"; import { OPCUAServer } from "node-opcua-server"; import { date_add } from "node-opcua-address-space/testHelpers"; import { OPCUAClient, ClientSession, ReadRawModifiedDetails, HistoryReadRequest, TimestampsToReturn, HistoryData, NodeId, StatusCode, DataValue } from "node-opcua-client"; const port = 2076; const describe = require("node-opcua-leak-detector").describeWithLeakDetector; describe("Testing Historical Data Node historyRead with continuation points", () => { const today = new Date("2017-01-01T00:00:00.000Z"); let server: OPCUAServer; let nodeId: NodeId; before(async () => { server = new OPCUAServer({ port, nodeset_filename: [nodesets.standard] }); await server.initialize(); const addressSpace = server.engine.addressSpace!; const namespace = addressSpace.registerNamespace("MyPrivateNamespace"); namespace.namespaceUri.should.eql("MyPrivateNamespace"); const node = addressSpace.getOwnNamespace().addVariable({ browseName: "MyVar2", componentOf: addressSpace.rootFolder.objects.server.vendorServerInfo, dataType: "Double" }); nodeId = node.nodeId; addressSpace.installHistoricalDataNode(node, { maxOnlineValues: 100 }); // let's inject some values into the history node.setValueFromSource({ dataType: "Double", value: 0 }, StatusCodes.Good, date_add(today, { seconds: 0 })); node.setValueFromSource({ dataType: "Double", value: 1 }, StatusCodes.Good, date_add(today, { seconds: 1 })); node.setValueFromSource({ dataType: "Double", value: 2 }, StatusCodes.Good, date_add(today, { seconds: 2 })); node.setValueFromSource({ dataType: "Double", value: 3 }, StatusCodes.Good, date_add(today, { seconds: 3 })); node.setValueFromSource({ dataType: "Double", value: 4 }, StatusCodes.Good, date_add(today, { seconds: 4 })); node.setValueFromSource({ dataType: "Double", value: 5 }, StatusCodes.Good, date_add(today, { seconds: 5 })); node.setValueFromSource({ dataType: "Double", value: 6 }, StatusCodes.Good, date_add(today, { seconds: 6 })); await server.start(); }); after(async () => { await server.shutdown(); }); it("should readHistory with continuation point", async () => { const endpointUrl = server.getEndpointUrl(); const client = OPCUAClient.create({ endpointMustExist: false }); await client.withSessionAsync(endpointUrl, async (session: ClientSession) => { const historyReadDetails = new ReadRawModifiedDetails({ endTime: date_add(today, { seconds: 1000 }), isReadModified: false, numValuesPerNode: 3, // three at a time returnBounds: false, startTime: date_add(today, { seconds: -10 }) }); const indexRange = undefined; const dataEncoding = undefined; const readRequest = new HistoryReadRequest({ nodesToRead: [{ nodeId, indexRange, dataEncoding, continuationPoint: undefined }], historyReadDetails, releaseContinuationPoints: false, timestampsToReturn: TimestampsToReturn.Both }); const historyReadResponse = await session.historyRead(readRequest); const historyReadResult = historyReadResponse.results![0]; historyReadResult.statusCode.should.eql(StatusCodes.Good); const dataValues = (historyReadResult.historyData as HistoryData).dataValues!; dataValues.length.should.eql(3); should.exist(historyReadResult.continuationPoint, "expecting a continuation point in our case"); const continuationPoint = historyReadResult.continuationPoint; dataValues[0].sourceTimestamp!.getTime().should.eql(date_add(today, { seconds: 0 }).getTime()); dataValues[1].sourceTimestamp!.getTime().should.eql(date_add(today, { seconds: 1 }).getTime()); dataValues[2].sourceTimestamp!.getTime().should.eql(date_add(today, { seconds: 2 }).getTime()); // make_first_continuation_read(callback) { const historyReadResponse2 = await session.historyRead( new HistoryReadRequest({ nodesToRead: [{ nodeId, indexRange, dataEncoding, continuationPoint }], historyReadDetails, releaseContinuationPoints: false, timestampsToReturn: TimestampsToReturn.Both }) ); const historyReadResult2 = historyReadResponse2.results![0]; historyReadResult2.statusCode.should.eql(StatusCodes.Good); const dataValues2 = (historyReadResult2.historyData as HistoryData).dataValues!; dataValues2.length.should.eql(3); should.exist(historyReadResult2.continuationPoint, "expecting a continuation point in our case"); const continuationPoint2 = historyReadResult2.continuationPoint; should(continuationPoint2).not.eql(null); should(continuationPoint2).eql(continuationPoint); dataValues2[0].sourceTimestamp!.getTime().should.eql(date_add(today, { seconds: 3 }).getTime()); dataValues2[1].sourceTimestamp!.getTime().should.eql(date_add(today, { seconds: 4 }).getTime()); dataValues2[2].sourceTimestamp!.getTime().should.eql(date_add(today, { seconds: 5 }).getTime()); // make_second_continuation_read(callback) { const historyReadResponse3 = await session.historyRead( new HistoryReadRequest({ nodesToRead: [ { nodeId, indexRange, dataEncoding, continuationPoint }, ], historyReadDetails, releaseContinuationPoints: false, timestampsToReturn: TimestampsToReturn.Both }) ); const historyReadResult3 = historyReadResponse3.results![0]; historyReadResult3.statusCode.should.eql(StatusCodes.Good); const dataValues3 = (historyReadResult3.historyData as HistoryData).dataValues!; dataValues3.length.should.eql(1); should.not.exist(historyReadResult3.continuationPoint, "expecting no continuation point"); dataValues3[0].sourceTimestamp!.getTime().should.eql(date_add(today, { seconds: 6 }).getTime()); // const historyReadResponse4 = await session.historyRead( new HistoryReadRequest({ nodesToRead: [{ nodeId, indexRange, dataEncoding, continuationPoint }], historyReadDetails, releaseContinuationPoints: false, timestampsToReturn: TimestampsToReturn.Both }) ); const historyReadResult4 = historyReadResponse4.results![0]; historyReadResult4.statusCode.should.eql(StatusCodes.BadContinuationPointInvalid); }); }); async function sendHistoryReadWithContinuationPointReturnContinuationPoint( session: ClientSession, cntPoint: ContinuationPoint | undefined, releaseContinuationPoints = false ): Promise<{ continuationPoint: ContinuationPoint; statusCode: StatusCode; dataValues: DataValue[]; }> { const historyReadDetails = new ReadRawModifiedDetails({ endTime: date_add(today, { seconds: 1000 }), isReadModified: false, numValuesPerNode: 3, // three at a time returnBounds: false, startTime: date_add(today, { seconds: -10 }) }); const indexRange = undefined; const dataEncoding = undefined; const readRequest = new HistoryReadRequest({ nodesToRead: [ { nodeId, indexRange, dataEncoding, continuationPoint: cntPoint } ], historyReadDetails, releaseContinuationPoints, timestampsToReturn: TimestampsToReturn.Both }); const historyReadResponse = await session.historyRead(readRequest); const historyReadResult = historyReadResponse.results![0]; const statusCode = historyReadResult.statusCode; const dataValues = (historyReadResult.historyData as HistoryData).dataValues!; const continuationPoint = historyReadResult.continuationPoint; return { continuationPoint, statusCode, dataValues }; } it("should readHistory with continuation point - and release continuation points if releaseContinuationPoints= true", async () => { const endpointUrl = server.getEndpointUrl(); const client = OPCUAClient.create({ endpointMustExist: false }); await client.withSessionAsync(endpointUrl, async (session: ClientSession) => { // given that the client has sent a historyRead request that generated a continuation point with releaseContinuationPoints=true const cont1 = await sendHistoryReadWithContinuationPointReturnContinuationPoint(session, undefined, true); should.not.exist(cont1.continuationPoint); }); }); it("should readHistory with continuation point - server should not server continuation point that have been released", async () => { const endpointUrl = server.getEndpointUrl(); const client = OPCUAClient.create({ endpointMustExist: false }); await client.withSessionAsync(endpointUrl, async (session: ClientSession) => { // given that the client has sent a historyRead request that generated a continuation point with releaseContinuationPoints=false const cont1 = await sendHistoryReadWithContinuationPointReturnContinuationPoint(session, undefined, false); should.exist(cont1.continuationPoint); cont1.statusCode.should.eql(StatusCodes.Good); // when that the client has sent a historyRead request that generated a continuation point with releaseContinuationPoints=true const cont2 = await sendHistoryReadWithContinuationPointReturnContinuationPoint(session, cont1.continuationPoint, true); should.not.exist(cont2.continuationPoint); cont2.statusCode.should.eql(StatusCodes.Good); // then the server should serve the continuation point anymore const cont3 = await sendHistoryReadWithContinuationPointReturnContinuationPoint(session, cont1.continuationPoint, true); should.not.exist(cont3.continuationPoint); cont3.statusCode.should.eql(StatusCodes.BadContinuationPointInvalid); }); }); it("the server shall automatically free ContinuationPoints from prior requests from a Session if they are needed to process a new request from this Session.", async () => { const endpointUrl = server.getEndpointUrl(); const client = OPCUAClient.create({ endpointMustExist: false }); await client.withSessionAsync(endpointUrl, async (session: ClientSession) => { // given that the client has sent a first historyRead request that generated a continuation point const cont1 = await sendHistoryReadWithContinuationPointReturnContinuationPoint(session, undefined); cont1.statusCode.should.eql(StatusCodes.Good); // and given that the client send a second historyRead request again const cont2 = await sendHistoryReadWithContinuationPointReturnContinuationPoint(session, undefined); cont2.statusCode.should.eql(StatusCodes.Good); // when the client try to read again with the continuation point of the first request const cont3 = await sendHistoryReadWithContinuationPointReturnContinuationPoint(session, cont1.continuationPoint); // then the server shall return with BadContinuationPointInvalid cont3.statusCode.should.eql(StatusCodes.BadContinuationPointInvalid); }); }); });
the_stack
import { build } from "."; import JsHistogram from "./JsHistogram"; import { NO_TAG } from "./Histogram"; import Int32Histogram from "./Int32Histogram"; import { initWebAssembly, WasmHistogram, initWebAssemblySync } from "./wasm"; import Int8Histogram from "./Int8Histogram"; import Histogram from "./Histogram"; class HistogramForTests extends JsHistogram { //constructor() {} clearCounts() {} incrementCountAtIndex(index: number): void {} incrementTotalCount(): void {} addToTotalCount(value: number) {} setTotalCount(totalCount: number) {} resize(newHighestTrackableValue: number): void { this.establishSize(newHighestTrackableValue); } addToCountAtIndex(index: number, value: number): void {} setCountAtIndex(index: number, value: number): void {} getTotalCount() { return 0; } getCountAtIndex(index: number): number { return 0; } protected _getEstimatedFootprintInBytes() { return 42; } copyCorrectedForCoordinatedOmission( expectedIntervalBetweenValueSamples: number ) { return this; } } describe("Histogram initialization", () => { let histogram: JsHistogram; beforeEach(() => { histogram = new HistogramForTests(1, Number.MAX_SAFE_INTEGER, 3); }); it("should set sub bucket size", () => { expect(histogram.subBucketCount).toBe(2048); }); it("should set resize to false when max value specified", () => { expect(histogram.autoResize).toBe(false); }); it("should compute counts array length", () => { expect(histogram.countsArrayLength).toBe(45056); }); it("should compute bucket count", () => { expect(histogram.bucketCount).toBe(43); }); it("should set min non zero value", () => { expect(histogram.minNonZeroValue).toBe(Number.MAX_SAFE_INTEGER); }); it("should set max value", () => { expect(histogram.maxValue).toBe(0); }); }); describe("Histogram recording values", () => { it("should compute count index when value in first bucket", () => { // given const histogram = new HistogramForTests(1, Number.MAX_SAFE_INTEGER, 3); // when const index = histogram.countsArrayIndex(2000); // 2000 < 2048 expect(index).toBe(2000); }); it("should compute count index when value outside first bucket", () => { // given const histogram = new HistogramForTests(1, Number.MAX_SAFE_INTEGER, 3); // when const index = histogram.countsArrayIndex(2050); // 2050 > 2048 // then expect(index).toBe(2049); }); it("should compute count index taking into account lowest discernible value", () => { // given const histogram = new HistogramForTests(2000, Number.MAX_SAFE_INTEGER, 2); // when const index = histogram.countsArrayIndex(16000); // then expect(index).toBe(15); }); it("should compute count index of a big value taking into account lowest discernible value", () => { // given const histogram = new HistogramForTests(2000, Number.MAX_SAFE_INTEGER, 2); // when const bigValue = Number.MAX_SAFE_INTEGER - 1; const index = histogram.countsArrayIndex(bigValue); // then expect(index).toBe(4735); }); it("should update min non zero value", () => { // given const histogram = new HistogramForTests(1, Number.MAX_SAFE_INTEGER, 3); // when histogram.recordValue(123); // then expect(histogram.minNonZeroValue).toBe(123); }); it("should update max value", () => { // given const histogram = new HistogramForTests(1, Number.MAX_SAFE_INTEGER, 3); // when histogram.recordValue(123); // then expect(histogram.maxValue).toBe(123); }); it("should throw an error when value bigger than highest trackable value", () => { // given const histogram = new HistogramForTests(1, 4096, 3); // when then expect(() => histogram.recordValue(9000)).toThrowError(); }); it("should not throw an error when autoresize enable and value bigger than highest trackable value", () => { // given const histogram = new HistogramForTests(1, 4096, 3); histogram.autoResize = true; // when then expect(() => histogram.recordValue(9000)).not.toThrowError(); }); it("should increase counts array size when recording value bigger than highest trackable value", () => { // given const histogram = new HistogramForTests(1, 4096, 3); histogram.autoResize = true; // when histogram.recordValue(9000); // then expect(histogram.highestTrackableValue).toBeGreaterThan(9000); }); }); describe("Histogram computing statistics", () => { const histogram = new Int32Histogram(1, Number.MAX_SAFE_INTEGER, 3); it("should compute mean value", () => { // given histogram.reset(); // when histogram.recordValue(25); histogram.recordValue(50); histogram.recordValue(75); // then expect(histogram.mean).toBe(50); }); it("should compute standard deviation", () => { // given histogram.reset(); // when histogram.recordValue(25); histogram.recordValue(50); histogram.recordValue(75); // then expect(histogram.stdDeviation).toBeGreaterThan(20.4124); expect(histogram.stdDeviation).toBeLessThan(20.4125); }); it("should compute percentile distribution", () => { // given histogram.reset(); // when histogram.recordValue(25); histogram.recordValue(50); histogram.recordValue(75); // then const expectedResult = ` Value Percentile TotalCount 1/(1-Percentile) 25.000 0.000000000000 1 1.00 25.000 0.100000000000 1 1.11 25.000 0.200000000000 1 1.25 25.000 0.300000000000 1 1.43 50.000 0.400000000000 2 1.67 50.000 0.500000000000 2 2.00 50.000 0.550000000000 2 2.22 50.000 0.600000000000 2 2.50 50.000 0.650000000000 2 2.86 75.000 0.700000000000 3 3.33 75.000 1.000000000000 3 #[Mean = 50.000, StdDeviation = 20.412] #[Max = 75.000, Total count = 3] #[Buckets = 43, SubBuckets = 2048] `; expect(histogram.outputPercentileDistribution()).toBe(expectedResult); }); it("should compute percentile distribution in csv format", () => { // given histogram.reset(); // when histogram.recordValue(25); histogram.recordValue(50); histogram.recordValue(75); // then const expectedResult = `"Value","Percentile","TotalCount","1/(1-Percentile)" 25.000,0.000000000000,1,1.00 25.000,0.100000000000,1,1.11 25.000,0.200000000000,1,1.25 25.000,0.300000000000,1,1.43 50.000,0.400000000000,2,1.67 50.000,0.500000000000,2,2.00 50.000,0.550000000000,2,2.22 50.000,0.600000000000,2,2.50 50.000,0.650000000000,2,2.86 75.000,0.700000000000,3,3.33 75.000,1.000000000000,3,Infinity `; expect( histogram.outputPercentileDistribution(undefined, undefined, true) ).toBe(expectedResult); }); it("should compute percentile distribution in JSON format with rounding according to number of significant digits", () => { // given histogram.reset(); // when histogram.recordValue(25042); histogram.recordValue(50042); histogram.recordValue(75042); // then const { summary } = histogram; expect(summary.p50).toEqual(50000); }); }); describe("Histogram correcting coordinated omissions", () => { const histogram = new Int32Histogram(1, Number.MAX_SAFE_INTEGER, 3); it("should generate additional values when recording", () => { // given histogram.reset(); // when histogram.recordValueWithExpectedInterval(207, 100); // then expect(histogram.totalCount).toBe(2); expect(histogram.minNonZeroValue).toBe(107); expect(histogram.maxValue).toBe(207); }); it("should generate additional values when correcting after recording", () => { // given histogram.reset(); histogram.recordValue(207); histogram.recordValue(207); // when const correctedHistogram = histogram.copyCorrectedForCoordinatedOmission( 100 ); // then expect(correctedHistogram.totalCount).toBe(4); expect(correctedHistogram.minNonZeroValue).toBe(107); expect(correctedHistogram.maxValue).toBe(207); }); it("should not generate additional values when correcting after recording", () => { // given histogram.reset(); histogram.recordValue(207); histogram.recordValue(207); // when const correctedHistogram = histogram.copyCorrectedForCoordinatedOmission( 1000 ); // then expect(correctedHistogram.totalCount).toBe(2); expect(correctedHistogram.minNonZeroValue).toBe(207); expect(correctedHistogram.maxValue).toBe(207); }); }); describe("WASM Histogram not initialized", () => { it("should throw a clear error message", () => { expect(() => build({ useWebAssembly: true })).toThrow( "WebAssembly is not ready yet" ); expect(() => WasmHistogram.build()).toThrow("WebAssembly is not ready yet"); expect(() => WasmHistogram.decode(null as any)).toThrow( "WebAssembly is not ready yet" ); }); }); describe("WASM Histogram not happy path", () => { beforeEach(initWebAssemblySync); it("should throw a clear error message when used after destroy", () => { const destroyedHistogram = build({ useWebAssembly: true }); destroyedHistogram.destroy(); expect(() => destroyedHistogram.recordValue(42)).toThrow( "Cannot use a destroyed histogram" ); }); it("should not crash when displayed after destroy", () => { const destroyedHistogram = build({ useWebAssembly: true }); destroyedHistogram.destroy(); expect(destroyedHistogram + "").toEqual("Destroyed WASM histogram"); }); it("should throw a clear error message when added to a JS regular Histogram", () => { const wasmHistogram = build({ useWebAssembly: true }); const jsHistogram = build({ useWebAssembly: false }); expect(() => jsHistogram.add(wasmHistogram)).toThrow( "Cannot add a WASM histogram to a regular JS histogram" ); }); it("should throw a clear error message when trying to add a JS regular Histogram", () => { const wasmHistogram = build({ useWebAssembly: true }); const jsHistogram = build({ useWebAssembly: false }); expect(() => wasmHistogram.add(jsHistogram)).toThrow( "Cannot add a regular JS histogram to a WASM histogram" ); }); it("should throw a clear error message when substracted to a JS regular Histogram", () => { const wasmHistogram = build({ useWebAssembly: true }); const jsHistogram = build({ useWebAssembly: false }); expect(() => jsHistogram.subtract(wasmHistogram)).toThrow( "Cannot subtract a WASM histogram to a regular JS histogram" ); }); it("should throw a clear error message when trying to add a JS regular Histogram", () => { const wasmHistogram = build({ useWebAssembly: true }); const jsHistogram = build({ useWebAssembly: false }); expect(() => wasmHistogram.subtract(jsHistogram)).toThrow( "Cannot subtract a regular JS histogram to a WASM histogram" ); }); }); describe("WASM estimated memory footprint", () => { let wasmHistogram: Histogram; beforeAll(initWebAssembly); afterEach(() => wasmHistogram.destroy()); it("should be a little bit more than js footprint for packed histograms", () => { wasmHistogram = build({ useWebAssembly: true, bitBucketSize: "packed" }); expect(wasmHistogram.estimatedFootprintInBytes).toBeGreaterThan( build({ bitBucketSize: "packed" }).estimatedFootprintInBytes ); }); }); describe("WASM Histogram correcting coordinated omissions", () => { let histogram: Histogram; beforeAll(initWebAssembly); beforeEach(() => { histogram = build({ useWebAssembly: true }); }); afterEach(() => histogram.destroy()); it("should generate additional values when recording", () => { // given histogram.reset(); // when histogram.recordValueWithExpectedInterval(207, 100); // then expect(histogram.totalCount).toBe(2); expect(histogram.minNonZeroValue).toBe(107); expect(histogram.maxValue).toBe(207); }); it("should generate additional values when correcting after recording", () => { // given histogram.reset(); histogram.recordValue(207); histogram.recordValue(207); // when const correctedHistogram = histogram.copyCorrectedForCoordinatedOmission( 100 ); // then expect(correctedHistogram.totalCount).toBe(4); expect(correctedHistogram.minNonZeroValue).toBe(107); expect(correctedHistogram.maxValue).toBe(207); }); it("should not generate additional values when correcting after recording", () => { // given histogram.reset(); histogram.recordValue(207); histogram.recordValue(207); // when const correctedHistogram = histogram.copyCorrectedForCoordinatedOmission( 1000 ); // then expect(correctedHistogram.totalCount).toBe(2); expect(correctedHistogram.minNonZeroValue).toBe(207); expect(correctedHistogram.maxValue).toBe(207); }); }); describe("Histogram add & substract", () => { beforeAll(initWebAssembly); it("should add histograms of same size", () => { // given const histogram = new Int32Histogram(1, Number.MAX_SAFE_INTEGER, 2); const histogram2 = new Int32Histogram(1, Number.MAX_SAFE_INTEGER, 2); histogram.recordValue(42); histogram2.recordValue(158); // when histogram.add(histogram2); // then expect(histogram.totalCount).toBe(2); expect(histogram.mean).toBe(100); }); it("should add histograms of different sizes & precisions", () => { // given const histogram = build({ lowestDiscernibleValue: 1, highestTrackableValue: 1024, autoResize: true, numberOfSignificantValueDigits: 2, bitBucketSize: "packed", useWebAssembly: true, }); const histogram2 = build({ lowestDiscernibleValue: 1, highestTrackableValue: 1024, autoResize: true, numberOfSignificantValueDigits: 3, bitBucketSize: 32, useWebAssembly: true, }); //histogram2.autoResize = true; histogram.recordValue(42000); histogram2.recordValue(1000); // when histogram.add(histogram2); // then expect(histogram.totalCount).toBe(2); expect(Math.floor(histogram.mean / 100)).toBe(215); }); it("should add histograms of different sizes", () => { // given const histogram = new Int32Histogram(1, Number.MAX_SAFE_INTEGER, 2); const histogram2 = new Int32Histogram(1, 1024, 2); histogram2.autoResize = true; histogram.recordValue(42000); histogram2.recordValue(1000); // when histogram.add(histogram2); // then expect(histogram.totalCount).toBe(2); expect(Math.floor(histogram.mean / 100)).toBe(215); }); it("should be equal when another histogram of lower precision is added then subtracted", () => { // given const histogram = build({ numberOfSignificantValueDigits: 5 }); const histogram2 = build({ numberOfSignificantValueDigits: 3 }); histogram.recordValue(100); histogram2.recordValue(42000); // when const before = histogram.summary; histogram.add(histogram2); histogram.subtract(histogram2); // then expect(histogram.summary).toStrictEqual(before); }); it("should update percentiles when another histogram of same characteristics is substracted", () => { // given const histogram = build({ numberOfSignificantValueDigits: 3 }); const histogram2 = build({ numberOfSignificantValueDigits: 3 }); histogram.recordValueWithCount(100, 2); histogram2.recordValueWithCount(100, 1); histogram.recordValueWithCount(200, 2); histogram2.recordValueWithCount(200, 1); histogram.recordValueWithCount(300, 2); histogram2.recordValueWithCount(300, 1); // when histogram.subtract(histogram2); // then expect(histogram.getValueAtPercentile(50)).toBe(200); }); }); describe("Histogram clearing support", () => { beforeAll(initWebAssembly); it("should reset data in order to reuse histogram", () => { // given const histogram = build({ lowestDiscernibleValue: 1, highestTrackableValue: Number.MAX_SAFE_INTEGER, numberOfSignificantValueDigits: 5, useWebAssembly: true, }); histogram.startTimeStampMsec = 42; histogram.endTimeStampMsec = 56; histogram.tag = "blabla"; histogram.recordValue(1000); // when histogram.reset(); // then expect(histogram.totalCount).toBe(0); expect(histogram.startTimeStampMsec).toBe(0); expect(histogram.endTimeStampMsec).toBe(0); expect(histogram.tag).toBe(NO_TAG); expect(histogram.maxValue).toBe(0); expect(histogram.minNonZeroValue).toBeGreaterThan(Number.MAX_SAFE_INTEGER); expect(histogram.getValueAtPercentile(99.999)).toBe(0); }); it("should behave as new when reseted", () => { // given const histogram = build({ lowestDiscernibleValue: 1, highestTrackableValue: 15000, numberOfSignificantValueDigits: 2, }); const histogram2 = build({ lowestDiscernibleValue: 1, highestTrackableValue: 15000, numberOfSignificantValueDigits: 2, }); histogram.recordValue(1); histogram.recordValue(100); histogram.recordValue(2000); histogram.reset(); // when histogram.recordValue(1000); histogram2.recordValue(1000); // then expect(histogram.mean).toBe(histogram2.mean); }); });
the_stack
module TDev.RT { export enum ShakeType { X, Y, Z, } export module ShakeDetector { /// <summary> /// Any vector that has a magnitude (after reducing gravitation) bigger than this parameter will be considered as a shake vector /// </summary> var shakeMagnitudeWithoutGravitationThreshold : number = 0.2; /// <summary> /// This parameter determines how many consecutive still vectors are required to stop a shake signal /// </summary> var stillCounterThreshold : number = 8; /// <summary> /// This parameter determines the maximum allowed magnitude (after reducing gravitation) for a still vector to be considered to the average /// The last still vector is averaged out of still vectors that are under this bound /// </summary> var stillMagnitudeWithoutGravitationThreshold : number = 0.02; /// <summary> /// The maximum amount of still vectors needed to create a still vector average /// instead of averaging the entire still signal, we just look at the top recent still vectors /// </summary> var maximumStillVectorsNeededForAverage : number = 20; /// <summary> /// The minimum amount of still vectors needed to create a still vector average. /// Without enough vectors the average will not be stable and thus ignored /// </summary> var minimumStillVectorsNeededForAverage : number = 5; /// <summary> /// Determines the amount of shake vectors needed that has been classified the same to recognize a shake /// </summary> var minimumShakeVectorsNeededForShake : number = 8; /// <summary> /// Shake vectors with magnitude less than this parameter will not be considered for gesture classification /// </summary> var weakMagnitudeWithoutGravitationThreshold : number = 0.2; /// <summary> /// Determines the number of moves required to get a shake signal /// </summary> var minimumRequiredMovesForShake : number = 2; // last still vector - average of the last still signal // used to eliminate the gravitation effect // initial value has no meaning, it's just a dummy vector to avoid dealing with null values var _lastStillVector : Vector3 = Vector3.mk(0, -1, 0); // flag that indicates whether we are currently in a middle of a shake signal var _isInShakeState : boolean = false; // counts the number of still vectors - while in shake signal var _stillCounter : number = 0; // holds shake signal vectors var _shakeSignal : Vector3[] = []; // holds shake signal histogram var _shakeHistogram : number[] = [0,0,0]; // hold still signal vectors, newest vectors are first var _stillSignal : Vector3[] = []; /// <summary> /// Called when the accelerometer provides a new value /// </summary> export function accelerationChanged(currentVector : Vector3) : boolean { //Util.log('sd: ' + currentVector); var shakeType : ShakeType = undefined; // check if this vector is considered a shake vector var isShakeMagnitude : boolean = Math.abs(_lastStillVector.length() - currentVector.length()) > shakeMagnitudeWithoutGravitationThreshold; // following is a state machine for detection of shake signal start and end // if still --> shake if ((!_isInShakeState) && (isShakeMagnitude)) { //Util.log('sd: still --> shake'); // set shake state flag _isInShakeState = true; // clear old shake signal clearShakeSignal(); // process still signal processStillSignal(); // add vector to shake signal addVectorToShakeSignal(currentVector); } // if still --> still else if ((!_isInShakeState) && (!isShakeMagnitude)) { //Util.log('sd: still --> still'); // add vector to still signal addVectorToStillSignal(currentVector); } // if shake --> shake else if ((_isInShakeState) && (isShakeMagnitude)) { //Util.log('sd: shake --> shake'); // add vector to shake signal addVectorToShakeSignal(currentVector); // reset still counter _stillCounter = 0; // try to process shake signal shakeType = processShakeSignal(); if (shakeType) // shake signal generated, clear used data clearShakeSignal(); } // if shake --> still else if ((_isInShakeState) && (!isShakeMagnitude)) { //Util.log('sd: shake -->? still: '+ _stillCounter); // add vector to shake signal addVectorToShakeSignal(currentVector); // count still vectors _stillCounter++; // if too much still samples if (_stillCounter > stillCounterThreshold) { //Util.log('sd: shake --> still'); // clear old still signal _stillSignal.clear(); // add still vectors from shake signal to still signal for (var i = 0; i < stillCounterThreshold; ++i) { // calculate current index element var currentSampleIndex = _shakeSignal.length - stillCounterThreshold + i; // add vector to still signal addVectorToStillSignal(currentVector); } // remove last samples from shake signal _shakeSignal.splice(_shakeSignal.length - stillCounterThreshold, stillCounterThreshold); // reset shake state flag _isInShakeState = false; _stillCounter = 0; // try to process shake signal shakeType = processShakeSignal(); if (shakeType) clearShakeSignal(); } } return !!shakeType; } function addVectorToStillSignal(currentVector : Vector3 ) { // add current vector to still signal, newest vectors are first _stillSignal.unshift(currentVector); // if still signal is getting too big, remove old items if (_stillSignal.length > 2 * maximumStillVectorsNeededForAverage) { _stillSignal.pop(); } } /// <summary> /// Add a vector the shake signal and does some preprocessing /// </summary> function addVectorToShakeSignal(currentVector : Vector3) { // remove still vector from current vector var currentVectorWithoutGravitation : Vector3 = currentVector.subtract(_lastStillVector); // add current vector to shake signal _shakeSignal.push(currentVectorWithoutGravitation); // skip weak vectors if (currentVectorWithoutGravitation.length() < weakMagnitudeWithoutGravitationThreshold) { return; } // classify vector var vectorShakeType : ShakeType = classifyVectorShakeType(currentVectorWithoutGravitation); // count vector to histogram _shakeHistogram[<number>vectorShakeType]++; } /// <summary> /// Clear shake signal and related data /// </summary> function clearShakeSignal() { // clear shake signal _shakeSignal.clear(); // create empty histogram for (var i = 0; i < _shakeHistogram.length;++i) _shakeHistogram[i] = 0; } /// <summary> /// Process still signal: calculate average still vector /// </summary> function processStillSignal() { var sumVector = Vector3.mk(0, 0, 0); var count = 0; // going over vectors in still signal // still signal was saved backwards, i.e. newest vectors are first for (var i = 0; i < _stillSignal.length;++i) { var currentStillVector = _stillSignal[i]; // make sure current vector is very still var isStillMagnitude : boolean = (Math.abs(_lastStillVector.length() - currentStillVector.length()) < stillMagnitudeWithoutGravitationThreshold); if (isStillMagnitude) { // sum x,y,z values sumVector = sumVector.add(currentStillVector); ++count; // 20 samples are sufficent if (count >= maximumStillVectorsNeededForAverage) { break; } } } // need at least a few vectors to get a good average if (count >= minimumStillVectorsNeededForAverage) { // calculate average of still vectors _lastStillVector = sumVector.scale(1 / count); } } /// <summary> /// Classify vector shake type /// </summary> function classifyVectorShakeType(v : Vector3) : ShakeType { var absX :number = Math.abs(v.x()); var absY :number = Math.abs(v.y()); var absZ :number = Math.abs(v.z()); // check if X is the most significant component if ((absX >= absY) && (absX >= absZ)) { return ShakeType.X; } // check if Y is the most significant component if ((absY >= absX) && (absY >= absZ)) { return ShakeType.Y; } // Z is the most significant component return ShakeType.Z; } /// <summary> /// Classify shake signal according to shake histogram /// </summary> function processShakeSignal() : ShakeType { var xCount = _shakeHistogram[0]; var yCount = _shakeHistogram[1]; var zCount = _shakeHistogram[2]; var shakeType : ShakeType = undefined; // if X part is strongest and above a minimum if ((xCount >= yCount) && (xCount >= zCount) && (xCount >= minimumShakeVectorsNeededForShake)) { shakeType = ShakeType.X; } // if Y part is strongest and above a minimum else if ((yCount >= xCount) && (yCount >= zCount) && (yCount >= minimumShakeVectorsNeededForShake)) { shakeType = ShakeType.Y; } // if Z part is strongest and above a minimum else if ((zCount >= xCount) && (zCount >= yCount) && (zCount >= minimumShakeVectorsNeededForShake)) { shakeType = ShakeType.Z; } if (shakeType) { var countSignsChanges = countSignChanges(shakeType); // check that we have enough shakes if (countSignsChanges < minimumRequiredMovesForShake) { //Util.log('sd: shake cancelled signs: ' + countSignsChanges); shakeType = undefined; } } return shakeType; } /// <summary> /// Count how many shakes the shake signal contains /// </summary> function countSignChanges(shakeType : ShakeType) : number { var countSignsChanges = 0; var currentSign = 0; var prevSign : number = undefined; for (var i = 0; i < _shakeSignal.length; ++i) { // get sign of current vector switch (shakeType) { case ShakeType.X: currentSign = Math_.sign(_shakeSignal[i].x()); break; case ShakeType.Y: currentSign = Math_.sign(_shakeSignal[i].y()); break; case ShakeType.Z: currentSign = Math_.sign(_shakeSignal[i].z()); break; } // skip sign-less vectors if (currentSign == 0) { continue; } // handle sign for first vector if (!prevSign) { prevSign = currentSign; } // check if sign changed if (currentSign != prevSign) { ++countSignsChanges; } // save previous sign prevSign = currentSign; } return countSignsChanges; } } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormCustomerAddress_Information { interface tab_general_Sections { additional_information: DevKit.Controls.Section; customer_address_information: DevKit.Controls.Section; phone_numbers: DevKit.Controls.Section; } interface tab_general extends DevKit.Controls.ITab { Section: tab_general_Sections; } interface Tabs { general: tab_general; } interface Body { Tab: Tabs; /** Select the address type, such as primary or billing. */ AddressTypeCode: DevKit.Controls.OptionSet; /** Type the city for the customer's address to help identify the location. */ City: DevKit.Controls.String; /** Type the country or region for the customer's address. */ Country: DevKit.Controls.String; /** Type the fax number associated with the customer's address. */ Fax: DevKit.Controls.String; /** Select the freight terms to make sure shipping charges are processed correctly. */ FreightTermsCode: DevKit.Controls.OptionSet; /** Type the first line of the customer's address to help identify the location. */ Line1: DevKit.Controls.String; /** Type the second line of the customer's address. */ Line2: DevKit.Controls.String; /** Type the third line of the customer's address. */ Line3: DevKit.Controls.String; /** Type a descriptive name for the customer's address, such as Corporate Headquarters. */ Name: DevKit.Controls.String; /** Type the ZIP Code or postal code for the address. */ PostalCode: DevKit.Controls.String; /** Type the name of the primary contact person for the customer's address. */ PrimaryContactName: DevKit.Controls.String; /** Select a shipping method for deliveries sent to this address. */ ShippingMethodCode: DevKit.Controls.OptionSet; /** Type the state or province of the customer's address. */ StateOrProvince: DevKit.Controls.String; /** Type the primary phone number for the customer's address. */ Telephone1: DevKit.Controls.String; /** Type a second phone number for the customer's address. */ Telephone2: DevKit.Controls.String; } } class FormCustomerAddress_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form CustomerAddress_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 CustomerAddress_Information */ Body: DevKit.FormCustomerAddress_Information.Body; } class CustomerAddressApi { /** * DynamicsCrm.DevKit CustomerAddressApi * @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; /** Shows the number of the address, to indicate whether the address is the primary, secondary, or other address for the customer. */ AddressNumber: DevKit.WebApi.IntegerValue; /** Select the address type, such as primary or billing. */ AddressTypeCode: DevKit.WebApi.OptionSetValue; /** Type the city for the customer's address to help identify the location. */ City: DevKit.WebApi.StringValue; /** Shows the complete address. */ Composite: DevKit.WebApi.StringValueReadonly; /** Type the country or region for the customer's address. */ Country: DevKit.WebApi.StringValue; /** Type the county for the customer's address. */ County: DevKit.WebApi.StringValue; /** Shows who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the customer address. */ CustomerAddressId: DevKit.WebApi.GuidValue; /** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Type the fax number associated with the customer's address. */ Fax: DevKit.WebApi.StringValue; /** Select the freight terms to make sure shipping charges are processed correctly. */ FreightTermsCode: DevKit.WebApi.OptionSetValue; /** Unique identifier of the data import or data migration that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Type the latitude value for the customer's address, for use in mapping and other applications. */ Latitude: DevKit.WebApi.DoubleValue; /** Type the first line of the customer's address to help identify the location. */ Line1: DevKit.WebApi.StringValue; /** Type the second line of the customer's address. */ Line2: DevKit.WebApi.StringValue; /** Type the third line of the customer's address. */ Line3: DevKit.WebApi.StringValue; /** Type the longitude value for the customer's address, for use in mapping and other applications. */ Longitude: DevKit.WebApi.DoubleValue; /** Shows who last updated the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Type a descriptive name for the customer's address, such as Corporate Headquarters. */ Name: 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.LookupValueReadonly; /** 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.LookupValueReadonly; /** Shows the business unit that the record owner belongs to. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user who owns the customer address. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Choose the customer's address. */ parentid_account: DevKit.WebApi.LookupValue; /** Choose the customer's address. */ parentid_contact: DevKit.WebApi.LookupValue; /** Type the ZIP Code or postal code for the address. */ PostalCode: DevKit.WebApi.StringValue; /** Type the post office box number of the customer's address. */ PostOfficeBox: DevKit.WebApi.StringValue; /** Type the name of the primary contact person for the customer's address. */ PrimaryContactName: DevKit.WebApi.StringValue; /** Select a shipping method for deliveries sent to this address. */ ShippingMethodCode: DevKit.WebApi.OptionSetValue; /** Type the state or province of the customer's address. */ StateOrProvince: DevKit.WebApi.StringValue; /** Type the primary phone number for the customer's address. */ Telephone1: DevKit.WebApi.StringValue; /** Type a second phone number for the customer's address. */ Telephone2: DevKit.WebApi.StringValue; /** Type a third phone number for the customer's address. */ Telephone3: DevKit.WebApi.StringValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** Type the UPS zone of the customer's address to make sure shipping charges are calculated correctly and deliveries are made promptly, if shipped by UPS. */ UPSZone: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Select the time zone for the address. */ UTCOffset: DevKit.WebApi.IntegerValue; /** Version number of the customer address. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace CustomerAddress { enum AddressTypeCode { /** 1 */ Bill_To, /** 4 */ Other, /** 3 */ Primary, /** 2 */ Ship_To } enum FreightTermsCode { /** 1 */ FOB, /** 2 */ No_Charge } enum ShippingMethodCode { /** 1 */ Airborne, /** 2 */ DHL, /** 3 */ FedEx, /** 6 */ Full_Load, /** 5 */ Postal_Mail, /** 4 */ UPS, /** 7 */ Will_Call } 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 React from 'react' import { FlatList, View, Text, TouchableOpacity, Linking } from 'react-native' // @ts-ignore import Prompt from 'react-native-input-prompt' // @ts-ignore import { USER_API_SECRET, USER_API_KEY } from 'react-native-dotenv' // @ts-ignore import Filter from 'bad-words' import { Buckets, Client, KeyInfo, ThreadID, Where } from '@textile/hub' import { createAstronaut, generateWebpage, generateIdentity, getCachedUserThread, cacheUserThread, astronautSchema, } from './helpers' import styles from './styles' const MAX_STEPS = 2 const sleep = (m: number) => new Promise((r) => setTimeout(r, m)) interface StateProps { steps: any step: number errorMessage: string showPrompt: boolean promptTitle: string promptHint: string identity: string db: Client threadId?: ThreadID entityId?: string bucketKey?: string ipfsAddr?: string content?: string } class CheckList extends React.Component<StateProps> { // you could also do this, so no constructor needed state: StateProps = { steps: [ { key: 'Step 0', name: 'Prepare Identity & Token', status: 0 }, { key: 'Step 1', name: 'Setup ThreadDB', status: 0 }, { key: 'Step 2', name: 'Add Instance to Collection', status: 0 }, { key: 'Step 3', name: 'Query from our Collection', status: 0 }, { key: 'Step 4', name: 'Create a webpage', status: 0 }, { key: 'Step 5', name: 'Push webpage to User Bucket', status: 0 }, ], step: 0, errorMessage: '', showPrompt: false, promptTitle: '', promptHint: '', identity: '', db: new Client(), } incrementStatus(index: number) { const steps = this.state.steps const data = steps[index] if (data.status >= MAX_STEPS) { return } data.status = data.status += 1 steps[index] = data this.setState({ steps: steps, }) } async runStep(stepNumber: number) { const steps = this.state.steps const data = steps[stepNumber] try { let { db, threadId } = this.state switch (stepNumber) { case 0: { /** * Create a new user Identity * * The identity pk will be cached in AsyncStorage. * On the next session, the pk identity will be reused */ const id = await generateIdentity() const identity = id.toString() /** * Authenticate the user with your User Key and Secret * * This will allow the user to store threads and buckets * using your developer resources on the Hub. */ const info: KeyInfo = { key: USER_API_KEY, secret: USER_API_SECRET } /** * Auth our Database with admin info * * API calls will now include the credentials created above */ db = await Client.withKeyInfo(info) /** * Generate an app user API token * * The app user (defined by Identity) needs an API token * The API will give you one based on ID plus Credentials * * The token will be added to the existing db.context. */ await db.getToken(id) data.message = 'Created new Identity' data.status = 2 steps[stepNumber] = data this.setState({ identity, db: db, }) break } case 1: { /** * An app should create a minimum number of Threads per user * * A single Thread can contain a large number of distinct * Collections for different types of data. * * Here, we create or restore the user's */ threadId = await getCachedUserThread() /** * Setup a new ThreadID and Database */ if (!threadId) { threadId = ThreadID.fromRandom() await cacheUserThread(threadId) /** * Each new ThreadID requires a `newDB` call. */ await db.newDB(threadId) /** * We add our first Collection to the DB for Astronauts. */ await db.newCollection(threadId, { name: 'Astronaut', schema: astronautSchema }) } /** * Update our context with the target threadId. */ db.context.withThread(threadId.toString()) // Update our app state with success data.status = 2 data.message = 'User Thread linked to Identity' steps[stepNumber] = data this.setState({ db, threadId, steps, }) break } case 2: { /** * Add a new Astronaut * * Our Thread contains the Astronaut Collection, so you just need * to add a new astronaut that matches the expected schema. * * If you run this app many times, you'll notice many Buzz Aldrin * entries in your ThreadDB, each with a unique ID. */ const ids = await db.create(threadId!, 'Astronaut', [createAstronaut()]) // Update our app state with success data.status = 2 steps[stepNumber] = data data.message = `New instance added: ${ids[0]}` this.setState({ entityId: ids[0], steps: steps, }) break } case 3: { /** * You can search all your existing Buzz Aldrins */ const q = new Where('firstName').eq('Buzz') const r = await db.find(threadId!, 'Astronaut', q) const ids = r.map((instance: any) => instance._id) /** * Clean up our entries (just delete them all!) */ await db.delete(threadId!, 'Astronaut', ids) data.status = ids.indexOf(this.state.entityId) > -1 ? 2 : 9 data.message = `${ids.length} existing instances found` steps[stepNumber] = data this.setState({ steps: steps, }) break } case 4: { this.setState({ promptTitle: 'Publish your Website', promptHint: 'Give it a new name, like "Fakeblock"', showPrompt: true, }) break } case 5: { /** * Buckets * * You can now create Buckets for your User. * Bucket will contain raw files and documents. * * We'll use the same auth info we already setup for the ThreadDB. */ const info: KeyInfo = { key: USER_API_KEY, secret: USER_API_SECRET } const identity = await generateIdentity() const buckets = await Buckets.withKeyInfo(info) await buckets.getToken(identity) const result = await buckets.getOrCreate('files') if (!result.root) { throw new Error('Error opening bucket') } const bucketKey = result.root.key /** * Create a simple html string for the webpage */ const webpage = generateWebpage(this.state.content || '') /** * Add a simple file Buffer * * Alternative formats are here: https://github.com/textileio/js-textile/blob/master/src/normalize.ts#L14 * * We add the file as index.html so that we can render it right in the browser afterwards. */ const file = { path: '/index.html', content: Buffer.from(webpage) } /** * Push the file to the root of the Files Bucket. */ const raw = await buckets.pushPath(bucketKey, 'index.html', file) data.status = 2 this.setState({ bucketKey, ipfsAddr: raw.root, steps: steps, }) break } default: data.status = 9 steps[stepNumber] = data this.setState({ steps: steps, }) return } } catch (err) { data.status = 9 data.message = err.message steps[stepNumber] = data this.setState({ steps: steps, }) } } async runAllSteps(stepNumber: number) { await sleep(1200) // <- just adds a delay between steps for UI looks this.runStep(stepNumber) } showStatus(stepNumber: number) { const steps = this.state.steps const data = steps[stepNumber] let message = JSON.stringify(data.message) if (!message) { switch (data.status) { case 0: { message = 'step pending' break } case 1: { message = 'step running' break } case 2: { message = 'step success' break } default: { message = 'step failed' break } } } this.setState({ errorMessage: message }) } renderRow(value: any) { const { item, index } = value if (item.status === 0 && this.state.step === index) { this.runAllSteps(index) this.incrementStatus(index) } else if (item.status === 2 && this.state.step === index) { this.setState({ step: this.state.step + 1 }) } const status = item.status === 2 ? 'success' : item.status === 9 ? 'error' : this.state.step === index ? 'running' : 'pending' const statusText = item.status < 1 ? ' ▵ ' : item.status === 1 ? ' ★ ' : item.status === 2 ? ' ✓ ' : ' ✘ ' const iconColor = item.status < 1 ? 'grey' : item.status === 1 ? 'orange' : item.status === 2 ? 'green' : 'red' return ( <TouchableOpacity style={styles.row} onPress={() => { this.showStatus(index) }} > <View style={styles.rowCellTimeplace}> <Text style={styles.rowTime}>{`${item.key}`}</Text> <Text style={styles.rowName}>{item.name}</Text> </View> <Text style={styles.rowCellTemp}>{status}</Text> <View> <Text style={{ color: iconColor }}>{statusText}</Text> </View> </TouchableOpacity> ) } websiteCancelled() { const steps = this.state.steps const data = steps[4] data.status = 9 data.message = 'User cancelled' steps[4] = data this.setState({ steps: steps, showPrompt: false, }) } websiteNamed(title: string) { const steps = this.state.steps const data = steps[4] const filter = new Filter() let content = title if (filter.isProfane(content)) { content = filter.clean(content) } data.status = 2 steps[4] = data this.setState({ steps: steps, showPrompt: false, content, }) } render() { return ( <View style={styles.container}> <FlatList style={styles.list} data={this.state.steps} keyExtractor={(item) => item.key} renderItem={this.renderRow.bind(this)} /> <View> <Text style={styles.error}>{this.state.errorMessage}</Text> </View> <View> <Text style={{ ...styles.error, ...{ color: 'blue' } }} onPress={() => Linking.openURL(`https://${this.state.bucketKey}.textile.space`)} > {this.state.ipfsAddr ? 'IPNS Webpage Link' : ''} </Text> </View> <View> <Text style={{ ...styles.error, ...{ color: 'blue' } }} onPress={() => Linking.openURL( `https://${this.state.threadId}.thread.hub.textile.io/buckets/${this.state.bucketKey}`, ) } > {this.state.ipfsAddr ? 'Thread Bucket Link' : ''} </Text> </View> <Prompt visible={this.state.showPrompt} title={this.state.promptTitle} placeholder={this.state.promptHint} onCancel={() => this.websiteCancelled()} onSubmit={(text: string) => this.websiteNamed(text)} /> </View> ) } } export default CheckList
the_stack
'use strict'; import { expect } from 'chai'; import { afterEach } from 'mocha'; import { SnippetString } from 'vscode'; import { DidactUriCompletionItemProvider, DIDACT_COMMAND_PREFIX } from "../../didactUriCompletionItemProvider"; import { getContext } from '../../extensionFunctions'; import * as vscode from 'vscode'; import * as path from 'path'; import { removeFilesAndFolders } from '../../utils'; import { waitUntil } from 'async-wait-until'; const COMPLETION_TIMEOUT = 5000; // this number should change as we add more commands const NUMBER_OF_EXPECTED_COMMANDS = 36; const testWorkspace = path.resolve(__dirname, '..', '..', '..', './test Fixture with speci@l chars'); const foldersAndFilesToRemove: string[] = [ 'testmy.didact.md' ]; const testFilename = path.resolve(testWorkspace, 'testmy.didact.md'); const testFileUri = vscode.Uri.file(testFilename); suite("Didact URI completion provider tests", function () { let ctx : vscode.ExtensionContext; let provider: DidactUriCompletionItemProvider; this.beforeAll(() => { ctx = getContext(); provider = new DidactUriCompletionItemProvider(ctx); }); test("that all commands in the didactCompletionCatalog.json are available", async () => { const catalog : any = provider.getCompletionCatalog(ctx); const vsCommands : string[] = await vscode.commands.getCommands(true); suite('walk through each provided completion', () => { catalog.forEach(function(completion: { fullCommandId: string; }){ const fullCommandId = completion.fullCommandId; test(`the command ${fullCommandId} should exist in the vscode commands list`, () => { expect(vsCommands.includes(fullCommandId)).to.be.true; }); }); }); }); test("that the didact protocol completion returns with didact://?commandId=", async () => { const textDocument: vscode.TextDocument | undefined = await vscode.workspace.openTextDocument(); const position = new vscode.Position(0,0); const completionItem = provider.didactProtocolCompletion(textDocument, position); expect(completionItem).to.not.be.null; expect(completionItem).to.not.be.undefined; expect(completionItem.insertText).to.be.equal(DIDACT_COMMAND_PREFIX); }); test("that completions work the way they should", async () => { const listOfCompletions : string[] = [ '[My Link](didact:', '[My Link](didact:/', '[My Link](didact://', '[My Link](didact://?', '[My Link](didact://?c', '[My Link](didact://?co', '[My Link](didact://?com' ]; suite('walk through each provided completion', () => { listOfCompletions.forEach(function(stringToTest: string){ afterEach( async () => { await removeFilesAndFolders(testWorkspace, foldersAndFilesToRemove); }); test(`test provided completion "${stringToTest}"`, async () => { await executeCompletionTest(stringToTest); }).timeout(COMPLETION_TIMEOUT); }); }); }); test("that the match utility returns expected results for simple didact uri", () => { const match = provider.findMatchForCommandVariable('didact://?commandId=vscode.didact.'); expect(match).to.not.be.null; if (match) { expect(match[0]).to.be.equal('?commandId=vscode.didact.'); expect(match[1]).to.be.equal('vscode.didact.'); } }); test("that the match utility returns expected results for didact uri with full command and properties", () => { const match = provider.findMatchForCommandVariable('didact://?commandId=vscode.didact.closeNamedTerminal&text=NamedTerminal'); expect(match).to.not.be.null; if (match) { expect(match[0]).to.be.equal('?commandId=vscode.didact.closeNamedTerminal'); expect(match[1]).to.be.equal('vscode.didact.closeNamedTerminal'); } }); test("that the command processing for a command prefix returns expected results", async () => { const match = provider.findMatchForCommandVariable('didact://?commandId=vscode.didact.'); const completionList = await provider.processCommands(match); expect(completionList.items).to.have.lengthOf(NUMBER_OF_EXPECTED_COMMANDS); }); test("that the command processing for one command returns one expected result", async () => { const match = provider.findMatchForCommandVariable('didact://?commandId=vscode.didact.cliCommandSuccessful&text=cli-requirement-name$$echo%20text'); const completionList = await provider.processCommands(match); expect(completionList.items).to.have.lengthOf(1); const includeText:string | SnippetString | undefined = completionList.items[0].insertText; expect(includeText).to.not.be.undefined; expect((includeText as SnippetString).value).to.include('${1:Requirement-Label}'); expect((includeText as SnippetString).value).to.include('${2:URLEncoded-Command-to-Execute}'); }); test("that the didact protocol matcher returns some expected results for valid values", () => { const validValues : Array<string> = [ "(didact://?commandId=mycommand)", "(didact)", "(didact://)", "(didact:)", "(didact:/", "(didact://?", "[my link](didact://?comma)", "link:didact://?commandId=someCommand", "link:didact", "(didact://?commandId=vscode.didact.cliCommandSuccessful&text=cli-requirement-name$$echo%20text)", "link:didact://?", "link:didact://?commandId=", ]; suite('testing didact protocol matching against positive results', () => { validValues.forEach(function(value:string){ test(`matched a didact protocol in ${value}`, () => { const match = provider.findMatchForDidactPrefix(value); expect(match).to.not.be.null; expect(match?.length).to.be.at.least(1); }); }); }); }); test("that the link matcher returns some expected results for valid asciidoc link values", () => { const validValues : Array<string> = [ "link:didact://?commandId=someCommand[Some text]", "link:didact://?commandId=someCommand", "link:didact", "link:", "link:[some text]" ]; suite('testing link matching against positive results', () => { validValues.forEach(function(value:string){ test(`matched a didact protocol in link ${value}`, () => { const match = provider.findMatchForLinkPrefix(value); expect(match).to.not.be.null; expect(match).to.have.lengthOf(1) }); }); }); }); test("that the didact protocol matcher returns some expected results for invalid values", () => { const invalidValues : Array<string> = [ "[dooby](did://?", "The man was a didact whiz" ]; suite('testing didact protocol matching against negative results', () => { invalidValues.forEach(function(value:string){ test(`did not match a didact protocol in ${value}`, () => { const match = provider.findMatchForDidactPrefix(value); expect(match).to.be.null; }); }); }); }); test("that we show only non-command completions outside of links for adoc documents", async () => { const testFile = path.resolve(__dirname, '..', '..', '..', './src/test/data/completion.didact.adoc'); const document = await vscode.workspace.openTextDocument(testFile); const position = new vscode.Position(0, 0); const actualItems = await getCompletionItems(provider, document, position); expect(actualItems).to.not.be.null; expect(actualItems.length).to.be.at.least(3); expect(await checkForCommandInList(actualItems, 'Insert Didact Requirements Label')).to.be.true; expect(await checkForCommandInList(actualItems, 'Insert link to install required VS Code extension')).to.be.true; expect(await checkForCommandInList(actualItems, 'Insert Didact Badge')).to.be.true; await vscode.commands.executeCommand('workbench.action.closeActiveEditor'); }); test("that we show only command completions for didact links for adoc documents", async () => { const testFile = path.resolve(__dirname, '..', '..', '..', './src/test/data/completion.didact.adoc'); const asciidocFileUri = vscode.Uri.file(testFile); const document = await vscode.workspace.openTextDocument(asciidocFileUri); const position = new vscode.Position(2, 26); const actualItems = await getCompletionItems(provider, document, position); expect(actualItems).to.not.be.null; expect(actualItems.length).to.be.at.least(4); await vscode.commands.executeCommand('workbench.action.closeActiveEditor'); }); test("that we show only non-command completions outside of links for markdown documents", async () => { const testFile = path.resolve(__dirname, '..', '..', '..', './src/test/data/completion.didact.md'); const document = await vscode.workspace.openTextDocument(testFile); const position = new vscode.Position(0, 0); const actualItems = await getCompletionItems(provider, document, position); expect(actualItems).to.not.be.null; expect(actualItems).to.have.lengthOf(4) expect(await checkForCommandInList(actualItems, 'Insert Didact Requirements Label')).to.be.true; expect(await checkForCommandInList(actualItems, 'Insert Validate All Button')).to.be.true; expect(await checkForCommandInList(actualItems, 'Insert link to install required VS Code extension')).to.be.true; expect(await checkForCommandInList(actualItems, 'Insert Didact Badge')).to.be.true; await vscode.commands.executeCommand('workbench.action.closeActiveEditor'); }); test("that we show only command completions for didact links for markdown documents", async () => { const markdownFile = path.resolve(__dirname, '..', '..', '..', './src/test/data/completion.didact.md'); const markdownFileUri = vscode.Uri.file(markdownFile); const document = await vscode.workspace.openTextDocument(markdownFileUri); const position = new vscode.Position(2, 30); const actualItems = await getCompletionItems(provider, document, position); expect(actualItems).to.not.be.null; expect(actualItems.length).to.be.at.least(4); await vscode.commands.executeCommand('workbench.action.closeActiveEditor'); }); }); async function getCompletionItems(provider: DidactUriCompletionItemProvider, document: vscode.TextDocument, position: vscode.Position): Promise<vscode.CompletionItem[]> { return await provider.provideCompletionItems( document, position, ({} as any) as vscode.CancellationToken, ({} as any) as vscode.CompletionContext ); } async function checkForCommandInList(completions: vscode.CompletionItem[], labelToCheck: string): Promise<boolean> { for (let index = 0; index < completions.length; index++) { const completionItem = completions[index]; if (completionItem.label === labelToCheck) { return true; } } return false; } async function createTestEditor(uri: vscode.Uri, input: string) { await vscode.workspace.fs.writeFile(testFileUri, Buffer.from(input)); const document = await vscode.workspace.openTextDocument(uri); return await vscode.window.showTextDocument(document, vscode.ViewColumn.One, true); } async function checkSuggestions(input: string, editor: vscode.TextEditor, document: vscode.TextDocument) { const newCursorPosition = new vscode.Position(0, input.length); editor.selection = new vscode.Selection(newCursorPosition, newCursorPosition); const actualCompletionList = (await vscode.commands.executeCommand( 'vscode.executeCompletionItemProvider', document.uri, newCursorPosition)) as vscode.CompletionList; expect(actualCompletionList).to.not.be.null; expect(actualCompletionList).to.not.be.empty; // if this is available, we have completed the didact://?commandId= part of the completion const startCompletionExists = await checkForCommandInList(actualCompletionList.items, "Start new Didact command link"); // if this is available we have populated the command list const startCommandCompletionExists = await checkForCommandInList(actualCompletionList.items, "vscode.didact.startDidact"); // if either is complete, we have expected completions showing up expect(startCompletionExists || startCommandCompletionExists).to.be.true; } async function executeCompletionTest(input: string) { const editor = await createTestEditor(testFileUri, input); waitUntil( () => { return vscode.window.activeTextEditor?.document.fileName.endsWith('testmy.didact.md'); }, 500); await checkSuggestions(input, editor, editor.document); await vscode.commands.executeCommand('workbench.action.closeActiveEditor'); await vscode.workspace.fs.delete(testFileUri); }
the_stack
import { InanoSQLAdapter, InanoSQLDataModel, InanoSQLTable, InanoSQLPlugin, InanoSQLInstance, VERSION } from "@nano-sql/core/lib/interfaces"; import { _nanoSQLQueue, generateID, maybeAssign, setFast, deepSet, allAsync, blankTableDefinition, chainAsync, slugify, binarySearch } from "@nano-sql/core/lib/utilities"; // import { nanoSQLMemoryIndex } from "@nano-sql/core/lib/adapters/memoryIndex"; import * as Cassandra from "cassandra-driver"; import * as redis from "redis"; const copy = (e) => e; export interface CassandraFilterArgs { createKeySpace?: (query: string) => string; createTable?: (query: string) => string; useKeySpace?: (query: string) => string; dropTable?: (query: string) => string; selectRow?: (query: string) => string; upsertRow?: (query: string) => string; deleteRow?: (query: string) => string; createIndex?: (query: string) => string; dropIndex?: (query: string) => string; addIndexValue?: (query: string) => string; deleteIndexValue?: (query: string) => string; readIndexValue?: (query: string) => string; } export interface CassandraFilterObj { createKeySpace: (query: string) => string; createTable: (query: string) => string; useKeySpace: (query: string) => string; dropTable: (query: string) => string; selectRow: (query: string) => string; upsertRow: (query: string) => string; deleteRow: (query: string) => string; createIndex: (query: string) => string; dropIndex: (query: string) => string; addIndexValue: (query: string) => string; deleteIndexValue: (query: string) => string; readIndexValue: (query: string) => string; } export class Scylla implements InanoSQLAdapter { plugin: InanoSQLPlugin = { name: "Scylla Adapter", version: 2.05 }; nSQL: InanoSQLInstance; private _id: string; private _client: Cassandra.Client; private _redis: redis.RedisClient; private _filters: CassandraFilterObj; private _tableConfigs: { [tableName: string]: InanoSQLTable; } constructor(public args: Cassandra.ClientOptions, public redisArgs?: redis.ClientOpts, filters?: CassandraFilterArgs) { this._tableConfigs = {}; this._filters = { createKeySpace: copy, createTable: copy, useKeySpace: copy, dropTable: copy, selectRow: copy, upsertRow: copy, deleteRow: copy, createIndex: copy, dropIndex: copy, addIndexValue: copy, deleteIndexValue: copy, readIndexValue: copy, ...(filters || {}) } } scyllaTable(table: string): string { return slugify(table).replace(/\-/gmi, "_"); } connect(id: string, complete: () => void, error: (err: any) => void) { this._id = id; this._client = new Cassandra.Client(this.args); this._client.connect().then(() => { this._client.execute(this._filters.createKeySpace(`CREATE KEYSPACE IF NOT EXISTS "${this.scyllaTable(id)}" WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };`), [], (err, result) => { if (err) { error(err); return; } this._client.execute(this._filters.useKeySpace(`USE "${this.scyllaTable(id)}";`), [], (err, result) => { if (err) { error(err); return; } this._redis = redis.createClient(this.redisArgs); this._redis.on("ready", () => { complete(); }); this._redis.on("error", error); }); }); }).catch(error); } key(tableName: string, key: any): string { return this._id + "." + tableName + "." + key; } createTable(tableName: string, tableData: InanoSQLTable, complete: () => void, error: (err: any) => void) { this._tableConfigs[tableName] = tableData; this._client.execute(this._filters.createTable(`CREATE TABLE IF NOT EXISTS "${this.scyllaTable(tableName)}" ( id ${tableData.isPkNum ? (tableData.pkType === "int" ? "bigint" : "double") : (tableData.pkType === "uuid" ? "uuid" : "text")} PRIMARY KEY, data text )`), [], (err, result) => { if (err) { error(err); return; } complete(); }) } dropTable(table: string, complete: () => void, error: (err: any) => void) { this._redis.del(this.key("_ai_", table), () => { // delete AI // done reading index, delete it this._redis.del(this.key("_index_", table), (delErr) => { if (delErr) { error(delErr); return; } this._client.execute(this._filters.dropTable(`DROP TABLE IF EXISTS "${this.scyllaTable(table)}"`), [], (err, result) => { if (err) { error(err); return; } complete(); }) }); }) } disconnect(complete: () => void, error: (err: any) => void) { this._redis.on("end", () => { this._client.shutdown(() => { complete(); }); }) this._redis.quit(); } write(table: string, pk: any, row: { [key: string]: any }, complete: (pk: any) => void, error: (err: any) => void) { new Promise((res, rej) => { // get current auto incremenet value if (this._tableConfigs[table].ai) { this._redis.get(this.key("_ai_", table), (err, result) => { if (err) { rej(err); return; } res(parseInt(result) || 0); }); } else { res(0); } }).then((AI: number) => { pk = pk || generateID(this._tableConfigs[table].pkType, AI + 1); return new Promise((res, rej) => { if (typeof pk === "undefined") { rej(new Error("Can't add a row without a primary key!")); return; } if (this._tableConfigs[table].ai && pk > AI) { // need to increment ai to database this._redis.incr(this.key("_ai_", table), (err, result) => { if (err) { rej(err); return; } res(result || 0); }); } else { res(pk); } }); }).then((primaryKey: any) => { deepSet(this._tableConfigs[table].pkCol, row, primaryKey); return allAsync(["_index_", "_table_"], (item, i, next, err) => { switch (item) { case "_index_": // update index this._redis.zadd(this.key("_index_", table), this._tableConfigs[table].isPkNum ? parseFloat(primaryKey) : 0, primaryKey, (error) => { if (error) { err(error); return; } next(primaryKey); }); break; case "_table_": // update row value const long = Cassandra.types.Long const setPK = this._tableConfigs[table].pkType === "int" ? (long as any).fromNumber(pk) : pk; this._client.execute(this._filters.upsertRow(`UPDATE "${this.scyllaTable(table)}" SET data = ? WHERE id = ?`), [JSON.stringify(row), setPK], (err2, result) => { if (err2) { err(err2); return; } next(primaryKey); }); break; } }); }).then((result: any[]) => { complete(result[0]) }).catch(error); } read(table: string, pk: any, complete: (row: { [key: string]: any } | undefined) => void, error: (err: any) => void) { const long = Cassandra.types.Long const setPK = this._tableConfigs[table].pkType === "int" ? (long as any).fromNumber(pk) : pk; let retries = 0; const doRead = () => { this._client.execute(this._filters.selectRow(`SELECT data FROM "${this.scyllaTable(table)}" WHERE id = ?`), [setPK], (err, result) => { if (err) { if (retries > 3) { error(err); } else { retries++; setTimeout(doRead, 100 + (Math.random() * 100)); } return; } if (result.rowLength > 0) { const row = result.first() || {data: "{}"}; complete(JSON.parse(row.data)); } else { complete(undefined); } }); } doRead(); } readMulti(table: string, type: "range" | "offset" | "all", offsetOrLow: any, limitOrHigh: any, reverse: boolean, onRow: (row: { [key: string]: any }, i: number) => void, complete: () => void, error: (err: any) => void) { this.readRedisIndex(table, type, offsetOrLow, limitOrHigh, reverse, (primaryKeys) => { const batchSize = 2000; let page = 0; const nextPage = () => { const getPKS = primaryKeys.slice(page * batchSize, (page * batchSize) + batchSize); if (getPKS.length === 0) { complete(); return; } allAsync(getPKS, (rowPK, i, rowData, onError) => { this.read(table, rowPK, rowData, onError); }).then((rows) => { rows.forEach(onRow); page++; nextPage(); }).catch(error); } nextPage(); }, error); } delete(table: string, pk: any, complete: () => void, error: (err: any) => void) { allAsync(["_index_", "_table_"], (item, i, next, err) => { switch (item) { case "_index_": // update index this._redis.zrem(this.key("_index_", table), pk, (error) => { if (error) { err(error); return; } next(); }); break; case "_table_": // remove row value const long = Cassandra.types.Long const setPK = this._tableConfigs[table].pkType === "int" ? (long as any).fromNumber(pk) : pk; this._client.execute(this._filters.deleteRow(`DELETE FROM "${this.scyllaTable(table)}" WHERE id = ?`), [setPK], (err2, result) => { if (err2) { error(err2); return; } next(); }) break; } }).then(complete).catch(error); } readRedisIndex(table: string, type: "range" | "offset" | "all", offsetOrLow: any, limitOrHigh: any, reverse: boolean, complete: (index: any[]) => void, error: (err: any) => void): void { switch (type) { case "offset": if (reverse) { this._redis.zrevrange(this.key("_index_", table), offsetOrLow + 1, offsetOrLow + limitOrHigh, (err, results) => { if (err) { error(err); return; } complete(results); }); } else { this._redis.zrange(this.key("_index_", table), offsetOrLow, offsetOrLow + limitOrHigh - 1, (err, results) => { if (err) { error(err); return; } complete(results); }); } break; case "all": this.getTableIndex(table, (index) => { if (reverse) { complete(index.reverse()); } else { complete(index); } }, error); break; case "range": if (this._tableConfigs[table].isPkNum) { this._redis.zrangebyscore(this.key("_index_", table), offsetOrLow, limitOrHigh, (err, result) => { if (err) { error(err); return; } complete(reverse ? result.reverse() : result); }); } else { this._redis.zrangebylex(this.key("_index_", table), "[" + offsetOrLow, "[" + limitOrHigh, (err, result) => { if (err) { error(err); return; } complete(reverse ? result.reverse() : result); }); } break; } } maybeMapIndex(table: string, index: any[]): any[] { if (this._tableConfigs[table].isPkNum) return index.map(i => parseFloat(i)); return index; } getTableIndex(table: string, complete: (index: any[]) => void, error: (err: any) => void) { this._redis.zrangebyscore(this.key("_index_", table), "-inf", "+inf", (err, result) => { if (err) { error(err); return; } complete(this.maybeMapIndex(table, result)); }); } getTableIndexLength(table: string, complete: (length: number) => void, error: (err: any) => void) { this._redis.zcount(this.key("_index_", table), "-inf", "+inf", (err, result) => { if (err) { error(err); return; } complete(result); }); } createIndex(tableId: string, index: string, type: string, complete: () => void, error: (err: any) => void) { const indexName = `_idx_${tableId}_${index}`; const isPkNum = ["float", "int", "number"].indexOf(type) !== -1; this._tableConfigs[indexName] = { ...blankTableDefinition, pkType: type, pkCol: ["id"], isPkNum: isPkNum }; const pksType = this._tableConfigs[tableId].isPkNum ? (this._tableConfigs[tableId].pkType === "int" ? "bigint" : "double") : (this._tableConfigs[tableId].pkType === "uuid" ? "uuid" : "text"); this._client.execute(this._filters.createIndex(`CREATE TABLE IF NOT EXISTS "${this.scyllaTable(indexName)}" ( id ${isPkNum ? (type === "int" ? "bigint" : "double") : (type === "uuid" ? "uuid" : "text")} PRIMARY KEY, pks set<${pksType}> )`), [], (err, result) => { if (err) { error(err); return; } complete(); }); } deleteIndex(tableId: string, index: string, complete: () => void, error: (err: any) => void) { const indexName = `_idx_${tableId}_${index}`; this.dropTable(indexName, complete, error); } addIndexValue(tableId: string, index: string, rowID: any, indexKey: any, complete: () => void, error: (err: any) => void) { const indexName = `_idx_${tableId}_${index}`; return allAsync(["_index_", "_table_"], (item, i, next, err) => { switch (item) { case "_index_": // update index this._redis.zadd(this.key("_index_", indexName), this._tableConfigs[indexName].isPkNum ? parseFloat(indexKey) : 0, indexKey, (error) => { if (error) { err(error); return; } next(); }); break; case "_table_": // update row value const long = Cassandra.types.Long const setIndexKey = this._tableConfigs[indexName].pkType === "int" ? (long as any).fromNumber(indexKey) : indexKey; const setPK = this._tableConfigs[tableId].pkType === "int" ? (long as any).fromNumber(rowID) : rowID; this._client.execute(this._filters.addIndexValue(`UPDATE "${this.scyllaTable(indexName)}" SET pks = pks + {${this._tableConfigs[tableId].isPkNum || this._tableConfigs[tableId].pkType === "uuid" ? setPK : "'" + setPK + "'" }} WHERE id = ?`), [setIndexKey], (err2, result) => { if (err2) { err(err2); return; } next(); }) break; } }).then(complete).catch(error); } deleteIndexValue(tableId: string, index: string, rowID: any, indexKey: any, complete: () => void, error: (err: any) => void) { const indexName = `_idx_${tableId}_${index}`; const long = Cassandra.types.Long const setIndexKey = this._tableConfigs[indexName].pkType === "int" ? (long as any).fromNumber(indexKey) : indexKey; const setPK = this._tableConfigs[tableId].pkType === "int" ? (long as any).fromNumber(rowID) : rowID; this._client.execute(this._filters.deleteIndexValue(`UPDATE "${this.scyllaTable(indexName)}" SET pks = pks - {${this._tableConfigs[tableId].isPkNum || this._tableConfigs[tableId].pkType === "uuid" ? setPK : "'" + setPK + "'" }} WHERE id = ?`), [setIndexKey], (err2, result) => { if (err2) { error(err2); return; } complete(); }) } readIndexKey(tableId: string, index: string, indexKey: any, onRowPK: (pk: any) => void, complete: () => void, error: (err: any) => void) { const indexName = `_idx_${tableId}_${index}`; const long = Cassandra.types.Long const setIndexKey = this._tableConfigs[indexName].pkType === "int" ? (long as any).fromNumber(indexKey) : indexKey; this._client.execute(this._filters.readIndexValue(`SELECT pks FROM "${this.scyllaTable(indexName)}" WHERE id = ?`), [setIndexKey], (err2, result) => { if (err2) { error(err2); return; } if (!result.rowLength) { complete(); return; } const row = result.first() || {pks: []}; row.pks.forEach((value, i) => { onRowPK(this._tableConfigs[tableId].isPkNum ? value.toNumber() : value.toString()); }); complete(); }) } readIndexKeys(tableId: string, index: string, type: "range" | "offset" | "all", offsetOrLow: any, limitOrHigh: any, reverse: boolean, onRowPK: (key: any, id: any) => void, complete: () => void, error: (err: any) => void) { const indexName = `_idx_${tableId}_${index}`; this.readRedisIndex(indexName, type, offsetOrLow, limitOrHigh, reverse, (primaryKeys) => { const pageSize = 2000; let page = 0; let count = 0; const getPage = () => { const keys = primaryKeys.slice(pageSize * page, (pageSize * page) + pageSize); if (!keys.length) { complete(); return; } allAsync(keys, (indexKey, i, pkNext, pkErr) => { this.readIndexKey(tableId, index, indexKey, (row) => { onRowPK(row, count); count++; }, pkNext, pkErr); }).then(() => { page++; getPage(); }) } getPage(); }, error); } }
the_stack
import classNames from 'classnames'; import React, { ChangeEvent, ReactElement, useEffect, useState } from 'react'; import { FieldError, useForm } from 'react-hook-form'; import * as yup from 'yup'; import { Layout } from '../components/Layout'; import { previews } from '../data/defaultPreviews'; import { Spinner } from '../components/loaders/Spinner'; import Link from 'next/link'; export default function LegacyPage(): ReactElement { const [owner, setOwner] = useState('pqt'); const [repo, setRepo] = useState('social-preview'); const [token, setToken] = useState(''); const [repoId, setRepoId] = useState(''); const [preview, setPreview] = useState(previews.legacy); const [showNotification, setShowNotification] = useState(false); const [notificationMessage, setNotificationMessage] = useState(''); useEffect(() => { if (preview === '') { setPreview(previews.legacy); } }, [preview]); const validationSchema = yup.object().shape({ owner: yup.string().required('Owner (or Organization) is required'), repo: yup.string().required('Repository is required'), token: yup.string(), }); const { errors, formState: { isSubmitting, isValid }, handleSubmit, register, } = useForm({ mode: 'onChange', validationSchema }); const handleOwnerChange = (event: ChangeEvent<HTMLInputElement>): void => { setOwner(event.currentTarget.value); }; const handleRepoChange = (event: ChangeEvent<HTMLInputElement>): void => { setRepo(event.currentTarget.value); }; const handleTokenChange = (event: ChangeEvent<HTMLInputElement>): void => { setToken(event.currentTarget.value); }; const onSubmit = handleSubmit(async ({ owner, repo, token }) => { let endpoint = `/api/github-legacy/${owner}/${repo}`; if (token) { endpoint = endpoint.concat(`?token=${token}`); } const response = await fetch(endpoint.toString()); const { data } = await response.json(); setShowNotification(false); setNotificationMessage(''); if (!data.error) { setPreview(data.image); setRepoId(data.id); } else { setNotificationMessage(data.error); setShowNotification(true); } }); return ( <Layout> {/* <Preview /> */} <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-4 sm:pt-6 lg:pt-8"> <div className="max-w-3xl mx-auto space-y-4"> <div className={classNames([ 'relative inline-flex shadow-sm rounded border border-gray-300 bg-gray-100 p-1 md:p-2 lg:p-3 overflow-hidden transition-opacity items-center', isSubmitting && 'opacity-50', ])} > <img src={preview} className="w-full rounded border bg-gray-300" /> {isSubmitting && ( <div className="absolute inset-0 flex justify-center items-center"> <Spinner size={60} /> </div> )} </div> {showNotification && ( <div className="rounded-md bg-red-50 p-4"> <div className="flex"> <div className="flex-shrink-0"> <svg className="h-5 w-5 text-red-400" fill="currentColor" viewBox="0 0 20 20"> <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" /> </svg> </div> <div className="ml-3"> <h3 className="text-sm leading-5 font-medium text-red-800">Error</h3> <div className="mt-2 text-sm leading-5 text-red-700"> <p>{notificationMessage}</p> </div> </div> </div> </div> )} <form onSubmit={onSubmit}> <div className="space-y-4"> <div className="flex flex-col md:flex-row w-full space-y-4 md:space-x-8 md:space-y-0"> <div className="flex-1"> <label htmlFor="owner" className="block text-sm font-medium leading-5 text-gray-700"> Owner / Organization </label> <div className="mt-1 relative rounded-md shadow-sm"> <input className={classNames([ 'form-input block w-full pr-10 sm:text-sm sm:leading-5', errors?.owner ? 'border-red-300 text-red-900 placeholder-red-300 focus:border-red-300 focus:shadow-outline-red' : 'text-gray-700', ])} placeholder="pqt" name="owner" ref={register()} onChange={handleOwnerChange} disabled={isSubmitting} defaultValue={owner} /> {errors?.owner && ( <div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none"> <svg className="h-5 w-5 text-red-500" fill="currentColor" viewBox="0 0 20 20"> <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" /> </svg> </div> )} </div> {errors?.owner && ( <p className="mt-2 text-sm text-red-600" id="email-error"> {(errors?.owner as FieldError)?.message} </p> )} </div> <div className="flex-1"> <label htmlFor="repo" className="block text-sm font-medium leading-5 text-gray-700"> Repository </label> <div className="mt-1 relative rounded-md shadow-sm"> <input className={classNames([ 'form-input block w-full pr-10 sm:text-sm sm:leading-5', errors?.repo ? 'border-red-300 text-red-900 placeholder-red-300 focus:border-red-300 focus:shadow-outline-red' : 'text-gray-700', ])} placeholder="social-preview" name="repo" ref={register()} onChange={handleRepoChange} disabled={isSubmitting} defaultValue={repo} /> {errors?.repo && ( <div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none"> <svg className="h-5 w-5 text-red-500" fill="currentColor" viewBox="0 0 20 20"> <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" /> </svg> </div> )} </div> {errors?.repo && ( <p className="mt-2 text-sm text-red-600" id="email-error"> {(errors?.repo as FieldError)?.message} </p> )} </div> </div> <div className="flex space-x-8 pb-6"> <div className="flex-1 flex space-x-4"> <span className="inline-flex rounded-md shadow-sm"> <button type="submit" className="inline-flex items-center px-4 py-2 border border-transparent text-sm leading-5 font-medium rounded-md text-white bg-blue-600 hover:bg-blue-500 focus:outline-none focus:border-blue-700 focus:shadow-outline-blue active:bg-blue-700 transition ease-in-out duration-150" disabled={isSubmitting || !isValid} > Generate </button> </span> <a className={classNames([ 'inline-flex items-center px-4 py-2 border border-transparent text-sm leading-5 font-medium rounded-md text-blue-700 bg-blue-100 hover:bg-blue-50 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue active:bg-blue-200 transition transform ease-in-out duration-300', repoId ? 'opacity-100 translate-x-0' : 'opacity-0 -translate-x-4 pointer-events-none', ])} href={preview} download={`${owner}-${repo}.png`} > Download </a> </div> <div className="flex-1"> {/* <label htmlFor="repo" className="block text-sm font-medium leading-5 text-gray-700"> Repository </label> */} <div className="mt-1 relative rounded-md shadow-sm"> <input className={classNames([ 'form-input block w-full pr-10 sm:text-sm sm:leading-5', errors?.token ? 'border-red-300 text-red-900 placeholder-red-300 focus:border-red-300 focus:shadow-outline-red' : 'text-gray-700', ])} placeholder="GitHub personal access token (optional)" name="token" ref={register()} onChange={handleTokenChange} disabled={isSubmitting} defaultValue={token} /> {errors?.token && ( <div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none"> <svg className="h-5 w-5 text-red-500" fill="currentColor" viewBox="0 0 20 20"> <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" /> </svg> </div> )} </div> {errors?.token && ( <p className="mt-2 text-sm text-red-600" id="email-error"> {(errors?.token as FieldError)?.message} </p> )} </div> </div> </div> </form> </div> </div> <div className="fixed bottom-40 sm:bottom-32 inset-x-0 pb-2 sm:pb-5 z-50"> <div className="max-w-screen-xl mx-auto px-2 sm:px-6 lg:px-8"> <div className="p-2 rounded-lg bg-blue-600 shadow-lg sm:p-3"> <div className="flex items-center justify-between flex-wrap"> <div className="flex-1 flex items-center"> <span className="flex p-2 rounded-lg bg-blue-800"> {/* <!-- Heroicon name: speakerphone --> */} <svg className="h-6 w-6 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M11 5.882V19.24a1.76 1.76 0 01-3.417.592l-2.147-6.15M18 13a3 3 0 100-6M5.436 13.683A4.001 4.001 0 017 6h1.832c4.1 0 7.625-1.234 9.168-3v14c-1.543-1.766-5.067-3-9.168-3H7a3.988 3.988 0 01-1.564-.317z" /> </svg> </span> <p className="ml-3 font-medium text-white truncate"> <span className="md:hidden">Social Preview has received an update!</span> <span className="hidden md:inline"> This is legacy! Social Preview has received an update with more options. </span> </p> </div> <div className="mt-2 flex-shrink-0 w-full sm:mt-0 sm:w-auto"> <div className="rounded-md shadow-sm"> <Link href="/"> <a className="flex items-center justify-center px-4 py-2 border border-transparent text-sm leading-5 font-medium rounded-md text-blue-600 bg-white hover:text-blue-500 focus:outline-none focus:shadow-outline transition ease-in-out duration-150"> Go </a> </Link> </div> </div> </div> </div> </div> </div> </Layout> ); }
the_stack
import * as KMLTAGS from './KMLTags'; import _ from 'lodash'; import { BoundingBox, GeoPackage, TileScaling, TileScalingType, FeatureTableStyles } from '@ngageoint/geopackage'; import { GeoSpatialUtilities } from './geoSpatialUtilities'; import { ImageUtilities } from './imageUtilities'; import Jimp from 'jimp'; import { IconRow } from '@ngageoint/geopackage/built/lib/extension/style/iconRow'; import { RelatedTablesExtension } from '@ngageoint/geopackage/built/lib/extension/relatedTables'; import path from 'path'; /** * Function directly related the processing of parsed kml data * * @export * @class KMLUtilities */ export class KMLUtilities { /** * Converts the KML Color format into rgb 000000 - FFFFFF and opacity 0.0 - 1.0 * * @static * @param {string} abgr KML Color format AABBGGRR alpha (00-FF) blue (00-FF) green (00-FF) red (00-FF) * @returns {{ rgb: string; a: number }} * @memberof KMLUtilities */ public static abgrStringToColorOpacity(abgr: string): { rgb: string; a: number } { // Valid Color and Hex number if (abgr.match(/^[0-9A-Fa-f]{8}$/)) { const rgb = abgr.slice(6, 8) + abgr.slice(4, 6) + abgr.slice(2, 4); const a = parseInt('0x' + abgr.slice(0, 2)) / 255; return { rgb, a }; } else { throw new Error('Invalid Color'); } } /** * Converts KML Ground Overlay into appropriate tile sets. * * @static * @param {*} node Ground Overlay KML node * @param {GeoPackage} geopackage * @param {Jimp} image * @param {Function} [progressCallback] * @returns {Promise<void>} * @memberof KMLUtilities */ public static async handleGroundOverLay( node: any, geopackage: GeoPackage, image: Jimp, progressCallback?: Function, ): Promise<void> { const imageName = node[KMLTAGS.NAME_TAG]; let kmlBBox = KMLUtilities.getLatLonBBox(node); if (node.LatLonBox.hasOwnProperty('rotation')) { if (progressCallback) progressCallback({ status: 'Rotating Ground Overlay' }); const rotation = parseFloat(node.LatLonBox.rotation); kmlBBox = GeoSpatialUtilities.getKmlBBoxRotation(kmlBBox, rotation); image.rotate(rotation); } const kmlBBoxWebMercator = kmlBBox.projectBoundingBox('EPSG:4326', 'EPSG:3857'); if (progressCallback) progressCallback({ status: 'Making 4326 Image fit 3857 bounding Box.' }); [kmlBBox, image] = await ImageUtilities.truncateImage(kmlBBox, image); const naturalScale = GeoSpatialUtilities.getNaturalScale(kmlBBox, image.getWidth()); const zoomLevels = GeoSpatialUtilities.getZoomLevels(kmlBBox, naturalScale); if (progressCallback) progressCallback({ status: 'Setting Up Web Mercator Tile Table' }); geopackage.createStandardWebMercatorTileTableWithZoomLevels( imageName, kmlBBoxWebMercator, kmlBBoxWebMercator, zoomLevels, ); if (progressCallback) progressCallback({ status: 'Setting Up tile Scaling Extension' }); const tileScalingExt = geopackage.getTileScalingExtension(imageName); await tileScalingExt.getOrCreateExtension(); const ts = new TileScaling(); ts.scaling_type = TileScalingType.IN_OUT; ts.zoom_in = 2; ts.zoom_out = 2; tileScalingExt.createOrUpdate(ts); if (progressCallback) progressCallback({ status: 'Inserting Zoomed and transformed images into Geopackage database.', data: { naturalScale: naturalScale, zoomLevels: zoomLevels }, }); ImageUtilities.insertZoomImages(image, Array.from(zoomLevels), kmlBBox, geopackage, imageName, progressCallback); if (progressCallback) progressCallback({ status: 'Inserted images.', }); } /** * Converts node that contains a LatLonBox tag into a geopackage Bounding box * * @static * @param {*} node node from KML * @returns {BoundingBox} Geopackage Bounding box. * @memberof KMLUtilities */ static getLatLonBBox(node: any): BoundingBox { return new BoundingBox( parseFloat(node.LatLonBox.west), // minLongitude parseFloat(node.LatLonBox.east), // maxLongitude parseFloat(node.LatLonBox.south), // minLatitude parseFloat(node.LatLonBox.north), // maxLatitude ); } /** * Converts kml geometries (Point, LineString, and Polygon) into GeoJSON features * * @static * @param {*} node KML parsed Placemark node * @returns {*} * @memberof KMLUtilities */ public static kmlToGeoJSON(node): any { if (node.hasOwnProperty(KMLTAGS.GEOMETRY_TAGS.POLYGON)) { return KMLUtilities.kmlPolygonToGeoJson(node[KMLTAGS.GEOMETRY_TAGS.POLYGON]); } if (node.hasOwnProperty(KMLTAGS.GEOMETRY_TAGS.POINT)) { return KMLUtilities.kmlPointToGeoJson(node[KMLTAGS.GEOMETRY_TAGS.POINT]); } if (node.hasOwnProperty(KMLTAGS.GEOMETRY_TAGS.LINESTRING)) { return KMLUtilities.kmlLineStringToGeoJson(node[KMLTAGS.GEOMETRY_TAGS.LINESTRING]); } return null; } /** * Takes in a KML parsed Point and returns a GeoJSON formatted object. * * @static * @param {any[]} node The data from xmlStream with the selector of Placemark. * @returns {{ type: string; coordinates: number[] }} * @memberof KMLUtilities */ public static kmlPointToGeoJson(node: any[]): { type: string; coordinates: number[] } { const geometryData = { type: 'Point', coordinates: [] }; node.forEach(point => { const coordPoint = point.coordinates[KMLTAGS.XML_STREAM_TEXT_SELECTOR] .split(',') .map((s: string) => parseFloat(s)); let coordinate: number[]; if (coordPoint.length === 3) { coordinate = [coordPoint[0], coordPoint[1], coordPoint[2]]; } else if (coordPoint.length === 2) { coordinate = [coordPoint[0], coordPoint[1]]; } else { console.error( 'Invalid Point: Coordinates must have a length of 2 or 3. You gave: ', coordPoint.length, point.coordinates[KMLTAGS.XML_STREAM_CHILDREN_SELECTOR], ); return null; } geometryData['coordinates'] = coordinate; }); return geometryData; } /** * Takes in a KML parsed LineString and returns a GeoJSON formatted object. * * @static * @param {any[]} node The data from xmlStream with the selector of Placemark. * @returns {{ type: string; coordinates: number[] }} * @memberof KMLUtilities */ public static kmlLineStringToGeoJson(node: any[]): { type: string; coordinates: number[] } { const geometryData = { type: 'LineString', coordinates: [] }; node.forEach(element => { const coordPoints = element.coordinates[KMLTAGS.XML_STREAM_TEXT_SELECTOR].split(/\s+/); const coordArray = []; coordPoints.forEach((element: string) => { const coords = element.split(',').map(s => parseFloat(s)); if (coords.length === 1 && isNaN(coords[0])) { } else if (coords.length === 3) { coordArray.push([coords[0], coords[1], coords[2]]); } else if (coords.length === 2) { coordArray.push([coords[0], coords[1]]); } else { console.error( 'Invalid Line String: Coordinates must have a length of 2 or 3. You gave: ', coords.length, coords, ); return null; } }); geometryData['coordinates'] = coordArray; }); return geometryData; } /** * Takes in a KML parsed Polygon and returns a GeoJSON formatted object. * * @static * @param {Array<any>} node The data from xmlStream with the selector of Placemark. * @returns {{ type: string; coordinates: number[][][] }} * @memberof KMLUtilities */ public static kmlPolygonToGeoJson(node: Array<any>): { type: string; coordinates: number[][][] } { const geometryData = { type: 'Polygon', coordinates: [] }; node.forEach(element => { const coordRing = element.outerBoundaryIs.LinearRing[0].coordinates[KMLTAGS.XML_STREAM_TEXT_SELECTOR].split( /\s+/, ); const coordArray = []; coordRing.forEach((elementRing: string) => { const coords = elementRing.split(',').map(s => parseFloat(s)); if (coords.length === 1 && isNaN(coords[0])) { } else if (coords.length === 3) { coordArray.push([coords[0], coords[1], coords[2]]); } else if (coords.length === 2) { coordArray.push([coords[0], coords[1]]); } else { console.error( 'Invalid Outer Boundary: Coordinates must have a length of 2 or 3. You gave: ', coords.length, coords, ); return null; } }); const temp = [coordArray]; if (element.hasOwnProperty(KMLTAGS.INNER_BOUNDARY_TAG)) { const coordRing = element[KMLTAGS.INNER_BOUNDARY_TAG][KMLTAGS.LINEAR_RING_TAG][0][KMLTAGS.COORDINATES_TAG][KMLTAGS.XML_STREAM_TEXT_SELECTOR].split( /\s+/, ); const coordArray = []; coordRing.forEach((elementRing: string) => { const coords = elementRing.split(',').map(s => parseFloat(s)); if (coords.length === 3) { coordArray.push([coords[0], coords[1], coords[2]]); } else if (coords.length == 2) { coordArray.push([coords[0], coords[1]]); } else if(coords.length === 1 && coords[0] === NaN) {} else { console.error( 'Invalid InnerBoundary: Coordinates must have a length of 2 or 3. You gave: ', coords.length, elementRing, node, ); return null; } }); temp.push(coordArray); } geometryData['coordinates'] = temp; }); return geometryData; } /** * Creates a list of node that need to be processed. * * @static * @param {*} node Placemark Node from kml via xml-stream * @param {Function} [progressCallback] * @returns {any[]} * @memberof KMLUtilities */ public static setUpGeometryNodes(node: any, progressCallback?: Function): any[] { const nodes = []; if (progressCallback) { progressCallback({ status: 'Handling Geometry and MultiGeometry', data: node, }); } if (node.hasOwnProperty(KMLTAGS.GEOMETRY_TAGS.MULTIGEOMETRY)) { for (const key in node[KMLTAGS.GEOMETRY_TAGS.MULTIGEOMETRY]) { const item = {}; for (const prop in node) { if (prop != KMLTAGS.GEOMETRY_TAGS.MULTIGEOMETRY) { item[prop] = node[prop]; } } if (node[KMLTAGS.GEOMETRY_TAGS.MULTIGEOMETRY].hasOwnProperty(key)) { const shapeType = node[KMLTAGS.GEOMETRY_TAGS.MULTIGEOMETRY][key]; shapeType.forEach(shape => { item[key] = [shape]; nodes.push({ ...item }); }); } } } else if (!_.isNil(node)) { nodes.push(node); } else { console.error('Placemark node is Nil.'); } return nodes; } /** * Writes and maps MultiGeometries into the database * * @static * @param {any[]} geometryIds List of Ids for the item in the Multi geometry * @param {GeoPackage} geopackage Geopackage Database * @param {string} multiGeometryTableName Name on the table that stores the id of the MultiGeometry * @param {RelatedTablesExtension} relatedTableExtension Used to connect tables. * @param {string} multiGeometryMapName Cross reference table (map) between the Geometry table and the MultiGeometry Table * @memberof KMLUtilities */ public static writeMultiGeometry( geometryIds: any[], geopackage: GeoPackage, multiGeometryTableName: string, relatedTableExtension: RelatedTablesExtension, multiGeometryMapName: string, ): void { const multiGeometryId = geopackage.addAttributeRow(multiGeometryTableName, { number_of_geometries: geometryIds.length, }); const userMappingDao = relatedTableExtension.getMappingDao(multiGeometryMapName); for (const id of geometryIds) { const userMappingRow = userMappingDao.newRow(); userMappingRow.baseId = parseInt(id); userMappingRow.relatedId = multiGeometryId; userMappingDao.create(userMappingRow); } } /** * Provides default styles and Icons for the Geometry table. * Currently set to White to match google earth. * Icon set to yellow pushpin google earth default. * * @static * @param {GeoPackage} geopackage * @param {string} tableName Name of the Main Geometry table * @param {Function} [progressCallback] * @returns {Promise<FeatureTableStyles>} * @memberof KMLUtilities */ public static async setUpKMLDefaultStylesAndIcons( geopackage: GeoPackage, tableName: string, progressCallback?: Function, ): Promise<FeatureTableStyles> { if (progressCallback) progressCallback({ status: 'Creating Style and Icon tables.' }); const defaultStyles = new FeatureTableStyles(geopackage, tableName); await defaultStyles.getFeatureStyleExtension().getOrCreateExtension(tableName); await defaultStyles .getFeatureStyleExtension() .getRelatedTables() .getOrCreateExtension(); await defaultStyles .getFeatureStyleExtension() .getContentsId() .getOrCreateExtension(); // Table Wide await defaultStyles.createTableStyleRelationship(); await defaultStyles.createTableIconRelationship(); // Each feature await defaultStyles.createStyleRelationship(); await defaultStyles.createIconRelationship(); if (progressCallback) progressCallback({ status: 'Creating KML Default Styles and Icons.' }); const defaultIcon = defaultStyles.getIconDao().newRow(); try { defaultIcon.name = 'default_black_marker'; defaultIcon.anchorU = 0.5; defaultIcon.anchorV = 0; const defaultImage = 'iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAAXNSR0IArs4c6QAAAk9JREFUaAXtmb1KxEAUhf3BQhtrtbMUbESwEhYLBVGsfBNfQER8BmsfQC0ttFAQQbBWwVIrC9FKRfR8sCkcMzs3uzNJFnPgsJmZO+fcuZkku9mBgQZNBf53BQYjL39OehviojglTorgSXwUL8Rj8UasFTaVzZ34bSSxzKkc08rgSrQm7sYxF41K0JLrs+gmVbSNBlqloiW3D7Fosr54tNAsBZzyGJV3F4NmKduplz3vJu220U4K7hyuaex20rtTkVtltwvDIwl4SFmTOlfsujjRJsf0WefjFR3bUrQksKu4oRx3+hizaOAVHWdSDJlT5bzks2QYIyakg1d0WPY/WyUEYkILSHIdvBmM2fMhEBNaAF4mdDrdrsCw25GwbfYqsgCelCHMhwI0bomxeBmsfoecqhk69VygnYrCGDEhHbxM6GTmCly7HTltfsjsiHm69DFGTAgWr5DGn/EV9YQql41T5V4eZHhFx4gUX8QsyVSfeOBlQt6p9k381MChbzBiPx54JcGCVFNVPtPFIym4wDKz2J9JLl63GqsJF4B2KbiUS+zqo1kaluQUewFolgrL12vrIpN8fQ5VY1YBMV6toIFWJdiTq7XKvjg0KsOonB9EX3KhfuaiUSmW5R5K1DfO3FpgX1n4kvT1M6c2GFMmt6IvWbefWObUCrzLeRfdZN02MUne+8SoxpZhAcTUFvxldSS6Vc/ajMX+Wyt6McaleJ+zCPoY6wvMKMtXMas8x/T1FdaU7VebHCeB+QVSF+5sGSp/Ih50Mb+Z0lSgqYChAj/TCV35EewaiAAAAABJRU5ErkJggg=='; const bufferImg = Buffer.from(defaultImage, 'base64'); defaultIcon.data = bufferImg; defaultIcon.width = 48; defaultIcon.height = 48; defaultIcon.contentType = 'image/png'; defaultStyles.getFeatureStyleExtension().getOrInsertIcon(defaultIcon); } catch (err) { console.error(err); } await defaultStyles.setTableIcon('Point', defaultIcon); const polygonStyleRow = defaultStyles.getStyleDao().newRow(); polygonStyleRow.setColor('FFFFFF', 1.0); polygonStyleRow.setFillColor('FFFFFF', 1.0); polygonStyleRow.setWidth(2.0); polygonStyleRow.setName('Table Polygon Style'); defaultStyles.getFeatureStyleExtension().getOrInsertStyle(polygonStyleRow); const lineStringStyleRow = defaultStyles.getStyleDao().newRow(); lineStringStyleRow.setColor('FFFFFF', 1.0); lineStringStyleRow.setWidth(2.0); lineStringStyleRow.setName('Table Line Style'); defaultStyles.getFeatureStyleExtension().getOrInsertStyle(lineStringStyleRow); const pointStyleRow = defaultStyles.getStyleDao().newRow(); pointStyleRow.setColor('FFFFFF', 1.0); pointStyleRow.setWidth(2.0); pointStyleRow.setName('Table Point Style'); defaultStyles.getFeatureStyleExtension().getOrInsertStyle(pointStyleRow); await defaultStyles.setTableStyle('Polygon', polygonStyleRow); await defaultStyles.setTableStyle('LineString', lineStringStyleRow); await defaultStyles.setTableStyle('Point', pointStyleRow); // await defaultStyles.setTableStyle('MultiPolygon', polygonStyleRow); // await defaultStyles.setTableStyle('MultiLineString', lineStringStyleRow); // await defaultStyles.setTableStyle('MultiPoint', pointStyleRow); return defaultStyles; } /** * Converts Item into a data URL and adds it and information about to the database. * * @static * @param {Jimp} jimpImage * @param {IconRow} newIcon * @param {FeatureTableStyles} styleTable * @param {number} [anchorU=0.5] * @param {number} [anchorV=0.5] * @returns {Promise<number>} * @memberof KMLUtilities */ public static async insertIconImageData( jimpImage: Jimp, newIcon: IconRow, styleTable: FeatureTableStyles, anchorU = 0.5, anchorV = 0.5, ): Promise<number> { newIcon.data = await jimpImage.getBufferAsync(jimpImage.getMIME()); if (_.isNil(newIcon.data)) { console.error('NULL', newIcon); } newIcon.width = jimpImage.getWidth(); newIcon.height = jimpImage.getHeight(); newIcon.contentType = jimpImage.getMIME(); newIcon.anchorU = anchorU; newIcon.anchorV = anchorV; return styleTable.getFeatureStyleExtension().getOrInsertIcon(newIcon); } /** * Adds an Icon into the Database * * @static * @param {FeatureTableStyles} styleTable Database Object for the style * @param {[string, object]} item The id from KML and the object data from KML * @returns {Promise<{ id: number; newIcon: IconRow }>} * @memberof KMLUtilities */ public static async addSpecificIcon( styleTable: FeatureTableStyles, item: [string, object], ): Promise<{ id: number; newIcon: IconRow }> { return new Promise(async (resolve, reject) => { const newIcon = styleTable.getIconDao().newRow(); const kmlStyle = item[1]; newIcon.name = item[0]; let id = -2; if (_.isNil(kmlStyle)) { console.error('kml Style Undefined'); reject(); } if (kmlStyle.hasOwnProperty(KMLTAGS.STYLE_TYPE_TAGS.ICON_STYLE)) { let aU = 0.5; let aV = 0.5; const iconStyle = kmlStyle[KMLTAGS.STYLE_TYPE_TAGS.ICON_STYLE]; if (_.isNil(iconStyle)) { console.error('Icon Style Undefined'); reject(); } if (_.isNil(iconStyle[KMLTAGS.ICON_TAG])) { console.error('Icon Tag Undefined'); reject(); return; } if (iconStyle[KMLTAGS.ICON_TAG].hasOwnProperty('href') && !_.isNil(iconStyle[KMLTAGS.ICON_TAG]['href'])) { let iconLocation = iconStyle[KMLTAGS.ICON_TAG]['href']; iconLocation = iconLocation.startsWith('http') ? iconLocation : path.join(__dirname, iconLocation); const img: Jimp = await Jimp.read(iconLocation).catch(err => { console.error('Image Reading Error', err); throw err; }); if (_.isNil(img)) { reject(); } if (iconStyle.hasOwnProperty(KMLTAGS.SCALE_TAG)) { img.scale(parseFloat(iconStyle[KMLTAGS.SCALE_TAG])); } const iconTag = iconStyle[KMLTAGS.ICON_TAG]; let cropX = 0; let cropY = 0; let cropH = img.getHeight(); let cropW = img.getWidth(); if (iconTag.hasOwnProperty('gx:x')) { cropX = parseInt(iconTag['gx:x']); } if (iconTag.hasOwnProperty('gx:y')) { cropY = cropH - parseInt(iconTag['gx:y']); } if (iconTag.hasOwnProperty('gx:w')) { cropW = parseInt(iconTag['gx:w']); } if (iconTag.hasOwnProperty('gx:h')) { cropH = parseInt(iconTag['gx:h']); } if (cropX > img.getWidth()) { cropX = 0; console.error('Pallet X position not valid'); } if (cropY < 0) { cropY = 0; console.error('Pallet Y position not valid'); } img.crop(cropX, cropY, cropW, cropH); if (iconStyle.hasOwnProperty(KMLTAGS.HOTSPOT_TAG)) { const hotSpot = iconStyle[KMLTAGS.HOTSPOT_TAG]['$']; switch (hotSpot['xunits']) { case 'fraction': aU = parseFloat(hotSpot['x']); break; case 'pixels': aU = 1 - parseFloat(hotSpot['x']) / img.getWidth(); break; case 'insetPixels': aU = parseFloat(hotSpot['x']) / img.getWidth(); default: break; } switch (hotSpot['yunits']) { case 'fraction': aV = 1 - parseFloat(hotSpot['y']); break; case 'pixels': aV = 1 - parseFloat(hotSpot['y']) / img.getHeight(); break; case 'insetPixels': aV = parseFloat(hotSpot['y']) / img.getHeight(); default: break; } } id = await KMLUtilities.insertIconImageData(img, newIcon, styleTable, aU, aV).catch(e => { console.error('error', e); return -1; }); } resolve({ id: id, newIcon: newIcon }); } reject(); }); } }
the_stack
import * as fs from "fs"; import { dirname, resolve, sep } from "path"; import { InternalError } from "../error"; import { trace, tracef } from "../utils"; import * as ts from "./tsmod"; // tslint:disable-next-line:no-var-requires const typeName = require("type-name"); const tsmod = ts.tsmod; export let debugChainableHosts = false; export let debugChainableHostsVerbose = false; if (debugChainableHostsVerbose) debugChainableHosts = true; export let debugDir = true; // tslint:disable:member-ordering // tslint:disable-next-line:ban-types type FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? K : never }[keyof T]; type InitCanonicalize<T> = { [K in keyof T]?: number }; // Member function -> Which arg to canonicalize const initCanonicalize: InitCanonicalize<ChainableHost> = { fileExists: 0, directoryExists: 0, readFile: 0, getFileVersion: 0, getSourceFile: 0, writeFile: 0, getDirectories: 0, realFilename: 0, }; const noop: any = undefined; function callSource(proto: object, propKey: string, desc: PropertyDescriptor) { return { ...desc, value: function _toSource(this: ChainableHost, ...args: any[]) { if (!this.source) throw new InternalError(`source for ${this.constructor.name} is null`); return (this.source as any)[propKey].apply(this.source, args); } }; } export abstract class ChainableHost implements ts.CompilerHost { public _id = ""; // @ts-ignore - Cheat so we don't have to check for null everywhere source: ChainableHost = null; constructor(readonly cwd: string) { for (const key of Object.keys(initCanonicalize)) { // @ts-ignore this.canonicalizeFunc(key, initCanonicalize[key]); } } @tracef(debugChainableHosts) @callSource directoryExists(directoryname: string): boolean { return noop; } @tracef(debugChainableHosts) @callSource fileExists(fileName: string): boolean { return noop; } @callSource getCancellationToken(): ts.CancellationToken { return noop; } @callSource getDefaultLibFileName(options: ts.CompilerOptions): string { return noop; } @tracef(debugChainableHosts) @callSource getDirectories(path: string): string[] { return noop; } @tracef(debugChainableHosts) @callSource getFileVersion(fileName: string): string { return noop; } @tracef(debugChainableHosts) @callSource getNewLine(): string { return noop; } @tracef(debugChainableHosts) @callSource getSourceFile(fileName: string, languageVersion: ts.ScriptTarget, onError?: (message: string) => void): ts.SourceFile | undefined { return noop; } @tracef(debugChainableHosts) @callSource readFile(fileName: string): string | undefined { return noop; } /** * Should be implemented by any Host that performs filename translation. * Given a possibly "faked" or virtual filename, return the real filename * that corresponds. */ @callSource realFilename(fileName: string): string | undefined { return noop; } @callSource resolveModuleName(modName: string, containingFile: string, runnable?: boolean): ts.ResolvedModule | undefined { return noop; } @callSource resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[]): ts.ResolvedModule[] { return noop; } @callSource useCaseSensitiveFileNames(): boolean { return noop; } @tracef(debugChainableHosts) @callSource writeFile(fileName: string, data: string) { return noop; } getCanonicalFileName(fileName: string) { return resolve(this.getCurrentDirectory(), fileName); } getCurrentDirectory(): string { return (this.source && this.source.getCurrentDirectory()) || this.cwd; } setSource(source: ChainableHost): void { if (this.source === null) { this.source = source; } else { throw new Error(`A chainable host can be connected to a source ` + `only once. It looks like you're trying to include the same ` + `instance in multiple chains.`); } } dir(): string[] { return []; } dirTrace() { const dflag = debugChainableHosts || debugDir; if (!dflag) return; // tslint:disable-next-line:no-this-assignment let s: ChainableHost = this; while (true) { const objname = typeName(s) + s._id; trace(dflag, `\nFiles in ${objname}:`); for (const f of s.dir()) { trace(dflag, ` ${f}`); } if (!s.source) break; s = s.source; } } private canonicalizeFunc(funcName: FunctionPropertyNames<this>, argNo: number) { const origFunc = this[funcName]; (this as any)[funcName] = function (this: ChainableHost, ...args: any[]) { args[argNo] = resolve(this.getCurrentDirectory(), args[argNo]); return (origFunc as any).apply(this, args); }; } } export class HostFinal extends ChainableHost { fileExists() { return false; } directoryExists() { return false; } getFileVersion() { return undefined as any; } getSourceFile() { return undefined; } useCaseSensitiveFileNames() { return true; } getNewLine() { return "\n"; } getDefaultLibFileName() { return "lib.d.ts"; } resolveModuleName() { return {resolvedFileName: undefined} as any; } getDirectories() { return []; } readFile() { return undefined; } getCancellationToken() { return null as any; } resolveModuleNames(moduleNames: string[], containingFile: string) { return moduleNames.map((modName) => { return this.resolveModuleName(); }); } realFilename() { return undefined; } writeFile() { throw new Error(`Base Compiler host is not writable`); } dir() { return []; } } export class FileSystemHost extends ChainableHost { constructor(private rootDir: string, cwd = process.cwd()) { super(cwd); this.rootDir = fs.realpathSync(rootDir); } readDirectory(path: string, extensions?: ReadonlyArray<string>, excludes?: ReadonlyArray<string>, includes?: ReadonlyArray<string>, depth?: number): string[] { if (!this.allowed(path)) return []; return tsmod().sys.readDirectory(path, extensions, excludes, includes, depth); } getDirectories(fileName: string) { if (!this.allowed(fileName)) return []; return tsmod().sys.getDirectories(fileName); } directoryExists(path: string) { if (!this.allowed(path)) return false; return tsmod().sys.directoryExists(path); } @tracef(debugChainableHosts) readFile(path: string, encoding?: string) { if (!this.allowed(path)) return undefined; const contents = fs.readFileSync(path, encoding); if (contents) return contents.toString(); return undefined; } @tracef(debugChainableHosts) getFileVersion(fileName: string) { try { const stats = fs.statSync(fileName); return stats.mtimeMs.toString(); } catch (err) { return this.source.getFileVersion(fileName); } } @tracef(debugChainableHosts) fileExists(path: string) { return this.allowed(path) && tsmod().sys.fileExists(path); } realFilename(fileName: string) { return fileName; } writeFile() { throw new Error(`FileSystemHost is not writable`); } dir() { // We don't really want to list the whole filesystem. return [`File system at ${this.rootDir}`]; } private allowed(path: string) { try { const resolved = fs.realpathSync(path); return resolved.startsWith(this.rootDir); } catch (err) { if (err.code && err.code === "ENOENT") { return false; } throw err; } } } interface MemFileVersion { version: number; contents: string; } // Pretends files are on disk for the TS Language Services API export class MemoryHost extends ChainableHost { private files = new Map<string, MemFileVersion>(); private dirs = new Map<string, Set<string>>(); constructor(rootDir: string, cwd = process.cwd()) { super(cwd); this.mkdirs(rootDir); this.mkdirs(cwd); } @tracef(debugChainableHosts) writeFile(path: string, data: string) { let f = this.files.get(path); if (f !== undefined) { f.version++; f.contents = data; } else { f = {version: 1, contents: data}; this.files.set(path, f); // Set up directory const dir = dirname(path); this.mkdirs(dir); const dirSet = this.dirs.get(dir); if (!dirSet) throw new InternalError(`dir not found`); dirSet.add(path); } } @tracef(debugChainableHosts) readFile(path: string, encoding?: string) { const f = this.files.get(path); if (f !== undefined) { return f.contents; } return this.source.readFile(path); } @tracef(debugChainableHosts) getFileVersion(fileName: string) { const f = this.files.get(fileName); if (f !== undefined) { return f.version.toString(); } return this.source.getFileVersion(fileName); } @tracef(debugChainableHosts) fileExists(path: string) { return (this.files.has(path) || super.fileExists(path)); } @tracef(debugChainableHosts) directoryExists(directoryName: string) { return this.dirs.has(directoryName) || this.source.directoryExists(directoryName); } @tracef(debugChainableHosts) getDirectories(path: string) { const pdirs = this.source.getDirectories(path); if (!path.endsWith(sep)) { path += sep; } // Yes this is crappy, but this operation is very infrequent. // regex is anything that matches path in the beginning and only // has one more slash (added above) const re = new RegExp(`^${path}[^/]+$`); for (const d of this.dirs.keys()) { if (re.test(d)) pdirs.push(d); } return pdirs; } dir() { return Array.from(this.files.keys()); } private mkdirs(dir: string) { while (true) { if (!this.dirs.get(dir)) { this.dirs.set(dir, new Set<string>()); } const parent = dirname(dir); if (parent === dir) { break; } dir = parent; } } } export function chainHosts(...hosts: ChainableHost[]): ChainableHost { if (hosts.length < 2) throw new Error(`Must chain at least two hosts`); for (let i = 1; i < hosts.length; i++) { hosts[i - 1].setSource(hosts[i]); } return hosts[0]; } export function MemFileHost(rootDir: string, cwd = process.cwd()): ChainableHost { return chainHosts(new MemoryHost(rootDir, cwd), new FileSystemHost(rootDir, cwd), new HostFinal(cwd)); }
the_stack
'use strict'; import * as dom5 from 'dom5'; var p = dom5.predicates; import {LintError} from './lint-error'; import {ExpressionParser} from './expressions'; var expressionParser = new ExpressionParser(); function getDomModules(analyzer, id) { if (!analyzer.__domModuleCache) { analyzer.__domModuleCache = {}; } if (analyzer.__domModuleCache[id]) { return analyzer.__domModuleCache[id]; } analyzer.__domModuleCache[id] = analyzer.nodeWalkAllDocuments(domModuleForId(id)); return analyzer.__domModuleCache[id]; } function domModuleForId(id) { return p.AND(p.hasTagName('dom-module'),p.hasAttrValue('id', id)); } var isTemplate = p.hasTagName('template'); var parentIsTemplate = p.parentMatches(isTemplate); var twoTemplateAncestors = p.parentMatches(p.AND(isTemplate, parentIsTemplate)); function domModuleTemplates(analyzer, id) { var domModules = getDomModules(analyzer,id); if (!domModules[0]) { return []; } var templates = []; var isOuterTemplate = p.AND( isTemplate, p.NOT(parentIsTemplate) ); return dom5.nodeWalkAll(domModules[0], isOuterTemplate); } function textNodesInDomModuleTemplates(analyzer, id) { var templates = domModuleTemplates(analyzer, id); var textNodes = []; templates.forEach(function(template){ textNodes = textNodes.concat(dom5.nodeWalkAll(template, p.AND( dom5.isTextNode, p.NOT(twoTemplateAncestors)))); }); return textNodes; } /** * Returns all the attributes for all elements defined in templates in * `dom-modules` with an attribute `id` matching the value of `is` * @param {hydrolysis.Analyzer} analyzer [description] * @param {string} is The id to search for * @return {Array.<Object>} A list of all attributes */ function allAttributesInDomModule(analyzer, is) { var templates = domModuleTemplates(analyzer, is); var attrs = []; templates.forEach(function(template) { attrs = attrs.concat(dom5.treeMap(template, function(node) { if (twoTemplateAncestors(node)) { return []; } if (node.attrs === undefined) { return []; } return node.attrs.map(function(attr:any){ attr.node = node; return attr; }); })); }); return attrs; } function extractBadBindingExpression(text) { // 4 cases, {{}, {}}, [[], []] var match = text.match(/\{\{([^\}]*)\}(?!\})/) || text.match(/\[\[([^\]]*)\](?!\])/); if (!match) { var reversed = text.split('').reverse().join(''); match = reversed.match(/\}\}([^\{]*)\{(?!\{)/) || reversed.match(/\]\]([^\[]*)\[(?!\[)/); } if (match) { return text; } return undefined; } function isBindingExpression(text) { var bindingMatch = expressionParser.extractBindingExpression(text); return !!bindingMatch || false; } function textNodeBindingExpressions(analyzer, is) { var expressions = []; var textNodes = textNodesInDomModuleTemplates(analyzer, is); textNodes.forEach(function(textNode) { if (isBindingExpression(textNode.value)) { expressions.push({ expression: textNode.value, node: textNode, parsed: expressionParser.parseExpression(textNode.value) }); } }); return expressions; } function attributeBindingExpressions(analyzer, is) { var expressions = []; var attributes = allAttributesInDomModule(analyzer, is); attributes.forEach(function(attribute) { if (attribute.value && isBindingExpression(attribute.value)) { // Remove the trailing $ from the attribute name. var nativeName = attribute.name.slice(0,-1); expressions.push({ attribute: attribute, expression: attribute.value, node: attribute.node, name: attribute.name, native: isNativeAttribute(nativeName), parsed: expressionParser.parseExpression(attribute.value) }); } }); return expressions; } function allBindingExpressions(analyzer, is) { return textNodeBindingExpressions(analyzer, is) .concat(attributeBindingExpressions(analyzer, is)); } function isBadBindingExpression(text) { var bindingMatch = extractBadBindingExpression(text); return !!bindingMatch || false; } function textNodeBadBindingExpressions(analyzer, is) { var expressions = []; var textNodes = textNodesInDomModuleTemplates(analyzer, is); textNodes.forEach(function(textNode) { if (isBadBindingExpression(textNode.value)) { expressions.push({ expression: textNode.value, node: textNode, parsed: expressionParser.extractBindingExpression(textNode.value) }); } }); return expressions; } function attributeBadBindingExpressions(analyzer, is) { var expressions = []; var attributes = allAttributesInDomModule(analyzer, is); attributes.forEach(function(attribute) { if (attribute.value && isBadBindingExpression(attribute.value)) { expressions.push({ attribute: attribute, expression: attribute.value, node: attribute.node, name: attribute.name, unwrapped: expressionParser.extractBindingExpression(attribute.value) }); } }); return expressions; } function badBindingExpressions(analyzer, is) { return textNodeBadBindingExpressions(analyzer, is) .concat(attributeBadBindingExpressions(analyzer, is)); } var nativeAttributes: Set<string> = new Set(['accesskey', 'class', 'contenteditable', 'contextmenu', 'dir', 'draggable', 'dropzone', 'hidden', 'href', 'id', 'itemprop', 'lang', 'spellcheck', 'style', 'style', 'tabindex', 'title']); function isNativeAttribute(name) { return nativeAttributes.has(name); } // Find attributes bound to native attributes that don't use native binding. function isProblematicAttribute(attr) { var isLabel = p.hasTagName("for"); switch(attr.name.toLowerCase()) { case "for": return isLabel(attr.node); } if (isNativeAttribute(attr.name.toLowerCase())) { return true; } if (attr.name.indexOf("data-") === 0 && attr.name[attr.name.length-1] != "$") { return true; } return false; } function isA11yAttribute(attr) { // list taken from WAI-ARIA spec // aria-* http://www.w3.org/TR/wai-aria/states_and_properties#state_prop_def // role: http://www.w3.org/TR/wai-aria/host_languages#host_general_role switch(attr.name.toLowerCase()) { case 'aria-activedescendant': case 'aria-atomic': case 'aria-autocomplete': case 'aria-busy': case 'aria-checked': case 'aria-controls': case 'aria-describedby': case 'aria-disabled': case 'aria-dropeffect': case 'aria-expanded': case 'aria-flowto': case 'aria-grabbed': case 'aria-haspopup': case 'aria-hidden': case 'aria-invalid': case 'aria-label': case 'aria-labelledby': case 'aria-level': case 'aria-live': case 'aria-multiline': case 'aria-multiselectable': case 'aria-orientation': case 'aria-owns': case 'aria-posinset': case 'aria-pressed': case 'aria-readonly': case 'aria-relevant': case 'aria-required': case 'aria-selected': case 'aria-setsize': case 'aria-sort': case 'aria-valuemax': case 'aria-valuemin': case 'aria-valuenow': case 'aria-valuetext': case 'role': return true; } return false; } function lintErrorFromNode(node, message) { return new LintError(node.__ownerDocument, node.__locationDetail, message, true); } function lintErrorFromJavascript(htmlNode, javascriptNode, href, message) { var jsLoc = javascriptNode.loc.start; var newLoc = { line: jsLoc.line, column: jsLoc.column }; if (href == htmlNode.__ownerDocument) { newLoc.line += htmlNode.__locationDetail.line - 1; newLoc.column += htmlNode.__locationDetail.column; } return new LintError(href, newLoc, message, true); } function lintBindingExpression(parsed, properties, href, node, javascriptNode, expressionName, is, implicitBindings, name) { var undeclaredBindings = []; /** * Hardcode isAttached as a builtin Polymer method, to fix * PolymerElements/iron-demo-helpers#47 until the new linter comes out. */ properties = properties.concat([{ name: 'isAttached', type: 'boolean' }]); parsed.methods.forEach(function(method){ // True if the method patches a property. var foundDefinition = false; // True if the matched property is a method var foundMethod = false; properties.forEach(function(property) { if (method == property.name) { foundMethod = property.type == 'Function'; foundDefinition = true; } }); if (!foundDefinition || !foundMethod) { var message; if (!foundMethod && foundDefinition) { message = name + " using property '" + method + "', " + "which is not a function for element ' " + is + "'"; } else { message = name + " method '" + method + "' is not defined on element ' " + is + "'"; } if (javascriptNode) { undeclaredBindings.push(lintErrorFromJavascript(node, javascriptNode, href, message)); } else { undeclaredBindings.push(lintErrorFromNode(node, message)); } } }); parsed.keys.forEach(function(key){ if (key === '') { return; } if (implicitBindings[key]) { return; } var foundDefinition = false; properties.forEach(function(property) { if (key == property.name) { foundDefinition = true; } }); if (!foundDefinition) { var message; if (expressionName) { message = "Property '" + key + "' bound to attribute '" + expressionName + "' not found in 'properties' for element '" + is + "'"; } else { message = "Property " + key + " not found in 'properties' for element '" + is + "'"; } undeclaredBindings.push(lintErrorFromNode(node, message)); } }); return undeclaredBindings; } var isCustomElement = p.hasMatchingTagName(/(.+-)+.+/); export var linters = { boundVariablesDeclared: function findBindingToClass(analyzer) { var undeclaredBindings = []; analyzer.elements.forEach(function(element) { if (!element.is) return; // Find implicit bindings var attributeExpressions = attributeBindingExpressions(analyzer, element.is); var implicitExpressions = {}; attributeExpressions.forEach(function(attributeExpression){ var node = attributeExpression.node; var parsed = attributeExpression.parsed; var element = analyzer.elementsByTagName[node.tagName]; var attr = attributeExpression.attribute; var native = attributeExpression.native; if (!element && !native) { return; } parsed.keys.forEach(function(key){ if (!implicitExpressions[key]) { implicitExpressions[key] = []; } implicitExpressions[key].push(attributeExpression); }); }); var implicitBindings = {}; Object.keys(implicitExpressions).forEach(function(expression){ var expressions = implicitExpressions[expression]; if (expressions.length <= 1 && !(expressions[0] && expressions[0].native)) { // Allow the binding, but require it to be defined. return; } implicitBindings[expression] = true; }); var textExpressions = textNodeBindingExpressions(analyzer, element.is); var expressions = attributeExpressions.concat(textExpressions); expressions.forEach(function(expression){ undeclaredBindings = undeclaredBindings.concat( lintBindingExpression( expression.parsed, element.properties, element.contentHref, expression.node, undefined, expression.name, element.is, implicitBindings, "Computed Binding" ) ); }); if (element.observers) { var parsedObservers = element.observers.map(function(observer){ return { expression: observer.expression, node: element.scriptElement, javascriptNode: observer.javascriptNode, parsed: expressionParser.parseExpression("{{" + observer.expression + "}}") }; }); parsedObservers.forEach(function(observer){ undeclaredBindings = undeclaredBindings.concat( lintBindingExpression( observer.parsed, element.properties, element.contentHref, observer.node, observer.javascriptNode, observer.name, element.is, implicitBindings, "Observer" ) ); }); } }); return undeclaredBindings; }, domModuleAfterPolymer: function domModuleAfterPolymer(analyzer, path) { var unorderedModules = []; var customElements = analyzer.nodeWalkDocuments(isCustomElement); var loadedDoc = analyzer.getLoadedAst(path); analyzer.elements.forEach(function(element){ // Ignore Polymer.Base since it's special. if (element.is == "Polymer.Base") return; var domModules = getDomModules(analyzer, element.is); if (!domModules[0]) { return; } if (domModules.length > 1) { domModules.forEach(function(domModule) { unorderedModules.push(lintErrorFromNode(domModule, "dom-module " + "has a repeated value for id " + element.is + ".")); }); return; } var scriptContent = dom5.getTextContent(element.scriptElement); var scriptFinderPredicate = p.hasTextValue(scriptContent); var script = dom5.nodeWalk(loadedDoc, scriptFinderPredicate); var otherDomModule = dom5.nodeWalkPrior(script, domModuleForId(element.is)); if (!otherDomModule) { var originalDomModule = domModules[0]; unorderedModules.push(lintErrorFromNode(originalDomModule, "dom-module " + "for " + element.is + " should be a parent of it or earlier in the document.")); } }); return unorderedModules; }, elementNotDefined: function elementNotDefined(analyzer) { var undefinedElements = []; var customElements = analyzer.nodeWalkAllDocuments(isCustomElement); customElements.forEach(function(element){ if (analyzer.elementsByTagName[element.tagName] === undefined) { if (element.tagName == "dom-module" || element.tagName == "test-fixture") { /** * dom-module gets created without using Polymer's syntactic sugar. * Consequently, we definitely don't want to warn if it doesn't exist */ return; } undefinedElements.push(lintErrorFromNode(element, "<" + element.tagName + "> is undefined.")); } }); return undefinedElements; }, nativeAttributeBinding: function nativeAttributeBinding(analyzer) { var badBindings = []; analyzer.elements.forEach(function(element) { var attributes = attributeBindingExpressions(analyzer, element.is); attributes.forEach(function(attr){ if (isProblematicAttribute(attr) || isA11yAttribute(attr)) { var node = attr.node; badBindings.push(lintErrorFromNode(node, "The expression " + attr.expression + " bound to the attribute '"+ attr.name + "' should use $= instead of =.")); } }); }); return badBindings; }, observerNotFunction: function observerNotFunction(analyzer, path) { var badObservers = []; // TODO(ajo): get rid of this horrible N^2. analyzer.elements.forEach(function(element){ element.properties.forEach(function(property){ if (property.observer) { var foundObserver = false; var observer = property.observer; var observerNode = property.observerNode; element.properties.forEach(function(property){ if (foundObserver) return; if (property.name == observer) { foundObserver = true; if (property.type === "Function") return; badObservers.push(lintErrorFromJavascript( element.scriptElement, property.javascriptNode, element.contentHref, "Observer '" + observer + "' is not a function.")); } }); if (!foundObserver) { badObservers.push(lintErrorFromJavascript( element.scriptElement, observerNode, element.contentHref, "Observer '" + observer + "' is undefined.")); } } }); }.bind(this)); return badObservers; }, unbalancedDelimiters: function unbalancedDelimiters(analyzer) { var undeclaredBindings = []; analyzer.elements.forEach(function(element) { if (!element.is) return; var expressions = badBindingExpressions(analyzer, element.is); expressions.forEach(function(expression){ var message = "Expression " + expression.expression + " has unbalanced delimiters"; undeclaredBindings.push(lintErrorFromNode(expression.node, message)); }); }); return undeclaredBindings; } };
the_stack
import { ElementRefs, EElementSignature, getElementType } from './field.render'; export enum ESettingType { standard = 'standard', advanced = 'advanced', hidden = 'hidden', } export interface IStorage { [key: string]: number | string | boolean | IStorage; } export interface IEntry { key: string; path: string; name: string; desc: string; type: ESettingType; index?: number; } interface IEntryDesc { name: string; type: string; canBeEmpty: boolean; } const CEntryProps: IEntryDesc[] = [ { name: 'key', type: 'string', canBeEmpty: false, }, { name: 'path', type: 'string', canBeEmpty: true, }, { name: 'name', type: 'string', canBeEmpty: false, }, { name: 'desc', type: 'string', canBeEmpty: false, }, { name: 'type', type: 'string', canBeEmpty: false, }, ]; export function getEntryError(entry: IEntry): Error | undefined { if (typeof entry !== 'object' || entry === null) { return new Error(`"entry" is not valid.`); } let error: Error | undefined; CEntryProps.forEach((_entry: IEntryDesc) => { if (error !== undefined) { return; } if (typeof (entry as any)[_entry.name] !== typeof _entry.type) { error = new Error(`Key "${_entry.name}" has wrong type "${typeof (entry as any)[_entry.name]}", but expected "${_entry.type}"`); } if (!_entry.canBeEmpty && typeof (entry as any)[_entry.name] === 'string') { if ((entry as any)[_entry.name].trim() === '') { error = new Error(`Key "${_entry.name}" could not be empty. Some value should be defined.`); } } }); return error; } export function findRef(storage: IStorage, path: string | string[], fullpath?: string): IStorage | Error { if (fullpath === undefined) { fullpath = path instanceof Array ? path.join('.') : path; } if (typeof storage !== 'object' || storage === null) { return new Error(`[${fullpath}]: Expected "storage" would be an object`); } if (typeof path === 'string') { if (path === '') { return storage; } else { path = path.split('.'); } } const ref = (storage as any)[path[0]]; if (path.length === 1) { if (typeof ref !== 'object' || ref === null) { return new Error(`[${fullpath}]: Fail to find destination.`); } else { return ref; } } else { return findRef(ref, path.slice(1, path.length), fullpath); } } export function getEntryKey(entry: Entry | Field<any>): string { return `${entry.getPath()}${entry.getPath() === '' ? '' : '.'}${entry.getKey()}`; } export function getEntryKeyByArgs(path: string, key: string): string { return `${path}${path === '' ? '' : '.'}${key}`; } const CEntryClassSignature = 'CEntryClassSignature'; export class Entry { private _key: string; private _name: string; private _desc: string; private _path: string; private _type: ESettingType; private _index: number = 0; constructor(entry: IEntry) { const err: Error | undefined = getEntryError(entry); if (err instanceof Error) { throw err; } this._key = entry.key; this._name = entry.name; this._desc = entry.desc; this._path = entry.path; this._type = entry.type; this._index = typeof entry.index === 'number' ? (!isNaN(entry.index) ? (isFinite(entry.index) ? entry.index : 0) : 0) : 0; } public getKey(): string { return this._key; } public getName(): string { return this._name; } public getDesc(): string { return this._desc; } public getPath(): string { return this._path; } public setPath(path: string) { this._path = path; } public getFullPath(): string { return getEntryKey(this); } public getType(): ESettingType { return this._type; } public getIndex(): number { return this._index; } public setIndex(index: number) { this._index = index; } public asEntry(): IEntry { return { key: this.getKey(), name: this.getName(), path: this.getPath(), type: this.getType(), desc: this.getDesc(), index: this.getIndex(), }; } public extract(store: IStorage): Promise<void> { return new Promise((resolve) => { // Dummy method to make code look nicer (see: service.settings.ts) resolve(); }); } public write(store: IStorage): Error | IStorage { if (typeof store !== 'object' && store === null) { return new Error(`Fail to write, because store isn't an object.`); } const ref: IStorage | Error = findRef(store, this.getPath()); if (ref instanceof Error) { return ref; } if ((ref as any)[this.getKey()] === undefined) { (ref as any)[this.getKey()] = {}; } return store; } /** * Internal usage */ public getClassSignature(): string { return CEntryClassSignature; } /** * Internal usage */ public static isInstance(smth: any): boolean { if (typeof smth !== 'object' || smth === null) { return false; } if (typeof smth.getClassSignature !== 'function') { return false; } return smth.getClassSignature() === CEntryClassSignature; } } export interface IField<T> extends IEntry { value?: T; elSignature?: EElementSignature, elParams?: any; } const CFieldBaseClassSignature = 'CFieldBaseClassSignature'; export class FieldBase<T> extends Entry { public value: T | undefined; constructor(entry: IField<T>) { super(entry); this.value = entry.value; } public asField(): IField<T> { return Object.assign({ value: this.value, }, this.asEntry()); } public get(): T { // Dummy implementation return this.value as T; } public write(store: IStorage): Error | IStorage { if (typeof store !== 'object' && store === null) { return new Error(`Fail to write, because store isn't an object.`); } const ref: IStorage | Error = findRef(store, this.getPath()); if (ref instanceof Error) { return ref; } (ref as any)[this.getKey()] = this.get(); return store; } public read(store: IStorage): T | undefined { const ref: IStorage | Error = findRef(store, this.getPath()); if (ref instanceof Error) { return undefined; } const stored: T | undefined = (ref as any)[this.getKey()]; return stored; } /** * Internal usage */ public getClassSignature(): string { return CFieldBaseClassSignature; } /** * Internal usage */ public static isInstance(smth: any): boolean { if (typeof smth !== 'object' || smth === null) { return false; } if (typeof smth.getClassSignature !== 'function') { return false; } return smth.getClassSignature() === CFieldBaseClassSignature; } } const CRemoteFieldClassSignature = 'CRemoteFieldClassSignature'; export class RemoteField<T> extends FieldBase<T> { public value: T | undefined; constructor(entry: IField<T>) { super(entry); this.value = entry.value; } public extract(store: IStorage, defaults?: T): Promise<void> { return new Promise((resolve, reject) => { const ref: IStorage | Error = findRef(store, this.getPath()); if (ref instanceof Error) { return reject(ref); } const stored: T | undefined = (ref as any)[this.getKey()]; if (stored === undefined && defaults !== undefined) { this.set(defaults).then(resolve).catch(reject); } else if (stored !== undefined) { this.set(stored).then(resolve).catch(reject); } resolve(); }); } public set(value: T): Promise<void> { return new Promise((resolve) => { this.value = value; resolve(); }); } public get(): T { if (this.value === undefined) { throw new Error(`Value of "${this.getFullPath()}" isn't initialized`); } return this.value; } public write(store: IStorage): Error | IStorage { if (typeof store !== 'object' && store === null) { return new Error(`Fail to write, because store isn't an object.`); } const ref: IStorage | Error = findRef(store, this.getPath()); if (ref instanceof Error) { return ref; } (ref as any)[this.getKey()] = this.get(); return store; } /** * Internal usage */ public getClassSignature(): string { return CRemoteFieldClassSignature; } /** * Internal usage */ public static isInstance(smth: any): boolean { if (typeof smth !== 'object' || smth === null) { return false; } if (typeof smth.getClassSignature !== 'function') { return false; } return smth.getClassSignature() === CRemoteFieldClassSignature; } } const CFieldClassSignature = 'CFieldClassSignature'; export abstract class Field<T> extends FieldBase<T> { public value: T | undefined; public abstract validate(value: T): Promise<void>; public abstract getDefault(): Promise<T>; public abstract getElement(): ElementRefs | undefined; public asField(): IField<T> { const element: ElementRefs | undefined = this.getElement(); return Object.assign({ value: this.value, elSignature: this.getElementType(), elParams: element === undefined ? undefined : element.getParams(), }, this.asEntry()); } public extract(store: IStorage): Promise<void> { return new Promise((resolve, reject) => { const ref: IStorage | Error = findRef(store, this.getPath()); if (ref instanceof Error) { return reject(ref); } const stored: T | undefined = (ref as any)[this.getKey()]; if (stored === undefined) { this.getDefault().then((value: T) => { this.set(value).then(resolve).catch(reject); }).catch(reject); } else { this.validate(stored).then(() => { this.set(stored).then(resolve).catch(reject); }).catch(() => { this.getDefault().then((value: T) => { this.set(value).then(resolve).catch(reject); }).catch(reject); }); } }); } public set(value: T): Promise<void> { return new Promise((resolve, reject) => { this.validate(value).then(() => { this.value = value; resolve(); }).catch((err: Error) => { reject(err); }); }); } public get(): T { if (this.value === undefined) { throw new Error(`Value of "${this.getFullPath()}" isn't initialized`); } return this.value; } public write(store: IStorage): Error | IStorage { if (typeof store !== 'object' && store === null) { return new Error(`Fail to write, because store isn't an object.`); } const ref: IStorage | Error = findRef(store, this.getPath()); if (ref instanceof Error) { return ref; } (ref as any)[this.getKey()] = this.get(); return store; } public getElementType(): EElementSignature | undefined { return getElementType(this.getElement()); } /** * Internal usage */ public getClassSignature(): string { return CFieldClassSignature; } /** * Internal usage */ public static isInstance(smth: any): boolean { if (typeof smth !== 'object' || smth === null) { return false; } if (typeof smth.getClassSignature !== 'function') { return false; } return smth.getClassSignature() === CFieldClassSignature; } } export abstract class RemoteFieldWrapper<T> extends RemoteField<T> { public abstract validate(value: T): Promise<void>; public abstract getDefault(): Promise<T>; public abstract getElement(): ElementRefs | undefined; }
the_stack
'use strict'; // ==================== // KONG TYPES // ==================== export interface KongApi { created_at?: number, hosts?: string[], uris?: string[], http_if_terminated?: boolean, https_only?: boolean, id?: string, name: string, preserve_host?: boolean, retries?: number, strip_uri?: boolean, hide_credentials?: boolean, connect_timeout?: number, read_timeout?: number, write_timeout?: number, upstream_url: string, routes?: KongRoute[] } export enum ProtocolType { http = 'http', https = 'https' } export interface KongService { id?: string, name: string, created_at?: number, updated_at?: number, protocol: ProtocolType, host: string, port: number, path: string, retries?: number, connect_timeout?: number, read_timeout?: number, write_timeout?: number, tags?: string[] } export interface KongRoute { id?: string, created_at?: number, updated_at?: number, protocols: ProtocolType[], methods?: string[], hosts?: string[], paths?: string[], regex_priority?: number, snis?: string[], sources?: string[], destinations?: string[], tags?: string[], strip_path: boolean, preserve_host: boolean, service: { id: string } } export interface KongPlugin { id?: string, name: string, enabled: boolean, api_id?: string, service_id?: string, route_id?: string, consumer_id?: string, config?: any } export interface KongPluginCors extends KongPlugin { config: { credentials?: boolean, origins: string[], preflight_continue?: boolean, // Can be comma-separated string or string[] methods?: any } } export interface KongPluginRequestTransformer extends KongPlugin { config: { http_method?: string, remove?: { headers?: string[], querystring?: string[], body?: string[], }, replace?: { headers?: string[], querystring?: string[], body?: string[] }, rename?: { headers?: string[], querystring?: string[], body?: string[], }, append?: { headers?: string[] querystring?: string[], body?: string[], }, add?: { headers?: string[] querystring?: string[], body?: string[], } } } export interface KongPluginResponseTransformer extends KongPlugin { config: { remove?: { headers?: string[], json?: string[] }, replace?: { headers?: string[], json?: string[] }, add?: { headers?: string[], json?: string[] }, append?: { headers?: string[], json?: string[] } } } export interface KongPluginOAuth2 extends KongPlugin { config: { refresh_token_ttl?: number, provision_key?: string, accept_http_if_already_terminated?: boolean, hide_credentials?: boolean, global_credentials?: boolean, enable_client_credentials?: boolean, enable_authorization_code?: boolean, enable_implicit_grant?: boolean, enable_password_grant?: boolean, token_expiration: number, anonymous?: string, scopes?: string[], mandatory_scope?: boolean, auth_header_name?: string } } export interface KongPluginRateLimiting extends KongPlugin { config: { fault_tolerant?: boolean, hide_client_headers?: boolean, limit_by?: string, second?: number, minute?: number, hour?: number, day?: number, month?: number, year?: number, policy?: string, redis_host?: string, redis_database?: number, redis_port?: number, redis_password?: string, redis_timeout?: number } } export interface KongPluginWhiteBlackList extends KongPlugin { config: { /** Comma-separated list of IP addresses */ whitelist?: string, /** Comma-separated list of IP addresses */ blacklist?: string } } export interface KongPluginBotDetection extends KongPlugin { config: { /** A comma separated array of regular expressions that should be whitelisted. The regular expressions will be checked against the User-Agent header. */ whitelist?: string, /** A comma separated array of regular expressions that should be blacklisted. The regular expressions will be checked against the User-Agent header. */ blacklist?: string } } export enum KongPluginCorrelationIdGeneratorType { UUID = 'uuid', UUIDCounter = 'uuid#counter', Tracker = 'tracker' } export interface KongPluginCorrelationId extends KongPlugin { config: { header_name?: string, generator?: KongPluginCorrelationIdGeneratorType, echo_downstream?: boolean } } export interface KongPluginHmacAuth extends KongPlugin { hide_credentials?: boolean, clock_skew?: number, anonymous?: string, validate_request_body?: boolean, enforce_headers?: string[], algorithms: string[] } export interface KongCollection<T> { // This property is not always present, take it out, use data.length // total: number, data: T[], next?: string } export interface KongConsumer { id?: string, created_at?: number, username?: string, custom_id: string } export interface KongProxyListener { ssl: boolean, ip: string, proxy_protocol: boolean, port: number, http2: boolean listener: string } export interface KongHttpDirective { value: string, name: string } /** * This is a possibly incomplete set of properties which a get to <kong>:8001/ returns. */ export interface KongGlobals { version: string, host: string, tagline: string, node_id: string, lua_version: string, plugins: { enabled_in_cluster: string[], available_on_server: { [plugin_name: string]: boolean } }, configuration: { plugins: string[], admin_listen: string[], lua_ssl_verify_depth: number, trusted_ips: string[], prefix: string, loaded_plugins: { [plugin_name: string]: boolean }, cassandra_username: string, admin_ssl_cert_csr_default: string, ssl_cert_key: string, dns_resolver: object, pg_user: string, mem_cache_size: string, cassandra_data_centers: string[], nginx_admin_directives: any, custom_plugins: any, pg_host: string, nginx_acc_logs: string, proxy_listen: string[], client_ssl_cert_default: string, ssl_cert_key_default: string, dns_no_sync: boolean, db_update_propagation: number, nginx_err_logs: string, cassandra_port: number, dns_order: string[], dns_error_ttl: number, headers: string[], dns_stale_ttl: number, nginx_optimizations: boolean, database: string, pg_database: string, nginx_worker_processes: string, lua_package_cpath: string, admin_acc_logs: string, lua_package_path: string, nginx_pid: string, upstream_keepalive: number, cassandra_contact_points: string[], client_ssl_cert_csr_default: string, proxy_listeners: KongProxyListener[], proxy_ssl_enabled: boolean, admin_access_log: string, pg_password: string, enabled_headers: { latency_tokens: boolean, "X-Kong-Proxy-Latency": boolean, Via: boolean, server_tokens: boolean, Server: boolean, "X-Kong-Upstream-Latency": boolean, "X-Kong-Upstream-Status": boolean }, cassandra_ssl: boolean, ssl_cert_csr_default: string, db_resurrect_ttl: number, client_max_body_size: string, cassandra_consistency: string, db_cache_ttl: number, admin_error_log: string, pg_ssl_verify: boolean, dns_not_found_ttl: boolean, pg_ssl: boolean, client_ssl: boolean, db_update_frequency: number, cassandra_repl_strategy: string, nginx_kong_conf: string, cassandra_repl_factor: number, nginx_http_directives: KongHttpDirective[], error_default_type: string, kong_env: string, cassandra_schema_consensus_timeout: number, dns_hostsfile: string, admin_listeners: KongProxyListener[], real_ip_header: string, ssl_cert: string, proxy_access_log: string, admin_ssl_cert_key_default: string, cassandra_ssl_verify: boolean, cassandra_lb_policy: string, ssl_cipher_suite: string, real_ip_recursive: string, proxy_error_log: string, client_ssl_cert_key_default: string, nginx_daemon: string, anonymous_reports: boolean, cassandra_timeout: number, nginx_proxy_directives: any, pg_port: number, log_level: string, client_body_buffer_size: string, ssl_ciphers: string, lua_socket_pool_size: number, admin_ssl_cert_default: string, cassandra_keyspace: string, ssl_cert_default: string, nginx_conf: string, admin_ssl_enabled: boolean } } export interface KongStatus { database: { reachable: boolean }, server: { connections_writing: number, total_requests: number, connections_handled: number, connections_accepted: number, connections_reading: number, connections_active: number, connections_waiting: number } } export interface KongApiConfig { api: KongApi, plugins?: KongPlugin[] }
the_stack
import React from 'react'; import {Link, RouteComponentProps} from "react-router-dom"; import "./Index.less" import TankComponent from "../../common/component/TankComponent"; import TankTitle from "../widget/TankTitle"; import {Alert, Col, Row} from 'antd'; import RatePanel from "./widget/RatePanel"; import ReactEcharts from 'echarts-for-react'; import Echarts from 'echarts'; import theme from "./theme.json" import Pager from "../../common/model/base/Pager"; import Dashboard from '../../common/model/dashboard/Dashboard'; import DateUtil from '../../common/util/DateUtil'; import SortDirection from "../../common/model/base/SortDirection"; import FileUtil from "../../common/util/FileUtil"; import Matter from '../../common/model/matter/Matter'; import Lang from "../../common/model/global/Lang"; import MessageBoxUtil from "../../common/util/MessageBoxUtil"; Echarts.registerTheme('tank_theme', theme); interface IProps extends RouteComponentProps { } interface IState { } interface IpStruct { ip: string times: number } export default class Index extends TankComponent<IProps, IState> { //获取分页的一个帮助器 pager: Pager<Dashboard> = new Pager<Dashboard>(this, Dashboard, 15); //今天的统计情况 dashboard: Dashboard = new Dashboard(this) yesterdayDashboard: Dashboard = new Dashboard(this) matterPager: Pager<Matter> = new Pager<Matter>(this, Matter, 10); activeIpTop10: IpStruct[] = [] //****************作图需要的对象******************/ days: number = 15 //用来存放日期的,辅助x轴的生成 dateStrings: string[] = [] //调用量周环比 standardWeekInvokeNum: number = 0 compareWeekInvokeNum: number = 0 //调用量日环比 standardDayInvokeNum: number = 0 compareDayInvokeNum: number = 0 //UV周环比 standardWeekUv: number = 0 compareWeekUv: number = 0 //UV日环比 standardDayUv: number = 0 compareDayUv: number = 0 //文件总数周环比 standardWeekMatterNum: number = 0 compareWeekMatterNum: number = 0 //文件总数日环比 standardDayMatterNum: number = 0 compareDayMatterNum: number = 0 //文件大小周环比 standardWeekSize: number = 0 compareWeekSize: number = 0 //文件大小日环比 standardDaySize: number = 0 compareDaySize: number = 0 invokeListOption: any = { tooltip: {}, legend: { data: ['PV', 'UV'] }, xAxis: { name: Lang.t("assign.date"), data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] }, yAxis: { name: Lang.t("assign.num") }, series: [{ name: 'PV', type: 'bar', data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }, { name: 'UV', type: 'line', data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }] }; constructor(props: IProps) { super(props); this.state = {}; } componentDidMount() { this.refresh() } refresh() { this.updateDateStrings() this.refreshDashboardPager() this.refreshMatterPager() this.refreshActiveIpTop10() } updateDateStrings() { let that = this; //更新横坐标 从今天开始倒推 let arr = [] for (let d = that.days - 1; d >= 0; d--) { let thenDate = new Date((new Date()).getTime() - d * 24 * 60 * 60 * 1000) arr.push(DateUtil.simpleDate(thenDate)) } that.dateStrings = arr } //获取15日调用分时数据 refreshDashboardPager() { let that = this; this.pager.setFilterValue("orderDt", SortDirection.DESC) this.pager.httpList(function (response: any) { let list = that.pager.data if (list.length > 0) { that.dashboard.assign(list[0]) } if (list.length > 1) { that.yesterdayDashboard.assign(list[1]) } //数据转换成map,方便检索 let map: { [key: string]: Dashboard } = {} for (let i = 0; i < list.length; i++) { map[list[i].dt] = list[i] } let invokeNumData = [] let uvData = [] let matterNumData = [] let fileSizeData = [] for (let i = 0; i < that.days; i++) { invokeNumData.push(0) uvData.push(0) matterNumData.push(0) fileSizeData.push(0) } //按照日期对应。 for (let i = 0; i < that.dateStrings.length; i++) { let item = map[that.dateStrings[i]]; if (item) { invokeNumData[i] = item.invokeNum uvData[i] = item.uv matterNumData[i] = item.matterNum fileSizeData[i] = item.fileSize } } //同环比 that.standardWeekInvokeNum = 0 that.compareWeekInvokeNum = 0 //调用量日环比 that.standardDayInvokeNum = 0 that.compareDayInvokeNum = 0 //UV周环比 that.standardWeekUv = 0 that.compareWeekUv = 0 //UV日环比 that.standardDayUv = 0 that.compareDayUv = 0 //文件总数周环比 that.standardWeekMatterNum = 0 that.compareWeekMatterNum = 0 //文件总数日环比 that.standardDayMatterNum = 0 that.compareDayMatterNum = 0 //文件大小周环比 that.standardWeekSize = 0 that.compareWeekSize = 0 //文件大小日环比 that.standardDaySize = 0 that.compareDaySize = 0 for (let i = 0; i < that.days; i++) { if (i >= 0 && i <= 6) { that.standardWeekInvokeNum += invokeNumData[i] that.standardWeekUv += uvData[i] that.standardWeekMatterNum += matterNumData[i] that.standardWeekSize += fileSizeData[i] } else if (i >= 7 && i <= 13) { that.compareWeekInvokeNum += invokeNumData[i] that.compareWeekUv += uvData[i] that.compareWeekMatterNum += matterNumData[i] that.compareWeekSize += fileSizeData[i] } if (i === 12) { that.standardDayInvokeNum = invokeNumData[i] that.standardDayUv = uvData[i] that.standardDayMatterNum = matterNumData[i] that.standardDaySize = fileSizeData[i] } if (i === 13) { that.compareDayInvokeNum = invokeNumData[i] that.compareDayUv = uvData[i] that.compareDayMatterNum = matterNumData[i] that.compareDaySize = fileSizeData[i] } } that.invokeListOption.xAxis.data = that.dateStrings.map((k) => k.substr(5)) that.invokeListOption.series[0].data = invokeNumData that.invokeListOption.series[1].data = uvData that.updateUI() }) } //获取下载前10的文件 refreshMatterPager() { let that = this; that.matterPager.setFilterValue("orderTimes", SortDirection.DESC) that.matterPager.httpList() } refreshActiveIpTop10() { let that = this that.dashboard.httpActiveIpTop10(function (data: any) { that.activeIpTop10 = data that.updateUI() }) } reRun() { let that = this that.dashboard.httpEtl(function (data: any) { MessageBoxUtil.success(Lang.t("operationSuccess")) that.refresh() }) } onChartReady() { } render() { let that = this let dashboard: Dashboard = this.dashboard let yesterdayDashboard: Dashboard = this.yesterdayDashboard return ( <div className="page-dashboard-index"> <TankTitle name={Lang.t("layout.dashboard")}> </TankTitle> <Row gutter={18}> <Col xs={24} sm={24} md={12} lg={6}> <div className="text-block"> <div className="upper"> <div className="indicator">{Lang.t("dashboard.totalInvokeNum")}</div> <div className="amount">{dashboard.totalInvokeNum}</div> <div> <RatePanel name={Lang.t("dashboard.weekRate")} standardValue={this.standardWeekInvokeNum} compareValue={this.compareWeekInvokeNum}/> <RatePanel name={Lang.t("dashboard.dayRate")} standardValue={this.standardDayInvokeNum} compareValue={this.compareDayInvokeNum}/> </div> </div> <div className="lower"> {Lang.t("dashboard.yesterdayInvoke")}:{yesterdayDashboard.invokeNum} </div> </div> </Col> <Col xs={24} sm={24} md={12} lg={6}> <div className="text-block"> <div className="upper"> <div className="indicator">{Lang.t("dashboard.totalUV")}</div> <div className="amount">{dashboard.totalUv}</div> <div> <RatePanel name={Lang.t("dashboard.weekRate")} standardValue={this.standardWeekUv} compareValue={this.compareWeekUv}/> <RatePanel name={Lang.t("dashboard.dayRate")} standardValue={this.standardDayUv} compareValue={this.compareDayUv}/> </div> </div> <div className="lower"> {Lang.t("dashboard.yesterdayUV")}:{yesterdayDashboard.uv} </div> </div> </Col> <Col xs={24} sm={24} md={12} lg={6}> <div className="text-block"> <div className="upper"> <div className="indicator">{Lang.t("dashboard.totalMatterNum")}</div> <div className="amount">{dashboard.totalMatterNum}</div> <div> <RatePanel name={Lang.t("dashboard.weekRate")} standardValue={this.standardWeekMatterNum} compareValue={this.compareWeekMatterNum}/> <RatePanel name={Lang.t("dashboard.dayRate")} standardValue={this.standardDayMatterNum} compareValue={this.compareDayMatterNum}/> </div> </div> <div className="lower"> {Lang.t("dashboard.yesterdayMatterNum")}:{yesterdayDashboard.matterNum} </div> </div> </Col> <Col xs={24} sm={24} md={12} lg={6}> <div className="text-block"> <div className="upper"> <div className="indicator">{Lang.t("dashboard.totalFileSize")}</div> <div className="amount">{FileUtil.humanFileSize(dashboard.totalFileSize)}</div> <div> <RatePanel name={Lang.t("dashboard.weekRate")} standardValue={this.standardWeekSize} compareValue={this.compareWeekSize}/> <RatePanel name={Lang.t("dashboard.dayRate")} standardValue={this.standardDaySize} compareValue={this.compareDaySize}/> </div> </div> <div className="lower"> {Lang.t("dashboard.yesterdayMatterSize")}:{FileUtil.humanFileSize(yesterdayDashboard.fileSize)} </div> </div> </Col> </Row> <Row> <Col span={24}> <div className="figure-block"> <div className="title"> {Lang.t("dashboard.recentDayInvokeUV", 15)} </div> <figure> <ReactEcharts option={that.invokeListOption} notMerge={true} lazyUpdate={false} theme={"tank_theme"} onChartReady={this.onChartReady.bind(this)} showLoading={this.pager.loading} opts={{renderer: "svg"}}/> </figure> </div> </Col> </Row> <Row gutter={18}> <Col xs={24} sm={24} md={12} lg={12}> <div className="figure-block"> <div className="title"> {Lang.t("dashboard.downloadMatterTop10")} </div> <div className="list-rank"> <ul> { this.matterPager.data.map((matter: Matter, index: number) => { return ( <li key={index}> <span className={`rank ${index < 3 ? 'top3' : ''}`}>{index + 1}</span> <Link className="name" to={'/matter/detail/' + matter.uuid}>{matter.name}</Link> <span className="info">{matter.times}</span> </li> ) }) } </ul> </div> </div> </Col> <Col xs={24} sm={24} md={12} lg={12}> <div className="figure-block"> <div className="title"> {Lang.t("dashboard.activeIpTop10")} </div> <div className="list-rank"> <ul> { this.activeIpTop10.map((item: IpStruct, index: number) => { return ( <li key={index}> <span className={`rank ${index < 3 ? 'top3' : ''}`}>{index + 1}</span> <span className="name">{item.ip}</span> <span className="info">{item.times}</span> </li> ) }) } </ul> </div> </div> </Col> </Row> <div> <Alert message={<span> {Lang.t("dashboard.warnHint")} <span className="link" onClick={this.reRun.bind(this)}>{Lang.t("dashboard.reRun")}</span> </span>} type="warning" /> </div> </div> ); } }
the_stack
import { AssertionKind, BlockStatement, ClassDeclaration, CommonFlags, Expression, FieldDeclaration, IfStatement, MethodDeclaration, NodeKind, ParameterKind, ParameterNode, PropertyAccessExpression, Range, Statement, Token, TypeNode, } from "./assemblyscript"; import { djb2Hash } from "./hash"; /** * This method creates a single FunctionDeclaration that allows Reflect.equals * to validate normal class member values. * * @param {ClassDeclaration} classDeclaration - The class that requires a new function. */ export function createStrictEqualsMember( classDeclaration: ClassDeclaration, ): MethodDeclaration { const range = classDeclaration.name.range; // __aspectStrictEquals(ref: T, stackA: usize[], stackB: usize[], ignore: StaticArray<i64>): bool return TypeNode.createMethodDeclaration( TypeNode.createIdentifierExpression("__aspectStrictEquals", range), null, CommonFlags.PUBLIC | CommonFlags.INSTANCE | (classDeclaration.isGeneric ? CommonFlags.GENERIC_CONTEXT : 0), null, TypeNode.createFunctionType( [ // ref: T, createDefaultParameter( "ref", TypeNode.createNamedType( TypeNode.createSimpleTypeName(classDeclaration.name.text, range), classDeclaration.isGeneric ? classDeclaration.typeParameters!.map((node) => TypeNode.createNamedType( TypeNode.createSimpleTypeName(node.name.text, range), null, false, range, ), ) : null, false, range, ), //createGenericTypeParameter("this", range), range, ), // stack: usize[] createDefaultParameter("stack", createArrayType("usize", range), range), // cache: usize[] createDefaultParameter("cache", createArrayType("usize", range), range), // ignore: StaticArray<i64> createDefaultParameter( "ignore", TypeNode.createNamedType( TypeNode.createSimpleTypeName("StaticArray", range), [ TypeNode.createNamedType( TypeNode.createSimpleTypeName("i64", range), null, false, range, ), ], false, range, ), range, ), ], // : bool createSimpleNamedType("bool", range), null, false, range, ), createStrictEqualsFunctionBody(classDeclaration), range, ); } /** * This method creates a simple name type with the given name and source range. * * @param {string} name - The name of the type. * @param {Range} range - The given source range. */ function createSimpleNamedType(name: string, range: Range): TypeNode { return TypeNode.createNamedType( TypeNode.createSimpleTypeName(name, range), null, false, range, ); } /** * This method creates an Array<name> type with the given range. * * @param {Range} range - The source range. */ function createArrayType(name: string, range: Range): TypeNode { return TypeNode.createNamedType( TypeNode.createSimpleTypeName("Array", range), [ TypeNode.createNamedType( TypeNode.createSimpleTypeName(name, range), null, false, range, ), ], false, range, ); } /** * This method creates the entire function body for __aspectStrictEquals. * * @param {ClassDeclaration} classDeclaration - The class declaration. */ function createStrictEqualsFunctionBody( classDeclaration: ClassDeclaration, ): BlockStatement { const body = new Array<Statement>(); const range = classDeclaration.name.range; const nameHashes = new Array<number>(); // for each field declaration, generate a check for (const member of classDeclaration.members) { // if it's an instance member, regardless of access modifier if (member.is(CommonFlags.INSTANCE)) { switch (member.kind) { // field declarations automatically get added case NodeKind.FIELDDECLARATION: { const fieldDeclaration = <FieldDeclaration>member; const hashValue = djb2Hash(member.name.text); body.push( createStrictEqualsIfCheck( member.name.text, hashValue, fieldDeclaration.range, ), ); nameHashes.push(hashValue); break; } // function declarations can be getters, check the get flag case NodeKind.METHODDECLARATION: { if (member.is(CommonFlags.GET)) { const methodDeclaration = <MethodDeclaration>member; const hashValue = djb2Hash(member.name.text); body.push( createStrictEqualsIfCheck( methodDeclaration.name.text, hashValue, methodDeclaration.name.range, ), ); nameHashes.push(hashValue); } break; } } } } // if (isDefined(...)) super.__aspectStrictEquals(ref, stack, cache, ignore.concat([...props])); body.push(createSuperCallStatement(classDeclaration, nameHashes)); // return true; body.push( TypeNode.createReturnStatement(TypeNode.createTrueExpression(range), range), ); return TypeNode.createBlockStatement(body, range); } /** * This function generates a single IfStatement with a nested ReturnStatement * to validate a nested property on a given class. * * @param {string} name - The name of the property. * @param {Range} range - The source range for the given property. */ function createStrictEqualsIfCheck( name: string, hashValue: number, range: Range, ): IfStatement { const equalsCheck = TypeNode.createBinaryExpression( Token.EQUALS_EQUALS, // Reflect.equals(this.prop, ref.prop, stack, cache) TypeNode.createCallExpression( // Reflect.equals createPropertyAccess("Reflect", "equals", range), null, // types can be inferred by the compiler! // arguments [ // this.prop TypeNode.createPropertyAccessExpression( TypeNode.createThisExpression(range), TypeNode.createIdentifierExpression(name, range), range, ), // ref.prop createPropertyAccess("ref", name, range), // stack TypeNode.createIdentifierExpression("stack", range), // cache TypeNode.createIdentifierExpression("cache", range), ], range, ), createPropertyAccess("Reflect", "FAILED_MATCH", range), range, ); // !ignore.includes("prop") const includesCheck = TypeNode.createUnaryPrefixExpression( Token.EXCLAMATION, // ignore.includes("prop") TypeNode.createCallExpression( // ignore.includes TypeNode.createPropertyAccessExpression( TypeNode.createIdentifierExpression("ignore", range), TypeNode.createIdentifierExpression("includes", range), range, ), null, // (nameHash) [TypeNode.createIntegerLiteralExpression(f64_as_i64(hashValue), range)], range, ), range, ); // if (Reflect.equals(this.prop, ref.prop, stack, cache) === Reflect.FAILED_MATCH) return false; return TypeNode.createIfStatement( // Reflect.equals(this.prop, ref.prop, stack, cache) === Reflect.FAILED_MATCH TypeNode.createBinaryExpression( Token.AMPERSAND_AMPERSAND, includesCheck, equalsCheck, range, ), // return false; TypeNode.createReturnStatement( TypeNode.createFalseExpression(range), range, ), null, range, ); } /** * Create a simple default parameter with a name and a type. * * @param {string} name - The name of the parameter. * @param {TypeNode} typeNode - The type of the parameter. * @param {Range} range - The source range of the parameter. */ function createDefaultParameter( name: string, typeNode: TypeNode, range: Range, ): ParameterNode { return TypeNode.createParameter( ParameterKind.DEFAULT, TypeNode.createIdentifierExpression(name, range), typeNode, null, range, ); } /** * This method creates a single property access and passes the given range to the AST. * * @param {string} root - The name of the identifier representing the root. * @param {string} property - The name of the identifier representing the property. * @param {Range} range - The range of the property access. */ function createPropertyAccess( root: string, property: string, range: Range, ): PropertyAccessExpression { // root.property return TypeNode.createPropertyAccessExpression( TypeNode.createIdentifierExpression(root, range), TypeNode.createIdentifierExpression(property, range), range, ); } /** * This method creates the function call into super.__aspectStrictEquals, * wrapping it in a check to make sure the super function is defined first. * * @param {ClassDeclaration} classDeclaration - The given class declaration. * @param {number[]} nameHashes - A collection of hash values of the comparing class properties. */ function createSuperCallStatement( classDeclaration: ClassDeclaration, nameHashes: number[], ): Statement { const range = classDeclaration.name.range; const ifStatement = TypeNode.createIfStatement( TypeNode.createCallExpression( TypeNode.createIdentifierExpression("isDefined", range), null, [ TypeNode.createPropertyAccessExpression( TypeNode.createSuperExpression(range), TypeNode.createIdentifierExpression("__aspectStrictEquals", range), range, ), ], range, ), TypeNode.createBlockStatement( [ TypeNode.createIfStatement( TypeNode.createUnaryPrefixExpression( Token.EXCLAMATION, createSuperCallExpression(nameHashes, range), range, ), TypeNode.createReturnStatement( TypeNode.createFalseExpression(range), range, ), null, range, ), ], range, ), null, range, ); return ifStatement; } /** * This method actually creates the super.__aspectStrictEquals function call. * * @param {number[]} hashValues - The collection of hashed property name values * @param {Range} range - The super call expression range */ function createSuperCallExpression( hashValues: number[], range: Range, ): Expression { return TypeNode.createCallExpression( TypeNode.createPropertyAccessExpression( TypeNode.createSuperExpression(range), TypeNode.createIdentifierExpression("__aspectStrictEquals", range), range, ), null, [ TypeNode.createIdentifierExpression("ref", range), TypeNode.createIdentifierExpression("stack", range), TypeNode.createIdentifierExpression("cache", range), // StaticArray.concat(ignore, [... props] as StaticArray<i64>) TypeNode.createCallExpression( TypeNode.createPropertyAccessExpression( TypeNode.createIdentifierExpression("StaticArray", range), TypeNode.createIdentifierExpression("concat", range), range, ), null, [ TypeNode.createIdentifierExpression("ignore", range), // [...] as StaticArray<i64> TypeNode.createAssertionExpression( AssertionKind.AS, TypeNode.createArrayLiteralExpression( hashValues.map((e) => TypeNode.createIntegerLiteralExpression(f64_as_i64(e), range), ), range, ), TypeNode.createNamedType( TypeNode.createSimpleTypeName("StaticArray", range), [ TypeNode.createNamedType( TypeNode.createSimpleTypeName("i64", range), null, false, range, ), ], false, range, ), range, ), ], range, ), ], range, ); }
the_stack
export type MAGIC_EVENTS = | '@init' | '@enter' | '@leave' | '@change' | '@miss' | '@guard'; export type MAGIC_PHASES = '@current' | '@busy' | '@locked'; const BUSY_PHASES: MAGIC_PHASES[] = ['@busy', '@locked']; export interface InternalMachine< State, Attributes, AvailablePhases, Messages, Signals > { /** * machine attributes */ attrs: Attributes; /** * machine state */ state: State; /** * current message */ message?: Messages | MAGIC_EVENTS; /** * update machine state * @param newState */ setState(newState: Partial<State>): void; setState(cb: (oldState: State) => Partial<State>): void; /** * changes machine phase * @param phase */ transitTo(phase: AvailablePhases | MAGIC_PHASES): boolean; /** * sends a signal to the outer world * @param message * @param args */ emit(message: Signals, ...args: any[]): void; /** * sends a signal back to the machine * @param event * @param args */ trigger: (event: Messages, ...args: any[]) => void; } export type OnCallback<State, Attributes, AvalablePhases, Messages, Signals> = ( slots: InternalMachine<State, Attributes, AvalablePhases, Messages, Signals>, ...args: any[] ) => Promise<any> | any; export type AnyOnCallback = OnCallback<any, any, any, any, any>; export interface MessagePhase<Phases> { phases: Phases[]; } export interface MessageHandler<State, Attrs, Phases, OnCallback> { phases: Phases[]; callback: OnCallback; } export type MessageHandlerArray< State, Attrs, Phases, OnCallback > = MessageHandler<State, Attrs, Phases, OnCallback>[]; export type MessageHandlers<State, Attrs, Phases, Messages, OnCallback> = { [name: string]: MessageHandlerArray<State, Attrs, Phases, OnCallback>; }; export type GuardCallback<State, Attributes> = ( arg: HookArgument<any, State, Attributes> ) => boolean; export type Guards<State, Phases, Attributes> = Array<{ state: Phases[]; trap: boolean; callback: GuardCallback<State, Attributes>; }>; export type HookArgument<Messages, State, Attributes> = InternalMachine< State, Attributes, '', Messages, '' > & { message: Messages }; export type OnHookCallback<Messages, State, Attributes, T> = ( arg: HookArgument<Messages, State, Attributes> ) => T | void; export type OffHookCallback<Messages, State, Attributes, T> = ( arg: HookArgument<Messages, State, Attributes>, hookInfo: T ) => void; export type HookCallback<Messages, State, Attributes, T = any> = { on: OnHookCallback<Messages, State, Attributes, T>; off: OffHookCallback<Messages, State, Attributes, T>; }; export type AnyHookCallback = HookCallback<any, any, any>; export type Hooks<State, Attributes, Messages extends string> = { [K in Messages]?: HookCallback<Messages, State, Attributes> }; export type Callbag<T, K> = (state: 0 | 1 | 2, payload: T) => K; export type FasteInstanceHooks<MessageHandlers, FasteHooks, FasteGuards> = { handlers: MessageHandlers; hooks: FasteHooks; guards: FasteGuards; }; export type FastInstanceState<State, Attributes, Phases, Messages, Signals> = { state: State; attrs: Attributes; phase?: Phases | MAGIC_PHASES; instance?: InternalMachine<State, Attributes, Phases, Messages, Signals>; }; export type ConnectCall<Signals> = (event: Signals, args: any[]) => void; const callListeners = ( listeners: ((...args: any[]) => void)[], ...args: any[] ) => listeners.forEach(listener => listener(...args)); export type debugCallback = ( instance: any, event: string, ...args: any[] ) => any; let debugFlag: boolean | debugCallback = false; const debug = (instance: any, event: string, ...args: any[]) => { if (debugFlag) { if (typeof debugFlag === 'function') { debugFlag(instance, event, ...args); } else { console.debug( 'Faste:', instance.name ? instance.name : instance, event, ...args ); } } }; /** * enabled debug * @param flag */ export const setFasteDebug = (flag: debugCallback) => (debugFlag = flag); export interface FastePutable<Messages> { put(message: Messages | MAGIC_EVENTS, ...args: any[]): this; } export class FasteInstance< State, Attributes, Phases, Messages, Signals, MessageHandlers, FasteHooks, FasteGuards extends Guards<any, any, any> > { private state: FastInstanceState< State, Attributes, Phases, Messages, Signals >; private handlers: FasteInstanceHooks< MessageHandlers, FasteHooks, FasteGuards >; private stateObservers: ((phase: Phases) => void)[]; private messageObservers: ConnectCall<Signals>[]; private messageQueue: ({ message: Messages | MAGIC_EVENTS; args: any })[]; private callDepth: number; private handlersOffValues: any; private _started: boolean = false; public name: string; constructor( state: FastInstanceState<State, Attributes, Phases, Messages, Signals>, handlers: FasteInstanceHooks<MessageHandlers, FasteHooks, FasteGuards> ) { this.state = { ...state }; this.state.instance = this._createInstance({}); this.handlers = { ...handlers }; this.handlersOffValues = {}; this.stateObservers = []; this.messageObservers = []; } private _collectHandlers( phase: Phases | MAGIC_PHASES ): { [key: string]: boolean } { const h = this.handlers.handlers as any; return Object.keys(h) .filter(handler => h[handler].some( (hook: MessagePhase<Phases | MAGIC_PHASES>) => !hook.phases || hook.phases.indexOf(phase) >= 0 ) ) .reduce((acc, key) => ({ ...acc, [key]: true }), {}); } private _setState(newState: Partial<State>) { const oldState = this.state.state; this.state.state = Object.assign({}, oldState, newState); this.put('@change', oldState); } private _trySingleGuard( phase: Phases | MAGIC_PHASES, isTrap: boolean ): boolean { const instance = this._createInstance({ phase: phase }); // find traps return this.handlers.guards .filter(({ state, trap }) => state.indexOf(phase) >= 0 && trap === isTrap) .reduce((acc, { callback }) => acc && callback(instance as any), true); } private _tryGuard( oldPhase: Phases | MAGIC_PHASES, newPhase: Phases | MAGIC_PHASES ): boolean { return ( this._trySingleGuard(oldPhase, true) && this._trySingleGuard(newPhase, false) ); } private _transitTo(phase: Phases | MAGIC_PHASES) { const oldPhase = this.state.phase; debug(this, 'transit', phase); if (oldPhase != phase) { if (!this._tryGuard(oldPhase, phase)) { this.__put('@guard', phase); return false; } if (oldPhase) { this.__put('@leave', phase); } this.__performHookOn(phase); this.state.phase = phase; if (!this._started) { this.__put('@init'); this._started = true; } this.__put('@enter', oldPhase); callListeners(this.stateObservers, phase); if (BUSY_PHASES.indexOf(phase as any) === -1) { if (!this.callDepth) { this._executeMessageQueue(); } } } return true; } private _createInstance(options: { phase?: Phases | MAGIC_PHASES; message?: Messages | MAGIC_EVENTS; }): InternalMachine<State, Attributes, Phases, Messages, Signals> { return { state: this.state.state, attrs: this.state.attrs, message: options.message, setState: ( newState: Partial<State> | ((state: State) => Partial<State>) ) => typeof newState === 'function' ? this._setState(newState(this.state.state)) : this._setState(newState), transitTo: (phase: Phases | MAGIC_PHASES) => this._transitTo(phase === '@current' ? options.phase : phase), emit: (message: Signals, ...args: any[]) => callListeners(this.messageObservers, message, ...args), trigger: (event: Messages, ...args: any[]) => this.put(event, ...args) }; } private __performHookOn(nextPhase: Phases | MAGIC_PHASES | null) { const oldHandlers = this._collectHandlers(this.state.phase); const newHandlers = nextPhase ? this._collectHandlers(nextPhase) : {}; const instance = this._createInstance({ phase: this.state.phase }); const h = this.handlers.hooks as any; Object.keys(newHandlers).forEach(handler => { if (!oldHandlers[handler] && h[handler]) { debug(this, 'hook-on', h[handler]); this.handlersOffValues[handler] = h[handler].on({ ...instance, message: handler }); } }); Object.keys(oldHandlers).forEach(handler => { if (!newHandlers[handler] && h[handler]) { debug(this, 'hook-off', h[handler]); h[handler].off( { ...instance, message: handler }, this.handlersOffValues[handler] ); } }); } private __put(event: string, ...args: any[]) { debug(this, 'put', event, args); const h: any = this.handlers.handlers; const handlers: MessageHandler< State, Attributes, Phases, (state: any, ...args: any[]) => void >[] = h[event] as any; let hits = 0; const assertBusy = (result: Promise<any> | any) => { if (BUSY_PHASES.indexOf(this.state.phase as any) >= 0) { if (result && 'then' in result) { // this is async handler } else { throw new Error( 'faste: @busy should only be applied for async handlers' ); } } }; // Precache state, to prevent message to be passed to the changed state const phase = this.state.phase; if (handlers) { const instance = this._createInstance({ phase, message: event as any }); handlers.forEach(handler => { if (handler.phases && handler.phases.length > 0) { if (handler.phases.indexOf(phase as any) >= 0) { debug(this, 'message-handler', event, handler); assertBusy(handler.callback(instance, ...args)); hits++; } } else { debug(this, 'message-handler', event, handler); assertBusy(handler.callback(instance, ...args)); hits++; } }); } if (!hits) { if (event[0] !== '@') { this.__put('@miss', event); } } } _executeMessageQueue() { if (this.messageQueue.length) { const q = this.messageQueue; this.messageQueue = []; q.forEach(q => this.put(q.message, ...q.args)); } } /** * sets name to a machine (debug only) * @param n */ namedBy(n: string) { this.name = n; } /** * starts the machine * @param phase */ start(phase?: Phases): this { this.messageQueue = []; this.callDepth = 0; this._started = false; if (phase) { if (!this._transitTo(phase)) { throw new Error( 'Faste machine initialization failed - phase was rejected' ); } } else { this.__put('@init'); this._started = true; } return this; } /** * sets attributes * @param attrs */ attrs(attrs: Attributes): this { this.state.attrs = Object.assign({}, this.state.attrs || {}, attrs); return this; } /** * put the message in * @param {String} message * @param {any} args */ put(message: Messages | MAGIC_EVENTS, ...args: any[]): this { if (this.callDepth) { debug(this, 'queue', message, args); this.messageQueue.push({ message, args }); } else { switch (this.state.phase) { case '@locked': debug(this, 'locked', message, args); break; //nop case '@busy': debug(this, 'queue', message, args); this.messageQueue.push({ message, args }); break; default: this.callDepth++; this.__put(message as string, ...args); this.callDepth--; if (!this.callDepth) { this._executeMessageQueue(); } } } // find return this; } /** * Connects one machine to another * @param plug */ connect(plug: FastePutable<Signals> | ConnectCall<Signals>): this { if ('put' in plug) { this.messageObservers.push((event: Signals, ...args: any[]) => plug.put(event, ...args) ); } else { this.messageObservers.push(plug); } return this; } /** * adds change observer. Observer could not be removed. * @param callback */ observe(callback: (phase: Phases) => void): this { this.stateObservers.push(callback); return this; } /** * returns the current phase */ phase(): Phases | MAGIC_PHASES { return this.state.phase; } /** * return an internal instance */ instance(): InternalMachine<State, Attributes, Phases, Messages, Signals> { return this._createInstance({}); } /** * destroys the machine */ destroy(): void { this.__performHookOn(undefined); this.stateObservers = []; } } export type SomethingOf<T extends string, K extends T> = Partial<K>; export type PhaseTransition<T extends string, K> = { [key in T]: K }; export type PhaseTransitionSetup< K extends string, T extends PhaseTransition<K, Partial<K>> > = { [key in keyof T]: T[key][] }; /** * The Faste machine * @name Faste */ export class Faste< State extends object = {}, Attributes extends object = {}, Phases extends string = any, Transitions extends PhaseTransition< Phases, Partial<Phases> > = PhaseTransition<Phases, Phases>, Messages extends string = any, Signals extends string = any, OnCall = OnCallback<State, Attributes, Phases, Messages, Signals>, FasteMessageHandlers = MessageHandlers< State, Attributes, Phases, Messages, OnCall >, FasteHooks = Hooks<State, Attributes, Phases> > { private fState: State; private fAttrs: Attributes; private fHandlers: MessageHandlers< State, Attributes, Phases, Messages, OnCall >; private fHooks: FasteHooks; private fGuards: Guards<State, Phases, Attributes>; constructor( state?: State, attrs?: Attributes, messages?: FasteMessageHandlers, hooks?: FasteHooks, guards?: Guards<State, Phases, Attributes> ) { this.fState = state; this.fAttrs = attrs; this.fHandlers = messages || ({} as any); this.fHooks = hooks || ({} as FasteHooks); this.fGuards = guards || []; } /** * Adds event handler * @param {String} eventName * @param {String[]} phases * @param callback * * @example machine.on('disable', ['enabled'], ({transitTo}) => transitTo('disabled'); */ public on<K extends Phases>( eventName: Messages, phases: K[], callback: OnCallback<State, Attributes, Transitions[K], Messages, Signals> ): this; // on(eventName: Messages, phases: Phases[], callback: OnCall): this; /** * Adds event handler * @param {String} eventName * @param callback */ public on(eventName: Messages, callback: OnCall): this; /** * Adds event handler * @param args */ public on(...args: any[]): this { if (args.length == 2) { return this._addHandler(args[0], null, args[1]); } else if (args.length == 3) { return this._addHandler(args[0], args[1], args[2]); } return null; } private _addHandler( eventName: Messages, phases: Phases[], callback: OnCall ): this { this.fHandlers[eventName] = this.fHandlers[eventName] || []; this.fHandlers[eventName].push({ phases, callback }); return this; } /** * Adds hooks to the faste machine * @param hooks * * @example machine.hooks({ * click: { * on: onCallback, * off: offCallback, * }}); */ public hooks(hooks: Hooks<State, Attributes, Messages>): this { Object.assign(this.fHooks, hooks); return this; } /** * Adds a guard, which may block transition TO the phase * @param {String[]} state * @param callback */ public guard( state: Phases[], callback: GuardCallback<State, Attributes> ): this { this.fGuards.push({ state, callback, trap: false }); return this; } /** * Add a trap, which may block transition FROM the phase * @param state * @param callback */ public trap( state: Phases[], callback: GuardCallback<State, Attributes> ): this { this.fGuards.push({ state, callback, trap: true }); return this; } /** * checks that machine is build properly */ public check(): boolean { return true; } /** * Executes callback inside faste machine, could be used to reuse logic among different machines * @param {Function }swapper * * @example machine.scope( machine => machine.on('something'); */ scope(swapper: (stateIn: this) => void): this { swapper(this); return this; } /** * creates a Faste Machine from a blueprint */ create(): FasteInstance< State, Attributes, Phases, Messages, Signals, MessageHandlers<State, Attributes, Phases, Messages, OnCall>, FasteHooks, Guards<State, Phases, Attributes> > { return new FasteInstance( { state: this.fState, attrs: this.fAttrs, phase: undefined, instance: undefined }, { handlers: this.fHandlers, hooks: this.fHooks, guards: this.fGuards } ); // as any } /** * Defines the State * @param state */ withState<T extends object>( state?: T ): Faste<T, Attributes, Phases, Transitions, Messages, Signals> { return new Faste(state, this.fAttrs, this.fHandlers, this.fHooks, this .fGuards as any); } /** * Defines the Attributes * @param attributes */ withAttrs<T extends object>( attributes?: T ): Faste<State, T, Phases, Transitions, Messages, Signals> { return new Faste(this.fState, attributes, this.fHandlers, this.fHooks, this .fGuards as any); } /** * Defines possible Phases * @param phases */ withPhases<T extends string>( phases?: T[] ): Faste<State, Attributes, T, PhaseTransition<T, T>, Messages, Signals> { return this as any; } /** * Defines possible Phases Transitions * @param transitions */ withTransitions<T extends PhaseTransition<Phases, Partial<Phases>>>( transitions: PhaseTransitionSetup<Phases, T> ): Faste<State, Attributes, Phases, T, Messages, Signals> { return this as any; } /** * Defines possible "in" events * @param messages */ withMessages<T extends string>( messages?: T[] ): Faste<State, Attributes, Phases, Transitions, T | MAGIC_EVENTS, Signals> { return this as any; } /** * Defines possible "out" events * @param signals */ withSignals<T extends string>( signals?: T[] ): Faste<State, Attributes, Phases, Transitions, Messages, T> { return this as any; } } /** * Creates a faste machine */ export function faste(): Faste { return new Faste(); }
the_stack
import { Writable } from 'stream'; import cheerio = require('cheerio'); /** * Key and certificate to be passed to https.createServer() * See supported formats [here](https://nodejs.org/api/tls.html#tls_tls_createsecurecontext_options) */ export interface CertificateParams { cert: string | string[] | Buffer | Buffer[]; key: string | string[] | Buffer | Buffer[] | object[]; } export interface Slow { /** * Imposes a delay (in milliseconds) between all requests and responses */ rate: number; /** * Imposes a single rate-limiting bottleneck (in bytes per second) on all throughput */ latency: number; /** * Imposes a single rate-limiting bottleneck (in bytes per second) on all uploads */ up: number; /** * Imposes a single rate-limiting bottleneck (in bytes per second) on all downloads */ down: number; } export interface CreateServerOptions { /** * If present, this proxy will in turn use another proxy. * This allows Hoxy to play well with other proxies. * This value should take the form host:port */ upstreamProxy?: string | undefined; /** * If present, this proxy will run as a reverse proxy for the given server. * This allows you to point your client directly at the proxy, instead of * configuring it in the client's proxy settings. * This value should take the form scheme://host:port. */ reverse?: string | undefined; /** * If present, this should contain a key/cert combo representing a certificate * authority that your client trusts. See these instructions for how to * generate these files. You'll then need to configure your client to use this * proxy for https in addition to http. Once you've got all of that set up, * Hoxy will generate fake keys/cert combos for every hostname you visit, * caching them in memory for subsequent visits, thus allowing the proxy to * handle https requests as cleartext */ certAuthority?: CertificateParams | undefined; /** * Should only be used in combination with reverse. If present, causes Hoxy to * run as an https server. Passed as opts to https.createServer(opts, function) */ tls?: CertificateParams | undefined; /** * Latency emulation */ slow?: Slow | undefined; } /** * Factory for a new proxy with given options * @param opts - Options to be passed in constructor */ export function createServer(opts?: CreateServerOptions): Proxy; /** * Request phase */ export type Phase = 'request' | 'request-sent' | 'response' | 'response-sent'; /** * Body parsers */ export type BodyParser = '$' | 'json' | 'params' | 'buffer' | 'string'; export type TesterFunction<T> = (arg: T) => boolean; export type Filter<T> = RegExp | TesterFunction<T> | T; export interface InterceptOptions { /** * Request phase to listen to */ phase: Phase; /** * Body-parsers */ as?: BodyParser | undefined; /** * Match the request protocol */ protocol?: Filter<string> | undefined; /** * Match the all-uppercase HTTP request method */ method?: Filter<HttpMethod> | undefined; /** * Match the host, not including :port. */ hostname?: Filter<string> | undefined; /** * Match the port number. */ port?: Filter<number | string> | undefined; /** * Match the request URL. Patterns like /foo/* are allowed */ url?: Filter<string> | undefined; /** * Match the full request URL including protocol and hostname. * Patterns like /foo/* are allowed */ fullUrl?: Filter<string> | undefined; /** * Match the full content-type header of the request or * response (depending on the phase) */ contentType?: Filter<string> | undefined; /** * Same as contentType but only matches request */ requestContentType?: Filter<string> | undefined; /** * Same as contentType but only matches response */ responseContentType?: Filter<string> | undefined; /** * Match just the mime type portion of the content-type header * of the request or response (depending on the phase). I.e., * if the entire header is "text/html; charset=utf-8", just * match the "text/html" part */ mimeType?: Filter<string> | undefined; /** * Same as mimeType but only matches request */ requestMimeType?: Filter<string> | undefined; /** * Same as mimeType but only matches response */ responseMimeType?: Filter<string> | undefined; } /** * Request method */ export type HttpMethod = 'POST' | 'GET' | 'PUT' | 'PATCH' | 'DELETE'; export class Request { private constructor(); /** * Protocol of the request */ protocol: string; /** * Destination server hostname, sans port */ hostname: string; /** * Destination server port */ port: number; /** * All-caps HTTP method used. Lowercase values are converted to uppercase */ method: HttpMethod; /** * HTTP request header name/value JS object. These are all-lowercase, e.g. accept-encoding */ headers: Record<string, string>; /** * Root-relative request URL, including query string, like /foo/bar?baz=qux */ url: string; /** * An object representing querystring params in the URL. * For example if the URL is /foo/bar?baz=qux, then this * object will look like { baz: 'qux' }. */ query: Record<string, string>; /** * Request body parsed as JSON. This is only present if you intercept the * request as:'json'. Changes made to this object will be seen by the server. */ json?: Record<string, any> | undefined; /** * Request body parsed as form-url-encoded params. This will be a key/value * object. This object will only present if you intercept the request * as:'params'. Changes made to this object will be seen by the server. * * Note: parameters from the URL querystring are not included in this object. */ params?: Record<string, string> | undefined; /** * Request body string. This is only present if you intercept the request * as:'string'. Overwriting this will overwrite the request body sent to * the server. */ string?: string | undefined; /** * Request body binary buffer. This is only present if you intercept the * request as:'buffer'. Changes made to this object will be seen by the server. */ buffer?: Buffer | undefined; /** * Simulates slowness during request phase. With this method you can set a minimum * latency and/or maximum transfer rate. Since these are minimum/maximum, if your * native connection is already slower than these values, this method will have no * effect. */ slow(opts: Partial<Slow>): void; /** * If url is provided, sets the request's absolute protocol, hostname, port and * url. Otherwise it returns the absolute URL of this request. This is mainly a * convenience method. */ fullUrl(url?: string): string; /** * Whatever request body gets sent to the server, tee() pipes an identical copy * to your writable stream. Your stream is held in memory, and only gets written * to if and when the request is sent to the server. In other words, your stream * sees whatever the server sees. If the server sees nothing, your stream sees * nothing. You can tee() as many times as you want. * * @param stream - target stream */ tee(stream: Writable): void; } export class Response { private constructor(); /** * HTTP status code being sent to the client. */ statusCode: number; /** * HTTP response header name/value JS object. Header names are all-lowercase, * such as 'content-type'. */ headers: Record<string, string>; /** * Response body parsed as DOM. This object is only present if you intercept * the response as:'$'. This is a cheerio object, which provides a jQuery-like * API. Changes made to it will be seen by the client. */ $?: ReturnType<typeof cheerio> | undefined; /** * Response body parsed as JSON. This is only present if you intercept the * response as:'json'. Changes to this object will be seen by the client. */ json?: any; /** * Response body string. This is only present if you intercept the response * as:'string'. Overwriting this will overwrite the response body sent to the * client. */ string?: string | undefined; /** * Response body binary buffer. This is only present if you intercept the * response as:'buffer'. Changes made to this object will be seen by the client. */ buffer?: Buffer | undefined; /** * Simulates slowness during request phase. With this method you can set a minimum * latency and/or maximum transfer rate. Since these are minimum/maximum, if your * native connection is already slower than these values, this method will have no * effect. */ slow(opts: Partial<Slow>): void; /** * Whatever request body gets sent to the server, tee() pipes an identical copy * to your writable stream. Your stream is held in memory, and only gets written * to if and when the request is sent to the server. In other words, your stream * sees whatever the server sees. If the server sees nothing, your stream sees * nothing. You can tee() as many times as you want. * * @param stream - target stream */ tee(stream: Writable): void; } export type ServeStrategy = 'replace' | 'overlay' | 'mirror'; export interface ServeOptions { /** * Which file to serve. Defaults to the request URL. Normally this would * be used in mutual exclusion with docroot. Strictly speaking, path is * always rooted to docroot, which defaults to "/" */ path?: string | undefined; /** * Which local directory to serve out of. Defaults to filesystem root "/" */ docroot?: string | undefined; /** * Mainly relevant when using the docroot option. Describes the relationship * between the local docroot and the remote one. Strictly speaking, this * controls what happens when the local docroot is missing a requested file. * Accepted values: * * replace - (default) Replaces the remote docroot with the local one. In * other words, if a requested file doesn't exist locally, it populates the * response with a 404, even if it would have been found remotely. * * overlay - Overlays the local docroot on top of the remote one. In other * words, if a requested file doesn't exist locally, the request will * transparently fall through to the remote server. * * mirror - Automatically mirror the remote docroot locally. In other words, * if a requested file doesn't exist locally, it's copied to the local docroot * from the remote one, and will be found locally on subsequent requests. */ strategy?: ServeStrategy | undefined; } /** * Represents a whole request/response cycle. A Cycle instance is this in all * interceptor calls, and the same instance is shared across an entire * request/response cycle. It's also passed as the third argument, in order * to support arrow functions. It provides a small number of methods not * associated specifically to either the request or response. */ export class Cycle { private constructor(); /** * Provisions responses from the local filesystem. Generally, the reason you'd do * this is to be able to edit those files locally and test them as if they were * live on the remote server. This action populates the response object; see * response population for more info. The completion of this action is asynchronous, * so serve() returns a promise. * * The returned promise resolves after the response has been populated. There are at * least three use cases worth mentioning. */ serve(opts?: string | ServeOptions): Promise<void>; /** * Stores and retrieves data on a cycle instance. This is useful since the same * instance is shared across all interceptors for a given request/response cycle, * allowing you to share related data across disparate scopes. With two params this * method behaves as a setter, with one param as a getter. */ data(name: string, value?: any): any; } export type InterceptionHandler = (this: Proxy, req: Request, res: Response, cycle: Cycle) => Promise<void> | void; export type LogLevel = 'error' | 'warn' | 'info' | 'debug'; export interface Log { level: LogLevel; error?: Error | undefined; message: string; } export type LoggerCallbackFunction = (log: Log) => any; export type PossibleErrorCallback = (err?: Error) => any; export class Proxy { protected constructor(opts: CreateServerOptions); /** * Starts proxy listening on port. Returns itself. * A callback may be provided, to run when the proxy has started listening. * This method simply passes its arguments to Node's server.listen() method. */ listen(port: number, callback?: () => void): this; listen(port: number, host: string, callback?: () => void): this; listen(port: number, host: string, backlog: number, callback?: () => void): this; /** * This is the entry point for intercepting and operating on requests and responses. * This first example intercepts all requests: * ```javascript * proxy.intercept('request', req => console.log(req.url)); * ``` * This is more verbose, but identical to the above: * ```javascript * proxy.intercept({ * phase: 'request' * }, function(req, resp, cycle) { * console.log(req.url); * }); * ``` */ intercept(opts: string | InterceptOptions, handler: InterceptionHandler): void; /** * Get/set proxy-level slow options. If options is provided, it's a setter. * If options is not provided, it's a getter. * @param opts */ slow(opts: Slow): this; /** * Deals with various logging events. * * This first example listens for error, * warn, and debug logging events, and prints them to stderr: * ```javascript * proxy.log('error warn debug'); * ``` * Or, print logging events to various writable streams: * ```javascript * proxy.log('error warn debug', process.stderr); * proxy.log('info', process.stdout); * ``` * * Or, explicitly handle logging event: * ```javascript * proxy.log('error warn', function(event) { * console.error(event.level + ': ' + event.message); * if (event.error) console.error(event.error.stack); * }); * ``` */ log(levels: string, cb?: LoggerCallbackFunction | Writable): this; /** * Stops proxy receiving requests. Finalizes and/or cleans up any * resources the proxy uses internally. */ close(cb?: PossibleErrorCallback): void; }
the_stack
import { BezierNode } from '@0b5vr/automaton'; import { Colors } from '../constants/Colors'; import { MouseComboBit, mouseCombo } from '../utils/mouseCombo'; import { Resolution } from '../utils/Resolution'; import { TimeValueRange, dt2dx, dv2dy, dx2dt, dy2dv, snapTime, snapValue, t2x, v2y, x2t, y2v } from '../utils/TimeValueRange'; import { WithID } from '../../types/WithID'; import { arraySetHas } from '../utils/arraySet'; import { registerMouseEvent } from '../utils/registerMouseEvent'; import { useDispatch, useSelector } from '../states/store'; import { useDoubleClick } from '../utils/useDoubleClick'; import React, { useCallback } from 'react'; import styled from 'styled-components'; // == styles ======================================================================================= const NodeBody = styled.circle<{ isSelected: boolean }>` fill: ${ ( { isSelected } ) => ( isSelected ? Colors.accent : Colors.back1 ) }; stroke: ${ Colors.accent }; stroke-width: 0.125rem; cursor: pointer; pointer-events: auto; `; const HandleLine = styled.line` stroke: ${ Colors.accent }; stroke-width: 0.0625rem; `; const HandleCircle = styled.circle` fill: ${ Colors.accent }; cursor: pointer; pointer-events: auto; `; const Root = styled.g` pointer-events: none; `; // == element ====================================================================================== const CurveEditorNode = ( props: { curveId: string; node: BezierNode & WithID; range: TimeValueRange; size: Resolution; } ): JSX.Element => { const { node, range, size, curveId } = props; const { guiSettings, automaton } = useSelector( ( state ) => ( { guiSettings: state.automaton.guiSettings, automaton: state.automaton.instance } ) ); const dispatch = useDispatch(); const checkDoubleClick = useDoubleClick(); const curve = automaton?.getCurveById( curveId ) || null; const selectedNodes = useSelector( ( state ) => state.curveEditor.selected.nodes ); const grabNode = useCallback( (): void => { if ( !curve ) { return; } const timePrev = node.time; const valuePrev = node.value; let x = t2x( timePrev, range, size.width ); let y = v2y( valuePrev, range, size.height ); let time = timePrev; let value = valuePrev; let hasMoved = false; registerMouseEvent( ( event, movementSum ) => { hasMoved = true; x += movementSum.x; y += movementSum.y; const holdTime = event.ctrlKey || event.metaKey; const holdValue = event.shiftKey; const ignoreSnap = event.altKey; time = holdTime ? timePrev : x2t( x, range, size.width ); value = holdValue ? valuePrev : y2v( y, range, size.height ); if ( !ignoreSnap ) { if ( !holdTime ) { time = snapTime( time, range, size.width, guiSettings ); } if ( !holdValue ) { value = snapValue( value, range, size.height, guiSettings ); } } curve.moveNodeTime( node.$id, time ); curve.moveNodeValue( node.$id, value ); }, () => { if ( !hasMoved ) { return; } curve.moveNodeTime( node.$id, time ); curve.moveNodeValue( node.$id, value ); dispatch( { type: 'History/Push', description: 'Move Node', commands: [ { type: 'curve/moveNodeTime', curveId, node: node.$id, time, timePrev }, { type: 'curve/moveNodeValue', curveId, node: node.$id, value, valuePrev } ] } ); } ); }, [ node, curve, curveId, range, size, guiSettings, dispatch ] ); const removeNode = useCallback( (): void => { if ( !curve ) { return; } if ( curve.isFirstNode( node.$id ) ) { return; } curve.removeNode( node.$id ); dispatch( { type: 'History/Push', description: 'Remove Node', commands: [ { type: 'curve/removeNode', curveId, data: node } ], } ); }, [ node, curve, dispatch, curveId ] ); const handleNodeClick = useCallback( ( event ) => mouseCombo( event, { [ MouseComboBit.LMB ]: () => { if ( checkDoubleClick() ) { removeNode(); } else { dispatch( { type: 'CurveEditor/SelectItems', nodes: [ node.$id ] } ); grabNode(); } } } ), [ checkDoubleClick, removeNode, dispatch, node.$id, grabNode ] ); const grabHandle = useCallback( ( dir: 'in' | 'out' ): void => { if ( !curve ) { return; } const tPrev = node[ dir === 'in' ? 'inTime' : 'outTime' ]; const vPrev = node[ dir === 'in' ? 'inValue' : 'outValue' ]; const dirOp = dir === 'in' ? 'out' : 'in'; const tOpPrev = node[ dir === 'in' ? 'outTime' : 'inTime' ]; const vOpPrev = node[ dir === 'in' ? 'outValue' : 'inValue' ]; const xPrev = dt2dx( tPrev, range, size.width ); const yPrev = dv2dy( vPrev, range, size.height ); const slPrev = Math.sqrt( xPrev * xPrev + yPrev * yPrev ); const nxPrev = xPrev / slPrev; const nyPrev = yPrev / slPrev; const xOpPrev = dt2dx( tOpPrev, range, size.width ); const yOpPrev = dv2dy( vOpPrev, range, size.height ); const slOpPrev = Math.sqrt( xOpPrev * xOpPrev + yOpPrev * yOpPrev ); let x = xPrev; let y = yPrev; let time = tPrev; let value = vPrev; let tOp = tOpPrev; let vOp = vOpPrev; let hasMoved = false; registerMouseEvent( ( event, movementSum ) => { hasMoved = true; x += movementSum.x; y += movementSum.y; const holdDir = event.shiftKey; const moveBoth = event.ctrlKey || event.metaKey; const independent = event.altKey; let xDash = x; let yDash = y; if ( holdDir ) { const dot = x * nxPrev + y * nyPrev; xDash = dot * nxPrev; yDash = dot * nyPrev; } time = dx2dt( xDash, range, size.width ); value = dy2dv( yDash, range, size.height ); if ( independent ) { tOp = tOpPrev; vOp = vOpPrev; } else if ( moveBoth ) { tOp = -time; vOp = -value; } else { const sl = Math.sqrt( xDash * xDash + yDash * yDash ); const nxDash = xDash / sl; const nyDash = yDash / sl; tOp = -dx2dt( slOpPrev * nxDash, range, size.width ); vOp = -dy2dv( slOpPrev * nyDash, range, size.height ); } curve.moveHandleTime( node.$id, dir, time ); curve.moveHandleValue( node.$id, dir, value ); curve.moveHandleTime( node.$id, dirOp, tOp ); curve.moveHandleValue( node.$id, dirOp, vOp ); }, () => { if ( !hasMoved ) { return; } curve.moveHandleTime( node.$id, dir, time ); curve.moveHandleValue( node.$id, dir, value ); curve.moveHandleTime( node.$id, dirOp, tOp ); curve.moveHandleValue( node.$id, dirOp, vOp ); dispatch( { type: 'History/Push', description: 'Move Handle', commands: [ { type: 'curve/moveHandleTime', curveId, node: node.$id, dir, time, timePrev: tPrev }, { type: 'curve/moveHandleTime', curveId, node: node.$id, dir: dirOp, time: tOp, timePrev: tOpPrev }, { type: 'curve/moveHandleValue', curveId, node: node.$id, dir, value, valuePrev: vPrev }, { type: 'curve/moveHandleValue', curveId, node: node.$id, dir: dirOp, value: vOp, valuePrev: vOpPrev } ], } ); } ); }, [ node, curve, curveId, range, size, dispatch ] ); const removeHandle = useCallback( ( dir: 'in' | 'out' ): void => { if ( !curve ) { return; } const timePrev = node[ dir === 'in' ? 'inTime' : 'outTime' ]; const valuePrev = node[ dir === 'in' ? 'inValue' : 'outValue' ]; curve.moveHandleTime( node.$id, dir, 0.0 ); curve.moveHandleValue( node.$id, dir, 0.0 ); dispatch( { type: 'History/Push', description: 'Remove Handle', commands: [ { type: 'curve/moveHandleTime', curveId, node: node.$id, dir, time: 0.0, timePrev }, { type: 'curve/moveHandleValue', curveId, node: node.$id, dir, value: 0.0, valuePrev } ], } ); }, [ node, curve, dispatch, curveId ] ); const handleHandleInClick = useCallback( ( event ) => mouseCombo( event, { [ MouseComboBit.LMB ]: () => { if ( checkDoubleClick() ) { removeHandle( 'in' ); } else { grabHandle( 'in' ); } } } ), [ checkDoubleClick, removeHandle, grabHandle ] ); const handleHandleOutClick = useCallback( ( event ) => mouseCombo( event, { [ MouseComboBit.LMB ]: () => { if ( checkDoubleClick() ) { removeHandle( 'out' ); } else { grabHandle( 'out' ); } } } ), [ checkDoubleClick, removeHandle, grabHandle ] ); return ( <Root transform={ `translate(${ t2x( node.time, range, size.width ) },${ v2y( node.value, range, size.height ) })` } > <HandleLine x2={ dt2dx( node.inTime, range, size.width ) } y2={ dv2dy( node.inValue, range, size.height ) } /> <HandleCircle r="4" transform={ `translate(${ dt2dx( node.inTime, range, size.width ) },${ dv2dy( node.inValue, range, size.height ) })` } onMouseDown={ handleHandleInClick } /> <HandleLine x2={ dt2dx( node.outTime, range, size.width ) } y2={ dv2dy( node.outValue, range, size.height ) } /> <HandleCircle r="4" transform={ `translate(${ dt2dx( node.outTime, range, size.width ) },${ dv2dy( node.outValue, range, size.height ) })` } onMouseDown={ handleHandleOutClick } /> <NodeBody as="circle" r="5" isSelected={ arraySetHas( selectedNodes, node.$id ) } onMouseDown={ handleNodeClick } /> </Root> ); }; export { CurveEditorNode };
the_stack
import { Nullable } from "../../../shared/types"; import * as React from "react"; import { Dialog, Classes, MenuItem, Button, Callout, InputGroup, RadioGroup, Radio, Divider, Switch, Intent, NumericInput, FormGroup } from "@blueprintjs/core"; import { Suggest } from "@blueprintjs/select"; import { Animation, Color3, Color4, IAnimatable, Quaternion, Vector2, Vector3 } from "babylonjs"; import { Tools } from "../../editor/tools/tools"; const PropertyPathSuggest = Suggest.ofType<string>(); export interface IAddAnimationProps { /** * Defines the callback called on the animation has been added. */ onAnimationAdded: (animation: Animation) => void; } export interface IAddAnimationState { /** * Defines wether or not the dialog is opened. */ isOpened: boolean; /** * Defines the reference to the selected animatable. */ selectedAnimatable: Nullable<IAnimatable>; /** * Defines the name of the animation. */ animationName: string; /** * Defines the current value being drawn in the input. */ targetProperty: string; /** * Defines the list of items to be drawn in the suggest. */ items: string[]; /** * Defines the type of the animation (float, vector, etc.). */ animationType: string; /** * Defines wether or not blending is enabled for the animation. */ enableBlending: boolean; /** * Defines the number of frames per second for the animation. */ framesPerSecond: number; } export class AddAnimation extends React.Component<IAddAnimationProps, IAddAnimationState> { /** * Defines the hidden properties due to usage of property descriptors in Babylon.JS */ private static _HiddenProperties: string[] = [ "position", "rotation", "scaling", "rotationQuaternion", "material", "target", "x", "y", "z", "alpha", ]; /** * Constructor. * @param props defines the component's props. */ public constructor(props: IAddAnimationProps) { super(props); this.state = { targetProperty: "", items: [], isOpened: false, selectedAnimatable: null, animationName: "New Animation", animationType: "ANIMATIONTYPE_FLOAT", enableBlending: false, framesPerSecond: 60, }; } /** * Renders the component. */ public render(): React.ReactNode { return ( <Dialog usePortal={true} className={Classes.DARK} title="Add New Animation" isOpen={this.state.isOpened} > <div className={Classes.DIALOG_BODY}> <Callout title="Animation Name"> <InputGroup placeholder="Animation Name..." small={true} value={this.state.animationName} onChange={(e) => this.setState({ animationName: e.target.value })} /> </Callout> <Divider /> <Callout title="Property Path" intent={Intent.WARNING}> <PropertyPathSuggest fill={true} items={this.state.items} inputValueRenderer={(v) => v} closeOnSelect={false} resetOnSelect={false} popoverProps={{ fill: true, }} inputProps={{ fill: true, }} query={this.state.targetProperty} noResults={<MenuItem disabled={true} text="No results." />} itemRenderer={(i, props) => { if (!props.modifiers.matchesPredicate) { return null; } return ( <MenuItem text={i} key={`${i}_${props.index}`} onClick={props.handleClick} active={props.modifiers.active} disabled={props.modifiers.disabled} /> ); }} onItemSelect={(i) => { const split = this.state.targetProperty.split("."); split.pop(); const value = split.concat(i).join("."); this.setState({ targetProperty: value }); }} onQueryChange={(value) => this._handlePropertyPathQueryChanged(value)} /> </Callout> <Divider /> <Callout title="Animation Type" intent={Intent.WARNING}> <RadioGroup label="Data Type" onChange={(e) => this.setState({ animationType: (e.target as HTMLInputElement).value })} selectedValue={this.state.animationType} > <Radio label="Float" value="ANIMATIONTYPE_FLOAT" /> <Radio label="Vector2" value="ANIMATIONTYPE_VECTOR2" /> <Radio label="Vector3" value="ANIMATIONTYPE_VECTOR3" /> <Radio label="Color3" value="ANIMATIONTYPE_COLOR3" /> <Radio label="Color4" value="ANIMATIONTYPE_COLOR4" /> <Radio label="Quaternion" value="ANIMATIONTYPE_QUATERNION" /> </RadioGroup> </Callout> <Divider /> <Callout title="Options"> <Switch label="Enable Blending" checked={this.state.enableBlending} onChange={(e) => this.setState({ enableBlending: (e.target as HTMLInputElement).checked })} /> <FormGroup label="Frames Per Second"> <NumericInput min={1} fill={true} allowNumericCharactersOnly={true} placeholder="Frames Per Second..." value={this.state.framesPerSecond} onChange={(e) => this.setState({ framesPerSecond: Math.max(parseFloat(e.target.value), 1) })} /> </FormGroup> </Callout> <Divider /> </div> <div className={Classes.DIALOG_FOOTER}> <div className={Classes.DIALOG_FOOTER_ACTIONS}> <Button onClick={() => this.setState({ isOpened: false })}>Cancel</Button> <Button onClick={() => this._handleAddAnimation()}>Add</Button> </div> </div> </Dialog> ); } /** * Shows the dialog using the given animatable. * @param animatable defines the reference to the animatable. */ public showWithAnimatable(animatable: IAnimatable): void { this.setState({ isOpened: true, selectedAnimatable: animatable, }, () => { this.setState({ items: this._getAvailableItems(this.state.targetProperty) }); }); } /** * Called on the query changed for property path. */ private _handlePropertyPathQueryChanged(value: string): void { this.setState({ targetProperty: value, items: this._getAvailableItems(value) }); try { const property = Tools.GetProperty(this.state.selectedAnimatable, value); if (typeof(property) === "number") { this.setState({ animationType: "ANIMATIONTYPE_FLOAT" }); } else if (property instanceof Vector2) { this.setState({ animationType: "ANIMATIONTYPE_VECTOR2" }); } else if (property instanceof Vector3) { this.setState({ animationType: "ANIMATIONTYPE_VECTOR3" }); } else if (property instanceof Color3) { this.setState({ animationType: "ANIMATIONTYPE_COLOR3" }); } else if (property instanceof Color4) { this.setState({ animationType: "ANIMATIONTYPE_COLOR4" }); } else if (property instanceof Quaternion) { this.setState({ animationType: "ANIMATIONTYPE_QUATERNION" }); } } catch (e) { // Catch silently. } } /** * Called on the query changed. */ private _getAvailableItems(value: string): string[] { if (!this.state.selectedAnimatable) { return []; } const split = value.split("."); const finalProperty = split.pop()!; const basePath = split.join("."); const property = split.length ? (Tools.GetProperty<any>(this.state.selectedAnimatable, basePath) ?? null) : this.state.selectedAnimatable; if (property === null) { return []; } const result: string[] = []; const keys: string[] = []; for (const hiddenKey of AddAnimation._HiddenProperties) { const value = property[hiddenKey] ?? null; if (value !== null) { keys.push(hiddenKey); } } for (const key in property) { keys.push(key); } Tools.SortAlphabetically(keys); for (const key of Tools.Distinct(keys)) { if (key[0] === "_") { continue; } if (key.toLowerCase().indexOf(finalProperty.toLowerCase()) === -1) { continue; } const targetValue = property[key]; if (Array.isArray(targetValue)) { continue; } const type = typeof(targetValue); if (type === "function" || type === "boolean" || type === "string") { continue; } result.push(key); } return result; } /** * Called on the user clicks on the button "add". */ private _handleAddAnimation(): void { if (!this.state.selectedAnimatable?.animations) { return; } const targetProperty = Tools.GetProperty<any>(this.state.selectedAnimatable, this.state.targetProperty) ?? null; if (targetProperty === null) { return; } const animation = new Animation( this.state.animationName, this.state.targetProperty, this.state.framesPerSecond, Animation[this.state.animationType], Animation.ANIMATIONLOOPMODE_CONSTANT, this.state.enableBlending, ); switch (animation.dataType) { case Animation.ANIMATIONTYPE_FLOAT: animation.setKeys([ { frame: 0, value: targetProperty }, { frame: 60, value: targetProperty }, ]); break; case Animation.ANIMATIONTYPE_VECTOR2: case Animation.ANIMATIONTYPE_VECTOR3: case Animation.ANIMATIONTYPE_COLOR3: case Animation.ANIMATIONTYPE_COLOR4: case Animation.ANIMATIONTYPE_QUATERNION: animation.setKeys([ { frame: 0, value: targetProperty.clone() }, { frame: 60, value: targetProperty.clone() }, ]); break; } this.state.selectedAnimatable.animations.push(animation); this.props.onAnimationAdded(animation); this.setState({ isOpened: false }); } }
the_stack
import { commands, Disposable, GitTimelineItem, SourceControlResourceGroup, SourceControlResourceState, TextEditor, TextEditorEdit, TimelineItem, Uri, window, } from 'vscode'; import type { ActionContext } from '../api/gitlens'; import { Commands } from '../constants'; import { GitBranch, GitCommit, GitContributor, GitFile, GitReference, GitRemote, GitStashCommit, GitTag, Repository, } from '../git/models'; import { ViewNode, ViewRefNode } from '../views/nodes'; export function getCommandUri(uri?: Uri, editor?: TextEditor): Uri | undefined { // Always use the editor.uri (if we have one), so we are correct for a split diff return editor?.document?.uri ?? uri; } export interface CommandContextParsingOptions { expectsEditor: boolean; } export interface CommandBaseContext { command: string; editor?: TextEditor; uri?: Uri; } export interface CommandGitTimelineItemContext extends CommandBaseContext { readonly type: 'timeline-item:git'; readonly item: GitTimelineItem; readonly uri: Uri; } export interface CommandScmGroupsContext extends CommandBaseContext { readonly type: 'scm-groups'; readonly scmResourceGroups: SourceControlResourceGroup[]; } export interface CommandScmStatesContext extends CommandBaseContext { readonly type: 'scm-states'; readonly scmResourceStates: SourceControlResourceState[]; } export interface CommandUnknownContext extends CommandBaseContext { readonly type: 'unknown'; } export interface CommandUriContext extends CommandBaseContext { readonly type: 'uri'; } export interface CommandUrisContext extends CommandBaseContext { readonly type: 'uris'; readonly uris: Uri[]; } // export interface CommandViewContext extends CommandBaseContext { // readonly type: 'view'; // } export interface CommandViewNodeContext extends CommandBaseContext { readonly type: 'viewItem'; readonly node: ViewNode; } export function isCommandContextGitTimelineItem(context: CommandContext): context is CommandGitTimelineItemContext { return context.type === 'timeline-item:git'; } export function isCommandContextViewNodeHasBranch( context: CommandContext, ): context is CommandViewNodeContext & { node: ViewNode & { branch: GitBranch } } { if (context.type !== 'viewItem') return false; return GitBranch.is((context.node as ViewNode & { branch: GitBranch }).branch); } export function isCommandContextViewNodeHasCommit<T extends GitCommit | GitStashCommit>( context: CommandContext, ): context is CommandViewNodeContext & { node: ViewNode & { commit: T } } { if (context.type !== 'viewItem') return false; return GitCommit.is((context.node as ViewNode & { commit: GitCommit | GitStashCommit }).commit); } export function isCommandContextViewNodeHasContributor( context: CommandContext, ): context is CommandViewNodeContext & { node: ViewNode & { contributor: GitContributor } } { if (context.type !== 'viewItem') return false; return GitContributor.is((context.node as ViewNode & { contributor: GitContributor }).contributor); } export function isCommandContextViewNodeHasFile( context: CommandContext, ): context is CommandViewNodeContext & { node: ViewNode & { file: GitFile; repoPath: string } } { if (context.type !== 'viewItem') return false; const node = context.node as ViewNode & { file: GitFile; repoPath: string }; return node.file != null && (node.file.repoPath != null || node.repoPath != null); } export function isCommandContextViewNodeHasFileCommit( context: CommandContext, ): context is CommandViewNodeContext & { node: ViewNode & { commit: GitCommit; file: GitFile; repoPath: string } } { if (context.type !== 'viewItem') return false; const node = context.node as ViewNode & { commit: GitCommit; file: GitFile; repoPath: string }; return node.file != null && GitCommit.is(node.commit) && (node.file.repoPath != null || node.repoPath != null); } export function isCommandContextViewNodeHasFileRefs(context: CommandContext): context is CommandViewNodeContext & { node: ViewNode & { file: GitFile; ref1: string; ref2: string; repoPath: string }; } { if (context.type !== 'viewItem') return false; const node = context.node as ViewNode & { file: GitFile; ref1: string; ref2: string; repoPath: string }; return ( node.file != null && node.ref1 != null && node.ref2 != null && (node.file.repoPath != null || node.repoPath != null) ); } export function isCommandContextViewNodeHasRef( context: CommandContext, ): context is CommandViewNodeContext & { node: ViewNode & { ref: GitReference } } { return context.type === 'viewItem' && context.node instanceof ViewRefNode; } export function isCommandContextViewNodeHasRemote( context: CommandContext, ): context is CommandViewNodeContext & { node: ViewNode & { remote: GitRemote } } { if (context.type !== 'viewItem') return false; return GitRemote.is((context.node as ViewNode & { remote: GitRemote }).remote); } export function isCommandContextViewNodeHasRepository( context: CommandContext, ): context is CommandViewNodeContext & { node: ViewNode & { repo: Repository } } { if (context.type !== 'viewItem') return false; return (context.node as ViewNode & { repo?: Repository }).repo instanceof Repository; } export function isCommandContextViewNodeHasRepoPath( context: CommandContext, ): context is CommandViewNodeContext & { node: ViewNode & { repoPath: string } } { if (context.type !== 'viewItem') return false; return typeof (context.node as ViewNode & { repoPath?: string }).repoPath === 'string'; } export function isCommandContextViewNodeHasTag( context: CommandContext, ): context is CommandViewNodeContext & { node: ViewNode & { tag: GitTag } } { if (context.type !== 'viewItem') return false; return GitTag.is((context.node as ViewNode & { tag: GitTag }).tag); } export type CommandContext = | CommandGitTimelineItemContext | CommandScmGroupsContext | CommandScmStatesContext | CommandUnknownContext | CommandUriContext | CommandUrisContext // | CommandViewContext | CommandViewNodeContext; function isScmResourceGroup(group: any): group is SourceControlResourceGroup { if (group == null) return false; return ( (group as SourceControlResourceGroup).id != null && (group as SourceControlResourceGroup).label != null && (group as SourceControlResourceGroup).resourceStates != null && Array.isArray((group as SourceControlResourceGroup).resourceStates) ); } function isScmResourceState(resource: any): resource is SourceControlResourceState { if (resource == null) return false; return (resource as SourceControlResourceState).resourceUri != null; } function isTimelineItem(item: any): item is TimelineItem { if (item == null) return false; return (item as TimelineItem).timestamp != null && (item as TimelineItem).label != null; } function isGitTimelineItem(item: any): item is GitTimelineItem { if (item == null) return false; return ( isTimelineItem(item) && (item as GitTimelineItem).ref != null && (item as GitTimelineItem).previousRef != null && (item as GitTimelineItem).message != null ); } export abstract class Command implements Disposable { static getMarkdownCommandArgsCore<T>( command: Commands | `${Commands.ActionPrefix}${ActionContext['type']}`, args: T, ): string { return `command:${command}?${encodeURIComponent(JSON.stringify(args))}`; } protected readonly contextParsingOptions: CommandContextParsingOptions = { expectsEditor: false }; private readonly _disposable: Disposable; constructor(command: Commands | Commands[]) { if (typeof command === 'string') { this._disposable = commands.registerCommand( command, (...args: any[]) => this._execute(command, ...args), this, ); return; } const subscriptions = command.map(cmd => commands.registerCommand(cmd, (...args: any[]) => this._execute(cmd, ...args), this), ); this._disposable = Disposable.from(...subscriptions); } dispose() { this._disposable.dispose(); } protected preExecute(context: CommandContext, ...args: any[]): Promise<any> { return this.execute(...args); } abstract execute(...args: any[]): any; protected _execute(command: string, ...args: any[]): any { const [context, rest] = Command.parseContext(command, { ...this.contextParsingOptions }, ...args); return this.preExecute(context, ...rest); } private static parseContext( command: string, options: CommandContextParsingOptions, ...args: any[] ): [CommandContext, any[]] { let editor: TextEditor | undefined = undefined; let firstArg = args[0]; if (options.expectsEditor) { if (firstArg == null || (firstArg.id != null && firstArg.document?.uri != null)) { editor = firstArg; args = args.slice(1); firstArg = args[0]; } if (args.length > 0 && (firstArg == null || firstArg instanceof Uri)) { const [uri, ...rest] = args as [Uri, any]; if (uri != null) { // If the uri matches the active editor (or we are in a left-hand side of a diff), then pass the active editor if ( editor == null && (uri.toString() === window.activeTextEditor?.document.uri.toString() || command.endsWith('InDiffLeft')) ) { editor = window.activeTextEditor; } const uris = rest[0]; if (uris != null && Array.isArray(uris) && uris.length !== 0 && uris[0] instanceof Uri) { return [ { command: command, type: 'uris', editor: editor, uri: uri, uris: uris }, rest.slice(1), ]; } return [{ command: command, type: 'uri', editor: editor, uri: uri }, rest]; } args = args.slice(1); } else if (editor == null) { // If we are expecting an editor and we have no uri, then pass the active editor editor = window.activeTextEditor; } } if (firstArg instanceof ViewNode) { const [node, ...rest] = args as [ViewNode, any]; return [{ command: command, type: 'viewItem', node: node, uri: node.uri }, rest]; } if (isScmResourceState(firstArg)) { const states = []; let count = 0; for (const arg of args) { if (!isScmResourceState(arg)) break; count++; states.push(arg); } return [ { command: command, type: 'scm-states', scmResourceStates: states, uri: states[0].resourceUri }, args.slice(count), ]; } if (isScmResourceGroup(firstArg)) { const groups = []; let count = 0; for (const arg of args) { if (!isScmResourceGroup(arg)) break; count++; groups.push(arg); } return [{ command: command, type: 'scm-groups', scmResourceGroups: groups }, args.slice(count)]; } if (isGitTimelineItem(firstArg)) { const [item, uri, ...rest] = args as [GitTimelineItem, Uri, any]; return [{ command: command, type: 'timeline-item:git', item: item, uri: uri }, rest]; } return [{ command: command, type: 'unknown', editor: editor, uri: editor?.document.uri }, args]; } } export abstract class ActiveEditorCommand extends Command { protected override readonly contextParsingOptions: CommandContextParsingOptions = { expectsEditor: true }; constructor(command: Commands | Commands[]) { super(command); } protected override preExecute(context: CommandContext, ...args: any[]): Promise<any> { return this.execute(context.editor, context.uri, ...args); } protected override _execute(command: string, ...args: any[]): any { return super._execute(command, undefined, ...args); } abstract override execute(editor?: TextEditor, ...args: any[]): any; } let lastCommand: { command: string; args: any[] } | undefined = undefined; export function getLastCommand() { return lastCommand; } export abstract class ActiveEditorCachedCommand extends ActiveEditorCommand { constructor(command: Commands | Commands[]) { super(command); } protected override _execute(command: string, ...args: any[]): any { lastCommand = { command: command, args: args, }; return super._execute(command, ...args); } abstract override execute(editor: TextEditor, ...args: any[]): any; } export abstract class EditorCommand implements Disposable { private readonly _disposable: Disposable; constructor(command: Commands | Commands[]) { if (!Array.isArray(command)) { command = [command]; } const subscriptions = []; for (const cmd of command) { subscriptions.push( commands.registerTextEditorCommand( cmd, (editor: TextEditor, edit: TextEditorEdit, ...args: any[]) => this.executeCore(cmd, editor, edit, ...args), this, ), ); } this._disposable = Disposable.from(...subscriptions); } dispose() { this._disposable.dispose(); } private executeCore(command: string, editor: TextEditor, edit: TextEditorEdit, ...args: any[]): any { return this.execute(editor, edit, ...args); } abstract execute(editor: TextEditor, edit: TextEditorEdit, ...args: any[]): any; }
the_stack
import { AuthModeStrategy, InternalSchema, LimitTimerRaceResolvedValues, SchemaModel, SchemaNamespace, } from '../src/types'; import { generateSelectionSet, getModelAuthModes } from '../src/sync/utils'; import { GRAPHQL_AUTH_MODE } from '@aws-amplify/api-graphql'; import { DeferredCallbackResolver } from '../src/util'; describe('DataStore - utils', () => { describe('generateSelectionSet', () => { test('implicit owner', () => { const namespace: SchemaNamespace = { name: 'user', models: { Post: { name: 'Post', fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, attributes: [], }, title: { name: 'title', isArray: false, type: 'String', isRequired: true, attributes: [], }, }, syncable: true, pluralName: 'Posts', attributes: [ { type: 'model', properties: {}, }, { type: 'auth', properties: { rules: [ { provider: 'userPools', ownerField: 'owner', allow: 'owner', identityClaim: 'cognito:username', operations: ['create', 'update', 'delete', 'read'], }, ], }, }, ], }, }, enums: {}, nonModels: {}, relationships: { Post: { indexes: [], relationTypes: [], }, }, }; const modelDefinition: SchemaModel = { name: 'Post', fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, attributes: [], }, title: { name: 'title', isArray: false, type: 'String', isRequired: true, attributes: [], }, }, syncable: true, pluralName: 'Posts', attributes: [ { type: 'model', properties: {}, }, { type: 'auth', properties: { rules: [ { provider: 'userPools', ownerField: 'owner', allow: 'owner', identityClaim: 'cognito:username', operations: ['create', 'update', 'delete', 'read'], }, ], }, }, ], }; const selectionSet = `id title owner _version _lastChangedAt _deleted`; expect(generateSelectionSet(namespace, modelDefinition)).toEqual( selectionSet ); }); test('explicit owner', () => { const namespace: SchemaNamespace = { name: 'user', models: { Post: { name: 'Post', fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, attributes: [], }, title: { name: 'title', isArray: false, type: 'String', isRequired: true, attributes: [], }, owner: { name: 'owner', isArray: false, type: 'String', isRequired: false, attributes: [], }, }, syncable: true, pluralName: 'Posts', attributes: [ { type: 'model', properties: {}, }, { type: 'auth', properties: { rules: [ { provider: 'userPools', ownerField: 'owner', allow: 'owner', identityClaim: 'cognito:username', operations: ['create', 'update', 'delete', 'read'], }, ], }, }, ], }, }, enums: {}, nonModels: {}, relationships: { Post: { indexes: [], relationTypes: [], }, }, }; const modelDefinition: SchemaModel = { name: 'Post', fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, attributes: [], }, title: { name: 'title', isArray: false, type: 'String', isRequired: true, attributes: [], }, owner: { name: 'owner', isArray: false, type: 'String', isRequired: false, attributes: [], }, }, syncable: true, pluralName: 'Posts', attributes: [ { type: 'model', properties: {}, }, { type: 'auth', properties: { rules: [ { provider: 'userPools', ownerField: 'owner', allow: 'owner', identityClaim: 'cognito:username', operations: ['create', 'update', 'delete', 'read'], }, ], }, }, ], }; const selectionSet = `id title owner _version _lastChangedAt _deleted`; expect(generateSelectionSet(namespace, modelDefinition)).toEqual( selectionSet ); }); test('explicit custom owner', () => { const namespace: SchemaNamespace = { name: 'user', models: { Post: { name: 'Post', fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, attributes: [], }, title: { name: 'title', isArray: false, type: 'String', isRequired: true, attributes: [], }, customOwner: { name: 'customOwner', isArray: false, type: 'String', isRequired: false, attributes: [], }, }, syncable: true, pluralName: 'Posts', attributes: [ { type: 'model', properties: {}, }, { type: 'auth', properties: { rules: [ { provider: 'userPools', ownerField: 'customOwner', allow: 'owner', identityClaim: 'cognito:username', operations: ['create', 'update', 'delete', 'read'], }, ], }, }, ], }, }, enums: {}, nonModels: {}, relationships: { Post: { indexes: [], relationTypes: [], }, }, }; const modelDefinition: SchemaModel = { name: 'Post', fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, attributes: [], }, title: { name: 'title', isArray: false, type: 'String', isRequired: true, attributes: [], }, customOwner: { name: 'customOwner', isArray: false, type: 'String', isRequired: false, attributes: [], }, }, syncable: true, pluralName: 'Posts', attributes: [ { type: 'model', properties: {}, }, { type: 'auth', properties: { rules: [ { provider: 'userPools', ownerField: 'customOwner', allow: 'owner', identityClaim: 'cognito:username', operations: ['create', 'update', 'delete', 'read'], }, ], }, }, ], }; const selectionSet = `id title customOwner _version _lastChangedAt _deleted`; expect(generateSelectionSet(namespace, modelDefinition)).toEqual( selectionSet ); }); }); describe('getModel', () => { test('handles an array of auth modes', async () => { const authModeStrategy: AuthModeStrategy = () => [ GRAPHQL_AUTH_MODE.AMAZON_COGNITO_USER_POOLS, ]; const authModes = await getModelAuthModes({ authModeStrategy, defaultAuthMode: GRAPHQL_AUTH_MODE.AMAZON_COGNITO_USER_POOLS, modelName: 'Post', schema: {} as InternalSchema, // schema is only passed directly to the authModeStrategy }); const expectedAuthModes = { CREATE: ['AMAZON_COGNITO_USER_POOLS'], READ: ['AMAZON_COGNITO_USER_POOLS'], UPDATE: ['AMAZON_COGNITO_USER_POOLS'], DELETE: ['AMAZON_COGNITO_USER_POOLS'], }; expect(authModes).toEqual(expectedAuthModes); }); test('handles a string auth mode', async () => { const authModeStrategy: AuthModeStrategy = () => GRAPHQL_AUTH_MODE.AMAZON_COGNITO_USER_POOLS; const authModes = await getModelAuthModes({ authModeStrategy, defaultAuthMode: GRAPHQL_AUTH_MODE.AMAZON_COGNITO_USER_POOLS, modelName: 'Post', schema: {} as InternalSchema, }); const expectedAuthModes = { CREATE: ['AMAZON_COGNITO_USER_POOLS'], READ: ['AMAZON_COGNITO_USER_POOLS'], UPDATE: ['AMAZON_COGNITO_USER_POOLS'], DELETE: ['AMAZON_COGNITO_USER_POOLS'], }; expect(authModes).toEqual(expectedAuthModes); }); test('falls back to default auth mode', async () => { const expectedAuthModes = { CREATE: ['AMAZON_COGNITO_USER_POOLS'], READ: ['AMAZON_COGNITO_USER_POOLS'], UPDATE: ['AMAZON_COGNITO_USER_POOLS'], DELETE: ['AMAZON_COGNITO_USER_POOLS'], }; // using blocks in order to be able to re-use the same const-declared variables below { const authModeStrategy: AuthModeStrategy = () => null; const authModes = await getModelAuthModes({ authModeStrategy, defaultAuthMode: GRAPHQL_AUTH_MODE.AMAZON_COGNITO_USER_POOLS, modelName: 'Post', schema: {} as InternalSchema, }); expect(authModes).toEqual(expectedAuthModes); } { const authModeStrategy: AuthModeStrategy = () => undefined; const authModes = await getModelAuthModes({ authModeStrategy, defaultAuthMode: GRAPHQL_AUTH_MODE.AMAZON_COGNITO_USER_POOLS, modelName: 'Post', schema: {} as InternalSchema, }); expect(authModes).toEqual(expectedAuthModes); } { const authModeStrategy: AuthModeStrategy = () => []; const authModes = await getModelAuthModes({ authModeStrategy, defaultAuthMode: GRAPHQL_AUTH_MODE.AMAZON_COGNITO_USER_POOLS, modelName: 'Post', schema: {} as InternalSchema, }); expect(authModes).toEqual(expectedAuthModes); } }); }); describe('DeferredCallbackResolver utility class', () => { beforeEach(() => { jest.clearAllMocks(); }); test('happy path - limit wins', async () => { expect.assertions(5); const limitTimerRaceCallback = jest.fn(); // casting to any -> in order to access private members const limitTimerRace: any = new DeferredCallbackResolver({ maxInterval: 500, callback: limitTimerRaceCallback, }); const spyOnRace = jest.spyOn(limitTimerRace, 'racePromises'); expect(limitTimerRace.raceInFlight).toBe(false); limitTimerRace.start(); expect(spyOnRace).toBeCalledTimes(1); limitTimerRace.resolve(); const winner = await spyOnRace.mock.results[0].value; expect(winner).toEqual(LimitTimerRaceResolvedValues.LIMIT); expect(limitTimerRace.raceInFlight).toBe(false); expect(limitTimerRaceCallback).toBeCalledTimes(1); limitTimerRace.clear(); }); test('happy path - timer wins', async () => { expect.assertions(5); const limitTimerRaceCallback = jest.fn(); // casting to any -> in order to access private members const limitTimerRace: any = new DeferredCallbackResolver({ maxInterval: 500, callback: limitTimerRaceCallback, }); const spyOnRace = jest.spyOn(limitTimerRace, 'racePromises'); expect(limitTimerRace.raceInFlight).toBe(false); limitTimerRace.start(); expect(spyOnRace).toBeCalledTimes(1); const winner = await spyOnRace.mock.results[0].value; expect(winner).toEqual(LimitTimerRaceResolvedValues.TIMER); expect(limitTimerRace.raceInFlight).toBe(false); expect(limitTimerRaceCallback).toBeCalledTimes(1); limitTimerRace.clear(); }); test('throws default error', async () => { expect.assertions(4); const limitTimerRaceCallback = jest.fn(); // casting to any -> in order to access private members const limitTimerRace: any = new DeferredCallbackResolver({ maxInterval: 500, callback: limitTimerRaceCallback, }); const spyOnRace = jest.spyOn(limitTimerRace, 'racePromises'); const spyOnErrorHandler = jest.spyOn(limitTimerRace, 'errorHandler'); const spyOnTimer = jest.spyOn(limitTimerRace, 'startTimer'); // force the Promise to reject spyOnTimer.mockImplementation(() => { throw new Error('customErrorMsg'); }); expect(limitTimerRace.raceInFlight).toBe(false); limitTimerRace.start(); expect(spyOnRace).toBeCalledTimes(1); expect(spyOnErrorHandler).toThrowError('DeferredCallbackResolver error'); expect(limitTimerRaceCallback).toBeCalledTimes(0); limitTimerRace.clear(); }); test('accepts custom error handler and throws custom error', async () => { expect.assertions(4); const limitTimerRaceCallback = jest.fn(); const customErrorMsg = 'something went wrong with the DeferredCallbackResolver'; const limitTimerRaceErrorHandler = jest.fn(err => { throw new Error(customErrorMsg); }); // casting to any -> in order to access private members const limitTimerRace: any = new DeferredCallbackResolver({ maxInterval: 500, callback: limitTimerRaceCallback, errorHandler: limitTimerRaceErrorHandler, }); const spyOnRace = jest.spyOn(limitTimerRace, 'racePromises'); const spyOnErrorHandler = jest.spyOn(limitTimerRace, 'errorHandler'); const spyOnTimer = jest.spyOn(limitTimerRace, 'startTimer'); // force the 'racePromises' to fail spyOnTimer.mockImplementation(() => { throw new Error('timer error'); }); expect(limitTimerRace.raceInFlight).toBe(false); limitTimerRace.start(); expect(spyOnRace).toBeCalledTimes(1); expect(spyOnErrorHandler).toThrowError(customErrorMsg); expect(limitTimerRaceCallback).toBeCalledTimes(0); limitTimerRace.clear(); }); }); });
the_stack
import React from "react"; import { render, screen } from "@testing-library/react"; import { Box } from "."; describe("Box", () => { it("renders visibly", () => { render(<Box>box</Box>); expect(screen.getByText("box")).toBeVisible(); }); it("renders as element", () => { render(<Box as="span">box</Box>); expect(screen.getByText("box").tagName.toLowerCase() === "span").toBe(true); }); it("allows a custom class", () => { render(<Box className="testClass">box</Box>); expect(screen.getByText("box")).toHaveClass("testClass"); }); it("uses the display property to attach a class", () => { render(<Box display="inline">box</Box>); expect(screen.getByText("box")).toHaveClass("displayInline"); }); it("uses the position property to attach a class", () => { render(<Box position="absolute">box</Box>); expect(screen.getByText("box")).toHaveClass("positionAbsolute"); }); it("uses the flexDirection property to attach a class", () => { render(<Box flexDirection="column">box</Box>); expect(screen.getByText("box")).toHaveClass("flexDirectionColumn"); }); it("uses the flexWrap property to attach a class", () => { render(<Box flexWrap="nowrap">box</Box>); expect(screen.getByText("box")).toHaveClass("flexWrapNowrap"); }); it("uses the flex property to attach a class", () => { render(<Box flex="auto">box</Box>); expect(screen.getByText("box")).toHaveClass("flexAuto"); }); it("uses the flexGrow property to attach a class", () => { render(<Box flexGrow="1">box</Box>); expect(screen.getByText("box")).toHaveClass("flexGrow1"); }); it("uses the flexShrink property to attach a class", () => { render(<Box flexShrink="1">box</Box>); expect(screen.getByText("box")).toHaveClass("flexShrink1"); }); it("uses the alignItems property to attach a class", () => { render(<Box alignItems="flex-start">box</Box>); expect(screen.getByText("box")).toHaveClass("alignItemsFlexStart"); }); it("uses the justifyContent property to attach a class", () => { render(<Box justifyContent="flex-start">box</Box>); expect(screen.getByText("box")).toHaveClass("justifyContentFlexStart"); }); it("uses the width property to attach a class", () => { render(<Box width="1px">box</Box>); expect(screen.getByText("box")).toHaveClass("width1px"); }); it("uses the maxWidth property to attach a class", () => { render(<Box maxWidth="full">box</Box>); expect(screen.getByText("box")).toHaveClass("maxWidthFull"); }); it("uses the height property to attach a class", () => { render(<Box height="1em">box</Box>); expect(screen.getByText("box")).toHaveClass("height1em"); }); it("uses the maxHeight property to attach a class", () => { render(<Box maxHeight="screen">box</Box>); expect(screen.getByText("box")).toHaveClass("maxHeightScreen"); }); it("uses the margin property to attach a class", () => { render(<Box margin="s">box</Box>); expect(screen.getByText("box")).toHaveClass("marginS"); }); it("uses a margin property 2 element array to attach multiple classes", () => { render(<Box margin={["s", "m"]}>box</Box>); expect(screen.getByText("box")).toHaveClass( "marginTopS", "marginBottomS", "marginLeftM", "marginRightM" ); }); it("uses a margin property 3 element array to attach multiple classes", () => { render(<Box margin={["s", "m", "l"]}>box</Box>); expect(screen.getByText("box")).toHaveClass( "marginTopS", "marginRightM", "marginLeftM", "marginBottomL" ); }); it("uses a margin property 4 element array to attach multiple classes", () => { render(<Box margin={["s", "m", "l", "xl"]}>box</Box>); expect(screen.getByText("box")).toHaveClass( "marginTopS", "marginRightM", "marginBottomL", "marginLeftXl" ); }); it("uses the marginTop property to attach a class", () => { render(<Box marginTop="s">box</Box>); expect(screen.getByText("box")).toHaveClass("marginTopS"); }); it("uses the marginRight property to attach a class", () => { render(<Box marginRight="s">box</Box>); expect(screen.getByText("box")).toHaveClass("marginRightS"); }); it("uses the marginBottom property to attach a class", () => { render(<Box marginBottom="s">box</Box>); expect(screen.getByText("box")).toHaveClass("marginBottomS"); }); it("uses the marginLeft property to attach a class", () => { render(<Box marginLeft="s">box</Box>); expect(screen.getByText("box")).toHaveClass("marginLeftS"); }); it("uses the padding property to attach a class", () => { render(<Box padding="s">box</Box>); expect(screen.getByText("box")).toHaveClass("paddingS"); }); it("uses a padding property 2 element array to attach multiple classes", () => { render(<Box padding={["s", "m"]}>box</Box>); expect(screen.getByText("box")).toHaveClass( "paddingTopS", "paddingBottomS", "paddingLeftM", "paddingRightM" ); }); it("uses a padding property 3 element array to attach multiple classes", () => { render(<Box padding={["s", "m", "l"]}>box</Box>); expect(screen.getByText("box")).toHaveClass( "paddingTopS", "paddingRightM", "paddingLeftM", "paddingBottomL" ); }); it("uses a padding property 4 element array to attach multiple classes", () => { render(<Box padding={["s", "m", "l", "xl"]}>box</Box>); expect(screen.getByText("box")).toHaveClass( "paddingTopS", "paddingRightM", "paddingBottomL", "paddingLeftXl" ); }); it("uses the paddingTop property to attach a class", () => { render(<Box paddingTop="s">box</Box>); expect(screen.getByText("box")).toHaveClass("paddingTopS"); }); it("uses the paddingRight property to attach a class", () => { render(<Box paddingRight="s">box</Box>); expect(screen.getByText("box")).toHaveClass("paddingRightS"); }); it("uses the paddingBottom property to attach a class", () => { render(<Box paddingBottom="s">box</Box>); expect(screen.getByText("box")).toHaveClass("paddingBottomS"); }); it("uses the paddingLeft property to attach a class", () => { render(<Box paddingLeft="s">box</Box>); expect(screen.getByText("box")).toHaveClass("paddingLeftS"); }); it("uses the overflow property to attach a class", () => { render(<Box overflow="scroll">box</Box>); expect(screen.getByText("box")).toHaveClass("overflowScroll"); }); it("uses a overflow property 2 element array to attach multiple classes", () => { render(<Box overflow={["scroll", "hidden"]}>box</Box>); expect(screen.getByText("box")).toHaveClass( "overflowXScroll", "overflowYHidden" ); }); it("uses the overflowX property to attach a class", () => { render(<Box overflowX="scroll">box</Box>); expect(screen.getByText("box")).toHaveClass("overflowXScroll"); }); it("uses the overflowY property to attach a class", () => { render(<Box overflowY="scroll">box</Box>); expect(screen.getByText("box")).toHaveClass("overflowYScroll"); }); it("uses the borderColor property to attach a class", () => { render(<Box borderColor="display">box</Box>); expect(screen.getByText("box")).toHaveClass("borderColorDisplay"); }); it("uses the hoverBorderColor property to attach a class", () => { render(<Box hoverBorderColor="primary">box</Box>); expect(screen.getByText("box")).toHaveClass("hoverBorderColorPrimary"); }); it("uses the borderRadius property to attach a class", () => { render(<Box borderRadius="base">box</Box>); expect(screen.getByText("box")).toHaveClass("borderRadiusBase"); }); it("uses a borderRadius property 2 element array to attach multiple classes", () => { render(<Box borderRadius={["base", "outer"]}>box</Box>); expect(screen.getByText("box")).toHaveClass( "borderTopLeftRadiusBase", "borderBottomRightRadiusBase", "borderTopRightRadiusOuter", "borderBottomLeftRadiusOuter" ); }); it("uses a borderRadius property 3 element array to attach multiple classes", () => { render(<Box borderRadius={["base", "outer", "base"]}>box</Box>); expect(screen.getByText("box")).toHaveClass( "borderTopLeftRadiusBase", "borderTopRightRadiusOuter", "borderBottomLeftRadiusOuter", "borderBottomRightRadiusBase" ); }); it("uses a borderRadius property 4 element array to attach multiple classes", () => { render(<Box borderRadius={["base", "outer", "base", "outer"]}>box</Box>); expect(screen.getByText("box")).toHaveClass( "borderTopLeftRadiusBase", "borderTopRightRadiusOuter", "borderBottomRightRadiusBase", "borderBottomLeftRadiusOuter" ); }); it("uses the borderTopLeftRadius property to attach a class", () => { render(<Box borderTopLeftRadius="base">box</Box>); expect(screen.getByText("box")).toHaveClass("borderTopLeftRadiusBase"); }); it("uses the borderTopRightRadius property to attach a class", () => { render(<Box borderTopRightRadius="base">box</Box>); expect(screen.getByText("box")).toHaveClass("borderTopRightRadiusBase"); }); it("uses the borderBottomLeftRadius property to attach a class", () => { render(<Box borderBottomLeftRadius="base">box</Box>); expect(screen.getByText("box")).toHaveClass("borderBottomLeftRadiusBase"); }); it("uses the borderBottomRightRadius property to attach a class", () => { render(<Box borderBottomRightRadius="base">box</Box>); expect(screen.getByText("box")).toHaveClass("borderBottomRightRadiusBase"); }); it("uses the backgroundColor property to attach a class", () => { render(<Box backgroundColor="default">box</Box>); expect(screen.getByText("box")).toHaveClass("backgroundColorDefault"); }); it("uses the boxShadow property to attach a class", () => { render(<Box boxShadow="default">box</Box>); expect(screen.getByText("box")).toHaveClass("boxShadowDefault"); }); it("uses the hoverBoxShadow property to attach a class", () => { render(<Box hoverBoxShadow="default">box</Box>); expect(screen.getByText("box")).toHaveClass("hoverBoxShadowDefault"); }); it("uses the focusRing property to attach a class", () => { render(<Box focusRing="primary">box</Box>); expect(screen.getByText("box")).toHaveClass("focusRingPrimary"); }); it("uses the cursor property to attach a class", () => { render(<Box cursor="pointer">box</Box>); expect(screen.getByText("box")).toHaveClass("cursorPointer"); }); it("uses the pointerEvents property to attach a class", () => { render(<Box pointerEvents="none">box</Box>); expect(screen.getByText("box")).toHaveClass("pointerEventsNone"); }); it("uses the userSelect property to attach a class", () => { render(<Box userSelect="none">box</Box>); expect(screen.getByText("box")).toHaveClass("userSelectNone"); }); a11yCheck(() => render(<Box />)); });
the_stack
import { fabric } from 'fabric'; import { IEvent } from 'fabric/fabric-impl'; import jsonPatch from 'fast-json-patch'; import _ from 'lodash'; import { applyObjectConfig, deleteObject, getDeleteAtVersion, getId, isLiveObj, objectToJson, setDeleteAtVersion, } from './fabric-utils'; import LiveUpdateControl, { getUpdateControl } from './live-update-handler'; import PathCache from './path-cache'; import { CanvasLiveAction, CanvasObjectPatch, CanvasPushAction, VersionedCanvasObject, WhiteboardCanvas, WhiteboardLiveUpdateDto, } from './types'; import WhiteboardTool, { WhiteboardToolOptions } from './whiteboard-tool'; export type LiveUpdateHandler = { submit: (action: CanvasLiveAction) => void; on: (handler: (update: WhiteboardLiveUpdateDto) => void) => void; }; export default class WhiteboardController { private fc: fabric.Canvas; private tool: WhiteboardTool; private options: WhiteboardToolOptions; private unsubscribeTool: (() => void) | undefined; private currentVersion: number | undefined; private currentCanvas: WhiteboardCanvas | undefined; private currentDeletionId: string | undefined; private appliedLiveUpdates = new Map< string, { type: CanvasLiveAction['type']; updateControl: LiveUpdateControl<CanvasLiveAction> } >(); private throttledLiveUpdate: _.DebouncedFunc<(update: CanvasLiveAction) => void> | undefined; private pathCache = new PathCache(); constructor(canvas: HTMLCanvasElement, initialTool: WhiteboardTool, initialOptions: WhiteboardToolOptions) { this.fc = new fabric.Canvas(canvas); this.options = initialOptions; this.tool = initialTool; this.setTool(initialTool); this.fc.on('object:modified', this.onObjectModified.bind(this)); this.fc.on('object:removed', this.onObjectRemoved.bind(this)); this.fc.on('object:moving', this.onObjectModifying.bind(this)); this.fc.on('object:scaling', this.onObjectModifying.bind(this)); this.fc.on('object:rotating', this.onObjectModifying.bind(this)); this.fc.on('object:skewing', this.onObjectModifying.bind(this)); this.fc.on('mouse:down', this.onMouseDown.bind(this)); this.fc.on('mouse:move', this.onMouseMove.bind(this)); this.fc.on('mouse:up', this.onMouseUp.bind(this)); this.fc.on('mouse:out', this.onMouseOut.bind(this)); this.fc.setWidth(1280); this.fc.setHeight(720); } public pushAction: ((action: CanvasPushAction) => Promise<number>) | undefined; public setupLiveUpdateHandler(handler: LiveUpdateHandler): void { handler.on(this.onLiveUpdateReceived.bind(this)); this.throttledLiveUpdate = _.throttle((update) => { handler.submit(update); }, 1000 / 15); } public updateCanvas(canvas: WhiteboardCanvas) { canvas = this.pathCache.preprocess(canvas); // paths must be unpacked from point array to svg paths const newVersion = _.maxBy(canvas.objects, (x) => x.version)?.version ?? 0; if (!this.currentVersion) { this.fc.loadFromJSON( { objects: canvas.objects.map(({ id, data, version }) => ({ ...data, id, version })), background: canvas.backgroundColor, }, () => { this.fc.absolutePan(new fabric.Point(canvas.panX, canvas.panY)); this.fc.requestRenderAll(); }, ); } else { const appliedVersion = this.currentVersion; const updatedObjects = canvas.objects.filter((x) => x.version > appliedVersion); const existingObjects = Object.fromEntries( this.fc .getObjects() .map((x) => [getId(x) as string, x]) .filter((x) => x[0]), ); const newObjects = new Array<VersionedCanvasObject>(); for (const obj of updatedObjects) { const existing = existingObjects[obj.id]; if (existing) { applyObjectConfig(existing, obj.data); } else { newObjects.push(obj); } } const checkObjDeleted = (obj: fabric.Object) => { const objId = getId(obj); if (objId && !canvas.objects.find((y) => objId === y.id)) { return true; } const deleteAt = getDeleteAtVersion(obj); if (deleteAt !== undefined && newVersion >= deleteAt) { return true; } return false; }; const deletedObjects = this.fc.getObjects().filter(checkObjDeleted); this.fc.remove(...deletedObjects); fabric.util.enlivenObjects( newObjects.map(({ id, data, version }) => ({ ...data, id, version })), (enlivenedObjects: any[]) => { if (enlivenedObjects.length > 0) { this.fc.add(...enlivenedObjects); this.tool.configureNewObjects(enlivenedObjects); } this.fc.requestRenderAll(); }, '', ); this.fc.absolutePan(new fabric.Point(canvas.panX, canvas.panY)); } this.currentVersion = newVersion; this.currentCanvas = canvas; (this.fc as any).currentPan = { x: canvas.panX, y: canvas.panY }; } /** object:modified at the end of a transform or any change when statefull is true */ private onObjectModified(e: IEvent) { if (!e.target) return; if (e.target.type === 'activeSelection') { const selection = e.target as fabric.ActiveSelection; //Discard group to get position relative to canvas and not group selection this.fc.discardActiveObject(); this.onUpdateObjects(selection.getObjects()); } else { this.onUpdateObjects([e.target]); } } private onUpdateObjects(objects: fabric.Object[]): void { const patches = this.generatePatch(objects); if (patches.length === 0) return; this.pushActionAndResetOnError({ type: 'update', patches }); } private onLiveUpdateObjects(objects: fabric.Object[]): void { const patches = this.generatePatch(objects); if (patches.length === 0) return; this.throttledLiveUpdate?.({ type: 'modifying', patches }); } private generatePatch(objects: fabric.Object[]): CanvasObjectPatch[] { if (!this.currentCanvas) return []; const patches = new Array<CanvasObjectPatch>(); for (const updatedObj of objects) { const original = this.currentCanvas.objects.find((x) => x.id === getId(updatedObj)); if (!original) continue; const modified = objectToJson(updatedObj); const patch = jsonPatch.compare(original.data, modified); patches.push({ objectId: original.id, patch }); } return patches; } private onObjectRemoved(e: IEvent) { if (!e.target) return; const deletionId = (e.target as any).deletionId; if (deletionId) { if (this.currentDeletionId === deletionId) return; this.currentDeletionId = deletionId; const objectIds = (e.target as any).deletedWith.filter((x: any) => !isLiveObj(x)).map((x: any) => getId(x)); this.pushActionAndResetOnError({ type: 'delete', objectIds: objectIds }); } else { const targetId = getId(e.target); if (targetId) { this.pushActionAndResetOnError({ type: 'delete', objectIds: [targetId] }); } } } private onObjectModifying(e: IEvent) { if (!e.target) return; if (e.target.type === 'activeSelection') return; this.onLiveUpdateObjects([e.target as any]); } private onMouseDown(e: IEvent) { this.tool.onMouseDown(e); } private onMouseMove(e: IEvent) { this.tool.onMouseMove(e); } private onMouseOut(e: IEvent) { this.tool.onMouseOut(e); } private onMouseUp(e: IEvent) { this.tool.onMouseUp(e); } private onLiveUpdateReceived(update: WhiteboardLiveUpdateDto) { if (!this.currentCanvas) return; if (update.action.type === 'end') { this.removeLiveUpdate(update.participantId); return; } const existingHandler = this.appliedLiveUpdates.get(update.participantId); if (existingHandler) { if (update.action.type !== existingHandler.type) { this.removeLiveUpdate(update.participantId); } else { existingHandler.updateControl.apply(this.fc, update.action, this.currentCanvas); this.fc.requestRenderAll(); return; } } const updateControl = getUpdateControl(update.action.type); updateControl.apply(this.fc, update.action, this.currentCanvas); this.appliedLiveUpdates.set(update.participantId, { updateControl, type: update.action.type }); this.fc.requestRenderAll(); } public updateParticipants(participantIds: string[]) { for (const appliedParticipantId of this.appliedLiveUpdates.keys()) { if (!participantIds.includes(appliedParticipantId)) { this.removeLiveUpdate(appliedParticipantId); } } } private removeLiveUpdate(participantId: string) { if (!this.currentCanvas) return; const update = this.appliedLiveUpdates.get(participantId); if (!update) return; update.updateControl.delete(this.fc, this.currentCanvas); this.appliedLiveUpdates.delete(participantId); } public setTool(tool: WhiteboardTool) { this.unsubscribeTool?.(); this.tool = tool; const onToolUpdateHandler = this.onToolUpdate.bind(this); const onToolUpdatingHandler = this.onToolUpdating.bind(this); const onToolAddObjectHandler = this.onToolAddObject.bind(this); tool.on('update', onToolUpdateHandler); tool.on('updating', onToolUpdatingHandler); tool.on('addObj', onToolAddObjectHandler); this.unsubscribeTool = () => { tool.dispose(); tool.off('update', onToolUpdateHandler); tool.off('updating', onToolUpdatingHandler); tool.off('addObj', onToolAddObjectHandler); }; tool.configureCanvas(this.fc); tool.applyOptions(this.options); this.fc.discardActiveObject(); this.fc.requestRenderAll(); } private onToolUpdate(update: CanvasPushAction): void { this.pushActionAndResetOnError(update); } private onToolUpdating(update: CanvasLiveAction): void { this.throttledLiveUpdate?.(update); } private async onToolAddObject(update: CanvasPushAction, obj: fabric.Object) { if (!this.pushAction) return; let version: number; try { version = await this.pushAction(update); } catch (error) { this.fc.remove(obj); return; } if (this.currentVersion !== undefined && this.currentVersion >= version) { this.fc.remove(obj); return; } setDeleteAtVersion(obj, version); } public updateOptions(options: WhiteboardToolOptions) { this.options = options; this.tool.applyOptions(options); } get selectedTool(): WhiteboardTool { return this.tool; } public clearWhiteboard() { this.fc.discardActiveObject(); this.pushActionAndResetOnError({ type: 'delete', objectIds: this.fc .getObjects() .map((x) => getId(x)) .filter((x): x is string => !!x), }); } public deleteSelection() { const selected = this.fc.getActiveObject(); deleteObject(this.fc, selected); } private pushActionAndResetOnError(action: CanvasPushAction) { try { this.pushAction?.(action).catch(() => { this.resetCanvas(); }); } catch (error) { this.resetCanvas(); } } private resetCanvas() { if (!this.currentCanvas) return; this.currentVersion = undefined; this.updateCanvas(this.currentCanvas); } }
the_stack
import { assert } from "chai"; import { spy, useFakeTimers } from "sinon"; import { go, map, mapTo } from "@funkia/jabz"; import { at, Behavior, isBehavior, observe, producerBehavior, push, sinkBehavior, moment, format, switchTo, fromFunction, sinkFuture, freezeTo, Stream, time, runNow, Time } from "../src"; import * as H from "../src"; import { subscribeSpy } from "./helpers"; import { placeholder } from "../src/placeholder"; function double(n: number): number { return n * 2; } function sum(n: number, m: number): number { return n + m; } const add = (a: number) => (b: number): number => a + b; describe("behavior", () => { describe("isBehavior", () => { it("should be true when Behavior object", () => { assert.isTrue(isBehavior(Behavior.of(2))); }); it("should be false when not Behavior object", () => { assert.isFalse(isBehavior([])); assert.isFalse(isBehavior({})); assert.isFalse(isBehavior(undefined)); assert.isFalse(isBehavior("test")); assert.isFalse(isBehavior([Behavior.of(42)])); assert.isFalse(isBehavior(1234)); assert.isFalse(isBehavior(H.isBehavior)); // A stream is not a behavior assert.isFalse(isBehavior(H.sinkStream())); assert.isFalse(Behavior.is(1)); }); }); describe("producer", () => { it("activates and deactivates", () => { const activate = spy(); const deactivate = spy(); class MyProducer extends H.ProducerBehavior<undefined> { update(): undefined { return undefined; } activateProducer(): void { activate(); } deactivateProducer(): void { deactivate(); } } const producer = new MyProducer(); const observer = producer.subscribe((a) => a); observer.deactivate(); assert(activate.calledOnce); assert(deactivate.calledOnce); }); }); describe("producerBehavior", () => { it("activates and deactivates", () => { const activate = spy(); const deactivate = spy(); const producer = producerBehavior( (_push) => { activate(); return deactivate; }, () => "" ); const observer = producer.subscribe((a) => a); observer.deactivate(); assert(activate.calledOnce); assert(deactivate.calledOnce); }); it("can push and pull", () => { let variable = 0; let push: (t: Time) => void; const setVar = (n: number) => { variable = n; if (push !== undefined) { push(n); } }; const producer = producerBehavior( (push_) => { push = push_; return () => (push = undefined); }, () => variable ); assert.strictEqual(H.at(producer), 0); variable = 1; assert.strictEqual(H.at(producer), 1); const spy = subscribeSpy(producer); setVar(2); assert.strictEqual(H.at(producer), 2); setVar(3); assert.deepEqual(spy.args, [[1], [2], [3]]); }); }); describe("observe", () => { it("samples in same timestamp", () => { const f = jest.fn(() => 0); const b = fromFunction(f); const result = -1; b.observe( (_) => result, (pull) => { pull(); return () => {}; }, 3 ); expect(f.mock.calls).toEqual([[3]]); }); }); describe("fromFunction", () => { it("pulls from time varying functions", () => { let time = 0; const b = H.fromFunction(() => time); assert.equal(H.at(b), 0); time = 1; assert.equal(H.at(b), 1); time = 2; assert.equal(H.at(b), 2); time = 3; assert.equal(H.at(b), 3); }); it("does not recompute when pulling with same timestamp", () => { let callCount = 0; const b = H.fromFunction(() => { callCount++; return 0; }); b.at(0); b.at(0); b.at(1); b.at(1); assert.strictEqual(callCount, 2); }); }); describe("functor", () => { describe("map", () => { it("maps over initial value from parent", () => { const b = Behavior.of(3); assert.strictEqual(at(b, 1), 3); const mapped = map(double, b); let a; mapped.observe((v: unknown) => (a = v), () => {}); assert.strictEqual(a, 6); }); it("maps constant function", () => { const b = sinkBehavior(0); const mapped = map(double, b); const cb = spy(); mapped.subscribe(cb); push(1, b); push(2, b); push(3, b); assert.deepEqual(cb.args, [[0], [2], [4], [6]]); }); it("maps time function", () => { let time = 0; const b = H.fromFunction(() => { return time; }); const mapped = map(double, b); const cb = spy(); mapped.observe(cb, (pull: (t: Time) => void) => { pull(1); time = 1; pull(2); time = 2; pull(3); time = 3; pull(4); }); assert.deepEqual(cb.args, [[0], [2], [4], [6]]); }); }); describe("mapTo", () => { it("maps to constant", () => { const b = Behavior.of(1); const b2 = mapTo(2, b); assert.strictEqual(at(b2), 2); }); }); }); describe("applicative", () => { it("returns a constant behavior from of", () => { const b1 = Behavior.of(1); const b2 = b1.of(2); assert.strictEqual(at(b1), 1); assert.strictEqual(at(b2), 2); }); describe("ap", () => { it("applies event of functions to event of numbers with publish", () => { const fnB = sinkBehavior(add(1)); const numE = sinkBehavior(3); const applied = H.ap(fnB, numE); const cb = spy(); applied.subscribe(cb); assert.equal(H.at(applied, 1), 4); push(add(2), fnB); assert.equal(H.at(applied, 2), 5); push(4, numE); assert.equal(H.at(applied, 3), 6); push(double, fnB); assert.equal(H.at(applied, 4), 8); assert.deepEqual(cb.args, [[4], [5], [6], [8]]); }); it("applies event of functions to event of numbers with pull", () => { let n = 1; let fn = add(5); const fnB = H.fromFunction(() => fn); const numB = H.fromFunction(() => n); const applied = H.ap(fnB, numB); const cb = spy(); applied.observe(cb, (pull) => { pull(1); fn = add(2); pull(2); n = 4; pull(3); fn = double; pull(4); n = 8; pull(5); return () => {}; }); assert.deepEqual(cb.args, [[6], [3], [6], [8], [16]]); }); it("applies pushed event of functions to pulled event of numbers", () => { let n = 1; const fnB = sinkBehavior(add(5)); const numE = H.fromFunction(() => n); const applied = H.ap(fnB, numE); const cb = spy(); let pull: () => void; applied.observe(cb, (pull_) => { pull = pull_; return () => {}; }); pull(); push(add(2), fnB); pull(); n = 4; pull(); push(double, fnB); pull(); n = 8; pull(); assert.deepEqual(cb.args, [[6], [3], [6], [8], [16]]); }); }); describe("lift", () => { it("lifts function of three arguments", () => { const b1 = H.sinkBehavior(1); const b2 = H.sinkBehavior(1); const b3 = H.sinkBehavior(1); const lifted = H.lift((a, b, c) => a * b + c, b1, b2, b3); const cb = spy(); lifted.subscribe(cb); assert.strictEqual(at(lifted), 2); push(2, b2); assert.strictEqual(at(lifted), 3); push(3, b1); assert.strictEqual(at(lifted), 7); push(3, b3); assert.strictEqual(at(lifted), 9); assert.deepEqual(cb.args, [[2], [3], [7], [9]]); }); it("lift function of five arguments", () => { const b = H.lift( (a, b, c, d, e) => (a - b + c) * (d + e), Behavior.of(1), Behavior.of(2), Behavior.of(3), Behavior.of(4), Behavior.of(5) ); assert.strictEqual(H.at(b), 18); }); it("handles diamond dependency", () => { // p // / \ // b1 b2 // \ / // b3 const p = sinkBehavior(3); const b1 = p.map((n) => n * n); const b2 = p.map((n) => n + 4); const b3 = H.lift((n, m) => n + m, b1, b2); const cb = subscribeSpy(b3); p.newValue(4); assert.deepEqual(cb.args, [[16], [24]]); }); it("only switched to push if all parents are push", () => { // In this test the lifted behavior `b3` starts out in the pull state // since both of its parents are in pull. Then one of the parents // switches to push. But, since one parent is still in pull the lifted // behavior should remain in pull. let n = 1; const b1 = H.fromFunction(() => n); const fut = H.sinkFuture<H.Behavior<number>>(); const b2 = H.switchTo(fromFunction(() => 2), fut); const b3 = H.lift((n, m) => n + m, b1, b2); observe( () => {}, () => { return () => { throw new Error("Should not be called."); }; }, b3 ); expect(H.at(b3)).toEqual(3); fut.resolve(H.sinkBehavior(5)); expect(H.at(b3)).toEqual(6); n = 2; expect(H.at(b3)).toEqual(7); }); }); }); describe("flatMap", () => { it("handles a constant behavior", () => { const b1 = Behavior.of(12); const b2 = b1.flatMap((x) => Behavior.of(x * x)); b2.observe((_v) => {}, () => () => {}); assert.strictEqual(at(b2), 144); }); it("handles changing outer behavior", () => { const b1 = sinkBehavior(0); const b2 = b1.flatMap((x) => Behavior.of(x * x)); const cb = spy(); b2.observe(cb, () => () => {}); b1.push(2); b1.push(3); assert.deepEqual(cb.args, [[0], [4], [9]]); }); it("handles changing inner behavior", () => { const inner = sinkBehavior(0); const b = Behavior.of(1).flatMap((_) => inner); const cb = spy(); b.observe(cb, () => () => {}); assert.strictEqual(at(b), 0); inner.push(2); assert.strictEqual(at(b), 2); inner.push(3); assert.strictEqual(at(b), 3); assert.deepEqual(cb.args, [[0], [2], [3]]); }); it("stops subscribing to past inner behavior", () => { const inner = sinkBehavior(0); const outer = sinkBehavior(1); const b = outer.flatMap((n) => (n === 1 ? inner : Behavior.of(6))); b.observe(() => {}, () => () => {}); assert.strictEqual(at(b), 0); inner.push(2); assert.strictEqual(at(b), 2); outer.push(2); assert.strictEqual(at(b), 6); inner.push(3); assert.strictEqual(at(b), 6); }); it("handles changes from both inner and outer", () => { const outer = sinkBehavior(0); const inner1 = sinkBehavior(1); const inner2 = sinkBehavior(3); const b = outer.flatMap((n) => { if (n === 0) { return Behavior.of(0); } else if (n === 1) { return inner1; } else if (n === 2) { return inner2; } }); b.observe(() => {}, () => () => {}); assert.strictEqual(at(b), 0); outer.push(1); assert.strictEqual(at(b), 1); inner1.push(2); assert.strictEqual(at(b), 2); outer.push(2); assert.strictEqual(at(b), 3); inner1.push(7); // Pushing to previous inner should have no effect assert.strictEqual(at(b), 3); inner2.push(4); assert.strictEqual(at(b), 4); }); it("can switch between pulling and pushing", () => { const pushingB = sinkBehavior(0); let variable = 7; const pullingB = H.fromFunction(() => variable); const outer = sinkBehavior(true); const chained = outer.flatMap((b) => (b ? pushingB : pullingB)); const pushSpy = spy(); const beginPullingSpy = spy(); const endPullingSpy = spy(); const handlePulling = (...args: unknown[]) => { beginPullingSpy(...args); return endPullingSpy; }; // Test that several observers are notified chained.observe(pushSpy, handlePulling); pushingB.push(1); pushingB.push(2); outer.push(false); assert.strictEqual(at(chained), 7); variable = 8; assert.strictEqual(at(chained), 8); pushingB.push(3); pushingB.push(4); outer.push(true); pushingB.push(5); outer.push(false); variable = 9; assert.strictEqual(at(chained), 9); assert.deepEqual(pushSpy.args, [[0], [1], [2], [4], [5]]); assert.equal(beginPullingSpy.callCount, 2); assert.equal(endPullingSpy.callCount, 1); }); it("works with go-notation", () => { const a = H.sinkBehavior(1); const b = go(function*(): IterableIterator<any> { const val: number = yield a; return val * 2; }); const cb = spy(); b.subscribe(cb); a.push(7); assert.deepEqual(cb.args, [[2], [14]]); }); }); describe("flat", () => { it("has proper type", () => { const b = Behavior.of(Behavior.of("foo")); H.flat(b).map((s) => s + "bar"); }); }); describe("format", () => { it("interpolates string", () => { const bs1 = sinkBehavior("foo"); const bs2 = sinkBehavior("bar"); const b = format`${bs1} and ${bs2}!`; const cb = spy(); b.subscribe(cb); bs1.push("Hello"); bs2.push("goodbye"); assert.deepEqual(cb.args, [ ["foo and bar!"], ["Hello and bar!"], ["Hello and goodbye!"] ]); }); it("insert numbers", () => { const bs1 = sinkBehavior("foo"); const bs2 = sinkBehavior(12); const b = format`first ${bs1} then ${bs2}!`; const cb = spy(); b.subscribe(cb); bs1.push("bar"); bs2.push(24); assert.deepEqual(cb.args, [ ["first foo then 12!"], ["first bar then 12!"], ["first bar then 24!"] ]); }); it("supports literals", () => { const bs1 = sinkBehavior("foo"); const n = 12; const s = "then"; const b = format`first ${bs1} ${s} ${n}!`; const cb = spy(); b.subscribe(cb); bs1.push("bar"); assert.deepEqual(cb.args, [ ["first foo then 12!"], ["first bar then 12!"] ]); }); }); describe("moment", () => { it("works as lift", () => { const b1 = sinkBehavior(0); const b2 = sinkBehavior(1); const derived = moment((at) => { return at(b1) + at(b2); }); const cb = spy(); derived.subscribe(cb); b1.push(2); b2.push(3); assert.deepEqual(cb.args, [[1], [3], [5]]); }); it("adds and removes dependencies", () => { const flag = sinkBehavior(true); const b1 = sinkBehavior(2); const b2 = sinkBehavior(3); const derived = moment((at) => { return at(flag) ? at(b1) : at(b2); }); const cb = spy(); derived.subscribe(cb); b1.push(4); flag.push(false); b2.push(5); b1.push(6); assert.deepEqual(cb.args, [[2], [4], [3], [5]]); }); it("can combine behaviors from array", () => { const nr1 = sinkBehavior(4); const nr2 = sinkBehavior(3); const nr3 = sinkBehavior(2); const count1 = { count: nr1 }; const count2 = { count: nr2 }; const count3 = { count: nr3 }; const list: H.SinkBehavior<{ count: Behavior<number> }[]> = sinkBehavior( [] ); const derived = moment((at) => { return at(list) .map(({ count }) => at(count)) .reduce((n, m) => n + m, 0); }); const cb = spy(); derived.subscribe(cb); list.push([count1, count2, count3]); nr2.push(5); list.push([count1, count3]); nr2.push(10); nr3.push(3); assert.deepEqual(cb.args, [[0], [9], [11], [6], [7]]); }); it("works with placeholders", () => { const p = placeholder<number>(); const b0 = sinkBehavior(3); const b1 = sinkBehavior(1); const b2 = sinkBehavior(2); const derived = moment((at) => { return at(b1) + at(p) + at(b2); }); const cb = spy(); derived.subscribe(cb); b1.push(2); p.replaceWith(b0); b0.push(0); assert.deepEqual(cb.args, [[7], [4]]); }); it("works with snapshot", () => { const b1 = H.sinkBehavior(1); const b2 = H.moment((at) => at(b1) * 2); const snapped = H.snapshot(b2, H.empty); subscribeSpy(snapped); }); it("time doesn't pass inside moment", () => { const b = moment((at) => { const t1 = at(time); while (Date.now() <= t1) { undefined; } const t2 = at(time); assert.strictEqual(t1, t2); }); b.observe( () => {}, (pull) => { pull(); return () => {}; } ); }); it("can be sampled", () => { const b = Behavior.of(3); const b2 = H.moment((at) => 2 * at(b)); const n = H.at(b2); assert.strictEqual(n, 6); }); }); }); describe("Behavior and Future", () => { describe("whenFrom", () => { it("gives occurred future when behavior is true", () => { let occurred = false; const b = Behavior.of(true); const fut = runNow(H.when(b)); fut.subscribe((_) => (occurred = true)); assert.strictEqual(occurred, true); }); it("future occurs when behavior turns true", () => { let occurred = false; const b = sinkBehavior(false); const w = H.whenFrom(b); const fut = at(w); fut.subscribe((_) => (occurred = true)); assert.strictEqual(occurred, false); b.push(true); assert.strictEqual(occurred, true); }); }); describe("snapshotAt", () => { it("snapshots behavior at future occurring in future", () => { let result: number; const bSink = sinkBehavior(1); const futureSink = H.sinkFuture(); const mySnapshot = at(H.snapshotAt(bSink, futureSink)); mySnapshot.subscribe((res) => (result = res)); bSink.push(2); bSink.push(3); futureSink.resolve({}); bSink.push(4); assert.strictEqual(result, 3); }); it("uses current value when future occurred in the past", () => { let result: number; const bSink = sinkBehavior(1); const occurredFuture = H.Future.of({}); bSink.push(2); const mySnapshot = at(H.snapshotAt(bSink, occurredFuture)); mySnapshot.subscribe((res) => (result = res)); bSink.push(3); assert.strictEqual(result, 2); }); }); describe("switchTo", () => { it("steps to new value", () => { const futureSink = sinkFuture<number>(); const step = H.stepTo(3, futureSink); const cb = subscribeSpy(step); assert.strictEqual(at(step), 3); futureSink.resolve(7); assert.strictEqual(at(step), 7); assert.deepEqual(cb.args, [[3], [7]]); }); }); describe("switchTo", () => { it("switches to new behavior", () => { const b1 = sinkBehavior(1); const b2 = sinkBehavior(8); const futureSink = sinkFuture<Behavior<number>>(); const switching = switchTo(b1, futureSink); const cb = subscribeSpy(switching); assert.strictEqual(at(switching), 1); b2.push(9); assert.strictEqual(at(switching), 1); b1.push(2); b1.push(3); futureSink.resolve(b2); b2.push(10); assert.deepEqual(cb.args, [[1], [2], [3], [9], [10]]); }); it("changes from push to pull", () => { const pushSpy = spy(); const beginPullingSpy = spy(); const endPullingSpy = spy(); const handlePulling = (...args: unknown[]) => { beginPullingSpy(...args); return endPullingSpy; }; const pushingB = sinkBehavior(0); let x = 7; const pullingB = fromFunction(() => x); const futureSink = sinkFuture<Behavior<number>>(); const switching = switchTo(pushingB, futureSink); observe(pushSpy, handlePulling, switching); assert.strictEqual(at(switching), 0); pushingB.push(1); assert.strictEqual(at(switching), 1); futureSink.resolve(pullingB); assert.strictEqual(at(switching), 7); x = 8; assert.strictEqual(at(switching), 8); assert.strictEqual(beginPullingSpy.callCount, 1); assert.strictEqual(endPullingSpy.callCount, 0); }); it("changes from pull to push", () => { let beginPull = false; let endPull = false; const pushed: number[] = []; let x = 0; const b1 = fromFunction(() => x); const b2 = sinkBehavior(2); const futureSink = sinkFuture<Behavior<number>>(); const switching = switchTo(b1, futureSink); observe( (n: number) => pushed.push(n), () => { beginPull = true; return () => { endPull = true; }; }, switching ); assert.strictEqual(beginPull, true); assert.strictEqual(at(switching), 0); x = 1; assert.strictEqual(at(switching), 1); assert.strictEqual(endPull, false); futureSink.resolve(b2); assert.strictEqual(endPull, true); b2.push(3); assert.deepEqual(pushed, [2, 3]); }); }); describe("freezeTo", () => { it("freezes to the future's resolve value", () => { const cb = spy(); const b = sinkBehavior("a"); const f = sinkFuture<string>(); const frozenBehavior = freezeTo(b, f); frozenBehavior.subscribe(cb); b.push("b"); f.resolve("c"); b.push("d"); assert.deepEqual(cb.args, [["a"], ["b"], ["c"]]); }); }); describe("freezeAt", () => { it("freezes to the value of the behavior when the future resolved", () => { const cb = spy(); const b = sinkBehavior("a"); const f = sinkFuture<string>(); const frozenBehavior = runNow(H.freezeAt(b, f)); frozenBehavior.subscribe(cb); b.push("b"); assert.deepEqual(cb.args, [["a"], ["b"]]); f.resolve("c"); b.push("d"); assert.deepEqual(cb.args, [["a"], ["b"]]); }); }); }); describe("Behavior and Stream", () => { describe("switcher", () => { it("switches to behavior", () => { const result: number[] = []; const stream = H.sinkStream<Behavior<number>>(); const initB = Behavior.of(1); const outerSwitcher = H.switcher(initB, stream); const switchingB = runNow(outerSwitcher); switchingB.subscribe((n) => result.push(n)); const sinkB = sinkBehavior(2); stream.push(sinkB); sinkB.push(3); assert.deepEqual(result, [1, 2, 3]); assert.deepEqual(at(runNow(outerSwitcher)), 1); }); it("stays in pull when stream switches to push", () => { const stream = H.placeholder<Behavior<number>>(); let val = 2; const initB = H.fromFunction(() => val); const switchingB = runNow(H.switcher(initB, stream)); observe( () => {}, () => { return () => { throw new Error("Should not be called."); }; }, switchingB ); stream.replaceWith(H.sinkStream()); val = 4; expect(H.at(switchingB)).toBe(4); }); }); describe("stepper", () => { it("steps to the last event value", () => { const s = H.sinkStream(); const b = runNow(H.stepper(0, s)); const cb = subscribeSpy(b); s.push(1); s.push(2); assert.deepEqual(cb.args, [[0], [1], [2]]); }); it("saves last occurrence from stream", () => { const s = H.sinkStream(); const t = runNow(H.stepper(1, s)); s.push(12); const spy = subscribeSpy(t); assert.deepEqual(spy.args, [[12]]); }); it("has old value in exact moment", () => { const s = H.sinkStream(); const b = runNow(H.stepper(0, s)); const res = H.snapshot(b, s); const spy = subscribeSpy(res); s.push(1); assert.strictEqual(b.at(), 1); s.push(2); assert.strictEqual(b.at(), 2); assert.deepEqual(spy.args, [[0], [1]]); }); }); describe("accum", () => { it("has accumFrom as method on stream", () => { H.empty.accumFrom(sum, 0); }); it("accumulates in a pure way", () => { const s = H.sinkStream<number>(); const accumulated = H.accumFrom(sum, 1, s); const b1 = at(accumulated); const spy = subscribeSpy(b1); assert.strictEqual(at(b1), 1); s.push(2); assert.strictEqual(at(b1), 3); const b2 = at(accumulated); assert.strictEqual(at(b2), 1); s.push(4); assert.strictEqual(at(b1), 7); assert.strictEqual(at(b2), 5); assert.deepEqual(spy.args, [[1], [3], [7]]); }); it("works with placeholder", () => { const s = H.sinkStream<number>(); const ps = H.placeholder(); const accumulated = runNow(ps.accum(sum, 1)); ps.replaceWith(s); s.push(2); s.push(3); s.push(4); assert.strictEqual(accumulated.at(), 10); }); }); describe("scanCombineFrom", () => { it("combines several streams", () => { const add = H.sinkStream(); const sub = H.sinkStream(); const mul = H.sinkStream(); const b = runNow( H.accumCombine( [ [add, (n: number, m: number) => n + m], [sub, (n: number, m: number) => m - n], [mul, (n: number, m: number) => n * m] ], 1 ) ); const cb = subscribeSpy(b); add.push(3); mul.push(3); sub.push(5); assert.deepEqual(cb.args, [[1], [4], [12], [7]]); }); }); describe("shiftCurrent", () => { it("returns stream that emits from stream", () => { const s1 = H.sinkStream(); const s2 = H.sinkStream(); const s3 = H.sinkStream(); const b = sinkBehavior(s1); const switching = H.shiftCurrent(b); const cb = spy(); switching.subscribe(cb); s1.push(1); s1.push(2); b.push(s2); s2.push(3); b.push(s3); s2.push(4); s3.push(5); s3.push(6); assert.deepEqual(cb.args, [[1], [2], [3], [5], [6]]); }); it("works with placeholder", () => { const s1 = H.sinkStream<number>(); const b = sinkBehavior(s1); const pB = H.placeholder<Stream<number>>(); const s = H.shiftCurrent(pB); const callback = subscribeSpy(s); pB.replaceWith(b); s1.push(0); assert.deepEqual(callback.args, [[0]]); }); // it("can be applied to `scanFrom` stream", () => { // // FIXME: `s3` below should result in an empty stream. This probably // // requires implementing pull stream. // const s1 = H.sinkStream(); // const s2 = H.scanFrom((_, b) => b + 1, 0, s1); // const s3 = H.shiftCurrent(s2); // H.subscribe((s) => console.log(s), s3); // }); }); describe("toggle", () => { it("has correct initial value", () => { const s1 = H.sinkStream(); const s2 = H.sinkStream(); const flipper1 = runNow(H.toggle(true, s1, s2)); assert.strictEqual(at(flipper1), true); const flipper2 = runNow(H.toggle(false, s1, s2)); assert.strictEqual(at(flipper2), false); }); it("flips properly", () => { const s1 = H.sinkStream(); const s2 = H.sinkStream(); const flipper = runNow(H.toggle(false, s1, s2)); const cb = subscribeSpy(flipper); s1.push(1); s2.push(2); s1.push(3); assert.deepEqual(cb.args, [[false], [true], [false], [true]]); }); }); describe("observe", () => { it("when switching from push to pull the pull handler can pull", () => { const pushingB = sinkBehavior(0); let variable = -1; const pullingB = H.fromFunction(() => variable); const outer = sinkBehavior<Behavior<number>>(pushingB); const flattened = H.flat(outer); const pushSpy = spy(); let pull: () => void; const handlePulling = (p: () => void): (() => void) => { pull = p; return () => undefined; }; flattened.observe(pushSpy, handlePulling); outer.push(pullingB); variable = 1; pull(); variable = 2; pull(); variable = 3; pull(); assert.deepEqual(pushSpy.args, [[0], [1], [2], [3]]); }); }); describe("log", () => { it("logs every change on push behavior", () => { const origLog = console.log; const strings: unknown[] = []; console.log = (...s: string[]) => strings.push(s); const b = sinkBehavior("hello"); b.log(); b.push("world"); console.log = origLog; assert.deepEqual(strings, [["hello"], ["world"]]); }); it("logs with prefix", () => { const origLog = console.log; const strings: unknown[] = []; console.log = (...s: string[]) => strings.push(s); const b = sinkBehavior("hello"); b.log("b"); b.push("world"); console.log = origLog; assert.deepEqual(strings, [["b", "hello"], ["b", "world"]]); }); it("logs on pull behavior", () => { const clock = useFakeTimers(); const origLog = console.log; const strings: unknown[] = []; console.log = (...s: string[]) => strings.push(s); let v = "zero"; const b = fromFunction(() => v); b.log("b", 1000); clock.tick(500); v = "one"; clock.tick(500); v = "two"; clock.tick(1000); // Restore console.log = origLog; clock.restore(); assert.deepEqual(strings, [["b", "zero"], ["b", "one"], ["b", "two"]]); }); }); });
the_stack
import * as GObject from "@gi-types/gobject"; export const ANALYZER_ANALYZING: number; export const ASCII_DTOSTR_BUF_SIZE: number; export const BIG_ENDIAN: number; export const CSET_A_2_Z: string; export const CSET_DIGITS: string; export const CSET_a_2_z: string; export const DATALIST_FLAGS_MASK: number; export const DATE_BAD_DAY: number; export const DATE_BAD_JULIAN: number; export const DATE_BAD_YEAR: number; export const DIR_SEPARATOR: number; export const DIR_SEPARATOR_S: string; export const E: number; export const GINT16_FORMAT: string; export const GINT16_MODIFIER: string; export const GINT32_FORMAT: string; export const GINT32_MODIFIER: string; export const GINT64_FORMAT: string; export const GINT64_MODIFIER: string; export const GINTPTR_FORMAT: string; export const GINTPTR_MODIFIER: string; export const GNUC_FUNCTION: string; export const GNUC_PRETTY_FUNCTION: string; export const GSIZE_FORMAT: string; export const GSIZE_MODIFIER: string; export const GSSIZE_FORMAT: string; export const GSSIZE_MODIFIER: string; export const GUINT16_FORMAT: string; export const GUINT32_FORMAT: string; export const GUINT64_FORMAT: string; export const GUINTPTR_FORMAT: string; export const HAVE_GINT64: number; export const HAVE_GNUC_VARARGS: number; export const HAVE_GNUC_VISIBILITY: number; export const HAVE_GROWING_STACK: number; export const HAVE_ISO_VARARGS: number; export const HOOK_FLAG_USER_SHIFT: number; export const IEEE754_DOUBLE_BIAS: number; export const IEEE754_FLOAT_BIAS: number; export const KEY_FILE_DESKTOP_GROUP: string; export const KEY_FILE_DESKTOP_KEY_ACTIONS: string; export const KEY_FILE_DESKTOP_KEY_CATEGORIES: string; export const KEY_FILE_DESKTOP_KEY_COMMENT: string; export const KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE: string; export const KEY_FILE_DESKTOP_KEY_EXEC: string; export const KEY_FILE_DESKTOP_KEY_GENERIC_NAME: string; export const KEY_FILE_DESKTOP_KEY_HIDDEN: string; export const KEY_FILE_DESKTOP_KEY_ICON: string; export const KEY_FILE_DESKTOP_KEY_MIME_TYPE: string; export const KEY_FILE_DESKTOP_KEY_NAME: string; export const KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN: string; export const KEY_FILE_DESKTOP_KEY_NO_DISPLAY: string; export const KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN: string; export const KEY_FILE_DESKTOP_KEY_PATH: string; export const KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY: string; export const KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS: string; export const KEY_FILE_DESKTOP_KEY_TERMINAL: string; export const KEY_FILE_DESKTOP_KEY_TRY_EXEC: string; export const KEY_FILE_DESKTOP_KEY_TYPE: string; export const KEY_FILE_DESKTOP_KEY_URL: string; export const KEY_FILE_DESKTOP_KEY_VERSION: string; export const KEY_FILE_DESKTOP_TYPE_APPLICATION: string; export const KEY_FILE_DESKTOP_TYPE_DIRECTORY: string; export const KEY_FILE_DESKTOP_TYPE_LINK: string; export const LITTLE_ENDIAN: number; export const LN10: number; export const LN2: number; export const LOG_2_BASE_10: number; export const LOG_DOMAIN: number; export const LOG_FATAL_MASK: number; export const LOG_LEVEL_USER_SHIFT: number; export const MAJOR_VERSION: number; export const MAXINT16: number; export const MAXINT32: number; export const MAXINT64: number; export const MAXINT8: number; export const MAXUINT16: number; export const MAXUINT32: number; export const MAXUINT64: number; export const MAXUINT8: number; export const MICRO_VERSION: number; export const MININT16: number; export const MININT32: number; export const MININT64: number; export const MININT8: number; export const MINOR_VERSION: number; export const MODULE_SUFFIX: string; export const OPTION_REMAINING: string; export const PDP_ENDIAN: number; export const PI: number; export const PID_FORMAT: string; export const PI_2: number; export const PI_4: number; export const POLLFD_FORMAT: string; export const PRIORITY_DEFAULT: number; export const PRIORITY_DEFAULT_IDLE: number; export const PRIORITY_HIGH: number; export const PRIORITY_HIGH_IDLE: number; export const PRIORITY_LOW: number; export const SEARCHPATH_SEPARATOR: number; export const SEARCHPATH_SEPARATOR_S: string; export const SIZEOF_LONG: number; export const SIZEOF_SIZE_T: number; export const SIZEOF_SSIZE_T: number; export const SIZEOF_VOID_P: number; export const SOURCE_CONTINUE: boolean; export const SOURCE_REMOVE: boolean; export const SQRT2: number; export const STR_DELIMITERS: string; export const SYSDEF_AF_INET: number; export const SYSDEF_AF_INET6: number; export const SYSDEF_AF_UNIX: number; export const SYSDEF_MSG_DONTROUTE: number; export const SYSDEF_MSG_OOB: number; export const SYSDEF_MSG_PEEK: number; export const TEST_OPTION_ISOLATE_DIRS: string; export const TIME_SPAN_DAY: number; export const TIME_SPAN_HOUR: number; export const TIME_SPAN_MILLISECOND: number; export const TIME_SPAN_MINUTE: number; export const TIME_SPAN_SECOND: number; export const UNICHAR_MAX_DECOMPOSITION_LENGTH: number; export const URI_RESERVED_CHARS_GENERIC_DELIMITERS: string; export const URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS: string; export const USEC_PER_SEC: number; export const VA_COPY_AS_ARRAY: number; export const VERSION_MIN_REQUIRED: number; export const WIN32_MSG_HANDLE: number; export function access(filename: string, mode: number): number; export function ascii_digit_value(c: number): number; export function ascii_dtostr(buffer: string, buf_len: number, d: number): string; export function ascii_formatd(buffer: string, buf_len: number, format: string, d: number): string; export function ascii_strcasecmp(s1: string, s2: string): number; export function ascii_strdown(str: string, len: number): string; export function ascii_string_to_signed(str: string, base: number, min: number, max: number): [boolean, number | null]; export function ascii_string_to_unsigned(str: string, base: number, min: number, max: number): [boolean, number | null]; export function ascii_strncasecmp(s1: string, s2: string, n: number): number; export function ascii_strtod(nptr: string): [number, string | null]; export function ascii_strtoll(nptr: string, base: number): [number, string | null]; export function ascii_strtoull(nptr: string, base: number): [number, string | null]; export function ascii_strup(str: string, len: number): string; export function ascii_tolower(c: number): number; export function ascii_toupper(c: number): number; export function ascii_xdigit_value(c: number): number; export function assert_warning( log_domain: string, file: string, line: number, pretty_function: string, expression: string ): void; export function assertion_message(domain: string, file: string, line: number, func: string, message: string): void; export function assertion_message_cmpstr( domain: string, file: string, line: number, func: string, expr: string, arg1: string, cmp: string, arg2: string ): void; export function assertion_message_error( domain: string, file: string, line: number, func: string, expr: string, error: Error, error_domain: Quark, error_code: number ): void; export function atexit(func: VoidFunc): void; export function atomic_int_add(atomic: number, val: number): number; export function atomic_int_and(atomic: number, val: number): number; export function atomic_int_compare_and_exchange(atomic: number, oldval: number, newval: number): boolean; export function atomic_int_dec_and_test(atomic: number): boolean; export function atomic_int_exchange_and_add(atomic: number, val: number): number; export function atomic_int_get(atomic: number): number; export function atomic_int_inc(atomic: number): void; export function atomic_int_or(atomic: number, val: number): number; export function atomic_int_set(atomic: number, newval: number): void; export function atomic_int_xor(atomic: number, val: number): number; export function atomic_pointer_add(atomic: any, val: number): number; export function atomic_pointer_and(atomic: any, val: number): number; export function atomic_pointer_compare_and_exchange(atomic: any, oldval?: any | null, newval?: any | null): boolean; export function atomic_pointer_get(atomic: any): any | null; export function atomic_pointer_or(atomic: any, val: number): number; export function atomic_pointer_set(atomic: any, newval?: any | null): void; export function atomic_pointer_xor(atomic: any, val: number): number; export function atomic_rc_box_acquire(mem_block: any): any; export function atomic_rc_box_alloc(block_size: number): any; export function atomic_rc_box_alloc0(block_size: number): any; export function atomic_rc_box_dup(block_size: number, mem_block: any): any; export function atomic_rc_box_get_size(mem_block: any): number; export function atomic_rc_box_release(mem_block: any): void; export function atomic_rc_box_release_full(mem_block: any): void; export function atomic_ref_count_compare(arc: number, val: number): boolean; export function atomic_ref_count_dec(arc: number): boolean; export function atomic_ref_count_inc(arc: number): void; export function atomic_ref_count_init(arc: number): void; export function base64_decode(text: string): Uint8Array; export function base64_decode_inplace(text: Uint8Array | string): [number, Uint8Array]; export function base64_encode(data?: Uint8Array | null): string; export function base64_encode_close( break_lines: boolean, state: number, save: number ): [number, Uint8Array, number, number]; export function base64_encode_step( _in: Uint8Array | string, break_lines: boolean, state: number, save: number ): [number, Uint8Array, number, number]; export function basename(file_name: string): string; export function bit_lock(address: number, lock_bit: number): void; export function bit_nth_lsf(mask: number, nth_bit: number): number; export function bit_nth_msf(mask: number, nth_bit: number): number; export function bit_storage(number: number): number; export function bit_trylock(address: number, lock_bit: number): boolean; export function bit_unlock(address: number, lock_bit: number): void; export function bookmark_file_error_quark(): Quark; export function build_filenamev(args: string[]): string; export function build_pathv(separator: string, args: string[]): string; export function byte_array_free(array: Uint8Array | string, free_segment: boolean): number; export function byte_array_free_to_bytes(array: Uint8Array | string): Bytes; export function byte_array_new(): Uint8Array; export function byte_array_new_take(data: Uint8Array | string): Uint8Array; export function byte_array_steal(array: Uint8Array | string): [number, number | null]; export function byte_array_unref(array: Uint8Array | string): void; export function canonicalize_filename(filename: string, relative_to?: string | null): string; export function chdir(path: string): number; export function check_version(required_major: number, required_minor: number, required_micro: number): string; export function checksum_type_get_length(checksum_type: ChecksumType): number; export function child_watch_add( priority: number, pid: Pid, _function: ChildWatchFunc, notify?: DestroyNotify | null ): number; export function child_watch_source_new(pid: Pid): Source; export function clear_error(): void; export function close(fd: number): boolean; export function compute_checksum_for_bytes(checksum_type: ChecksumType, data: Bytes | Uint8Array): string; export function compute_checksum_for_data(checksum_type: ChecksumType, data: Uint8Array | string): string; export function compute_checksum_for_string(checksum_type: ChecksumType, str: string, length: number): string; export function compute_hmac_for_bytes( digest_type: ChecksumType, key: Bytes | Uint8Array, data: Bytes | Uint8Array ): string; export function compute_hmac_for_data( digest_type: ChecksumType, key: Uint8Array | string, data: Uint8Array | string ): string; export function compute_hmac_for_string( digest_type: ChecksumType, key: Uint8Array | string, str: string, length: number ): string; export function convert( str: Uint8Array | string, to_codeset: string, from_codeset: string ): [Uint8Array, number | null]; export function convert_error_quark(): Quark; export function convert_with_fallback( str: Uint8Array | string, to_codeset: string, from_codeset: string, fallback: string ): [Uint8Array, number | null]; export function datalist_foreach(datalist: Data, func: DataForeachFunc): void; export function datalist_get_data(datalist: Data, key: string): any | null; export function datalist_get_flags(datalist: Data): number; export function datalist_id_get_data(datalist: Data, key_id: Quark): any | null; export function datalist_set_flags(datalist: Data, flags: number): void; export function datalist_unset_flags(datalist: Data, flags: number): void; export function dataset_destroy(dataset_location: any): void; export function dataset_foreach(dataset_location: any, func: DataForeachFunc): void; export function dataset_id_get_data(dataset_location: any, key_id: Quark): any | null; export function date_get_days_in_month(month: DateMonth, year: DateYear): number; export function date_get_monday_weeks_in_year(year: DateYear): number; export function date_get_sunday_weeks_in_year(year: DateYear): number; export function date_is_leap_year(year: DateYear): boolean; export function date_strftime(s: string, slen: number, format: string, date: Date): number; export function date_time_compare(dt1: any, dt2: any): number; export function date_time_equal(dt1: any, dt2: any): boolean; export function date_time_hash(datetime: any): number; export function date_valid_day(day: DateDay): boolean; export function date_valid_dmy(day: DateDay, month: DateMonth, year: DateYear): boolean; export function date_valid_julian(julian_date: number): boolean; export function date_valid_month(month: DateMonth): boolean; export function date_valid_weekday(weekday: DateWeekday): boolean; export function date_valid_year(year: DateYear): boolean; export function dcgettext(domain: string | null, msgid: string, category: number): string; export function dgettext(domain: string | null, msgid: string): string; export function dir_make_tmp(tmpl?: string | null): string; export function direct_equal(v1?: any | null, v2?: any | null): boolean; export function direct_hash(v?: any | null): number; export function dngettext(domain: string | null, msgid: string, msgid_plural: string, n: number): string; export function double_equal(v1: any, v2: any): boolean; export function double_hash(v: any): number; export function dpgettext(domain: string | null, msgctxtid: string, msgidoffset: number): string; export function dpgettext2(domain: string | null, context: string, msgid: string): string; export function environ_getenv(envp: string[] | null, variable: string): string; export function environ_setenv(envp: string[] | null, variable: string, value: string, overwrite: boolean): string[]; export function environ_unsetenv(envp: string[] | null, variable: string): string[]; export function file_error_from_errno(err_no: number): FileError; export function file_error_quark(): Quark; export function file_get_contents(filename: string): [boolean, Uint8Array]; export function file_open_tmp(tmpl: string | null): [number, string]; export function file_read_link(filename: string): string; export function file_set_contents(filename: string, contents: Uint8Array | string): boolean; export function file_set_contents_full( filename: string, contents: Uint8Array | string, flags: FileSetContentsFlags, mode: number ): boolean; export function file_test(filename: string, test: FileTest): boolean; export function filename_display_basename(filename: string): string; export function filename_display_name(filename: string): string; export function filename_from_uri(uri: string): [string, string | null]; export function filename_from_utf8(utf8string: string, len: number): [string, number | null, number | null]; export function filename_to_uri(filename: string, hostname?: string | null): string; export function filename_to_utf8(opsysstring: string, len: number): [string, number | null, number | null]; export function find_program_in_path(program: string): string | null; export function format_size(size: number): string; export function format_size_for_display(size: number): string; export function format_size_full(size: number, flags: FormatSizeFlags): string; export function free(mem?: any | null): void; export function get_application_name(): string | null; export function get_charset(): [boolean, string | null]; export function get_codeset(): string; export function get_console_charset(): [boolean, string | null]; export function get_current_dir(): string; export function get_current_time(result: TimeVal): void; export function get_environ(): string[]; export function get_filename_charsets(): [boolean, string[]]; export function get_home_dir(): string; export function get_host_name(): string; export function get_language_names(): string[]; export function get_language_names_with_category(category_name: string): string[]; export function get_locale_variants(locale: string): string[]; export function get_monotonic_time(): number; export function get_num_processors(): number; export function get_os_info(key_name: string): string | null; export function get_prgname(): string | null; export function get_real_name(): string; export function get_real_time(): number; export function get_system_config_dirs(): string[]; export function get_system_data_dirs(): string[]; export function get_tmp_dir(): string; export function get_user_cache_dir(): string; export function get_user_config_dir(): string; export function get_user_data_dir(): string; export function get_user_name(): string; export function get_user_runtime_dir(): string; export function get_user_special_dir(directory: UserDirectory): string; export function getenv(variable: string): string; export function hash_table_add(hash_table: HashTable<any, any>, key?: any | null): boolean; export function hash_table_contains(hash_table: HashTable<any, any>, key?: any | null): boolean; export function hash_table_destroy(hash_table: HashTable<any, any>): void; export function hash_table_insert(hash_table: HashTable<any, any>, key?: any | null, value?: any | null): boolean; export function hash_table_lookup(hash_table: HashTable<any, any>, key?: any | null): any | null; export function hash_table_lookup_extended( hash_table: HashTable<any, any>, lookup_key?: any | null ): [boolean, any | null, any | null]; export function hash_table_remove(hash_table: HashTable<any, any>, key?: any | null): boolean; export function hash_table_remove_all(hash_table: HashTable<any, any>): void; export function hash_table_replace(hash_table: HashTable<any, any>, key?: any | null, value?: any | null): boolean; export function hash_table_size(hash_table: HashTable<any, any>): number; export function hash_table_steal(hash_table: HashTable<any, any>, key?: any | null): boolean; export function hash_table_steal_all(hash_table: HashTable<any, any>): void; export function hash_table_steal_extended( hash_table: HashTable<any, any>, lookup_key?: any | null ): [boolean, any | null, any | null]; export function hash_table_unref(hash_table: HashTable<any, any>): void; export function hook_destroy(hook_list: HookList, hook_id: number): boolean; export function hook_destroy_link(hook_list: HookList, hook: Hook): void; export function hook_free(hook_list: HookList, hook: Hook): void; export function hook_insert_before(hook_list: HookList, sibling: Hook | null, hook: Hook): void; export function hook_prepend(hook_list: HookList, hook: Hook): void; export function hook_unref(hook_list: HookList, hook: Hook): void; export function hostname_is_ascii_encoded(hostname: string): boolean; export function hostname_is_ip_address(hostname: string): boolean; export function hostname_is_non_ascii(hostname: string): boolean; export function hostname_to_ascii(hostname: string): string; export function hostname_to_unicode(hostname: string): string; export function idle_add(priority: number, _function: SourceFunc, notify?: DestroyNotify | null): number; export function idle_remove_by_data(data?: any | null): boolean; export function idle_source_new(): Source; export function int64_equal(v1: any, v2: any): boolean; export function int64_hash(v: any): number; export function int_equal(v1: any, v2: any): boolean; export function int_hash(v: any): number; export function intern_static_string(string?: string | null): string; export function intern_string(string?: string | null): string; export function io_add_watch(channel: IOChannel, priority: number, condition: IOCondition, func: IOFunc): number; export function io_channel_error_from_errno(en: number): IOChannelError; export function io_channel_error_quark(): Quark; export function io_create_watch(channel: IOChannel, condition: IOCondition): Source; export function key_file_error_quark(): Quark; export function listenv(): string[]; export function locale_from_utf8(utf8string: string, len: number): [Uint8Array, number | null]; export function locale_to_utf8(opsysstring: Uint8Array | string): [string, number | null, number | null]; export function log_default_handler( log_domain: string | null, log_level: LogLevelFlags, message?: string | null, unused_data?: any | null ): void; export function log_remove_handler(log_domain: string, handler_id: number): void; export function log_set_always_fatal(fatal_mask: LogLevelFlags): LogLevelFlags; export function log_set_fatal_mask(log_domain: string, fatal_mask: LogLevelFlags): LogLevelFlags; export function log_set_handler(log_domain: string | null, log_levels: LogLevelFlags, log_func: LogFunc): number; export function log_set_writer_func(): void; export function log_structured_array(log_level: LogLevelFlags, fields: LogField[]): void; export function log_variant(log_domain: string | null, log_level: LogLevelFlags, fields: Variant): void; export function log_writer_default( log_level: LogLevelFlags, fields: LogField[], user_data?: any | null ): LogWriterOutput; export function log_writer_format_fields(log_level: LogLevelFlags, fields: LogField[], use_color: boolean): string; export function log_writer_is_journald(output_fd: number): boolean; export function log_writer_journald( log_level: LogLevelFlags, fields: LogField[], user_data?: any | null ): LogWriterOutput; export function log_writer_standard_streams( log_level: LogLevelFlags, fields: LogField[], user_data?: any | null ): LogWriterOutput; export function log_writer_supports_color(output_fd: number): boolean; export function main_context_default(): MainContext; export function main_context_get_thread_default(): MainContext; export function main_context_ref_thread_default(): MainContext; export function main_current_source(): Source; export function main_depth(): number; export function malloc(n_bytes: number): any | null; export function malloc0(n_bytes: number): any | null; export function malloc0_n(n_blocks: number, n_block_bytes: number): any | null; export function malloc_n(n_blocks: number, n_block_bytes: number): any | null; export function markup_error_quark(): Quark; export function markup_escape_text(text: string, length: number): string; export function mem_is_system_malloc(): boolean; export function mem_profile(): void; export function mem_set_vtable(vtable: MemVTable): void; export function memdup(mem: any | null, byte_size: number): any | null; export function mkdir_with_parents(pathname: string, mode: number): number; export function nullify_pointer(nullify_location: any): void; export function number_parser_error_quark(): Quark; export function on_error_query(prg_name: string): void; export function on_error_stack_trace(prg_name: string): void; export function once_init_enter(location: any): boolean; export function once_init_leave(location: any, result: number): void; export function option_error_quark(): Quark; export function parse_debug_string(string: string | null, keys: DebugKey[]): number; export function path_get_basename(file_name: string): string; export function path_get_dirname(file_name: string): string; export function path_is_absolute(file_name: string): boolean; export function path_skip_root(file_name: string): string | null; export function pattern_match( pspec: PatternSpec, string_length: number, string: string, string_reversed?: string | null ): boolean; export function pattern_match_simple(pattern: string, string: string): boolean; export function pattern_match_string(pspec: PatternSpec, string: string): boolean; export function pointer_bit_lock(address: any, lock_bit: number): void; export function pointer_bit_trylock(address: any, lock_bit: number): boolean; export function pointer_bit_unlock(address: any, lock_bit: number): void; export function poll(fds: PollFD, nfds: number, timeout: number): number; export function propagate_error(src: Error): Error | null; export function quark_from_static_string(string?: string | null): Quark; export function quark_from_string(string?: string | null): Quark; export function quark_to_string(quark: Quark): string; export function quark_try_string(string?: string | null): Quark; export function random_double(): number; export function random_double_range(begin: number, end: number): number; export function random_int(): number; export function random_int_range(begin: number, end: number): number; export function random_set_seed(seed: number): void; export function rc_box_acquire(mem_block: any): any; export function rc_box_alloc(block_size: number): any; export function rc_box_alloc0(block_size: number): any; export function rc_box_dup(block_size: number, mem_block: any): any; export function rc_box_get_size(mem_block: any): number; export function rc_box_release(mem_block: any): void; export function rc_box_release_full(mem_block: any): void; export function realloc(mem: any | null, n_bytes: number): any | null; export function realloc_n(mem: any | null, n_blocks: number, n_block_bytes: number): any | null; export function ref_count_compare(rc: number, val: number): boolean; export function ref_count_dec(rc: number): boolean; export function ref_count_inc(rc: number): void; export function ref_count_init(rc: number): void; export function ref_string_acquire(str: string): string; export function ref_string_length(str: string): number; export function ref_string_new(str: string): string; export function ref_string_new_intern(str: string): string; export function ref_string_new_len(str: string, len: number): string; export function ref_string_release(str: string): void; export function regex_check_replacement(replacement: string): [boolean, boolean | null]; export function regex_error_quark(): Quark; export function regex_escape_nul(string: string, length: number): string; export function regex_escape_string(string: string[]): string; export function regex_match_simple( pattern: string, string: string, compile_options: RegexCompileFlags, match_options: RegexMatchFlags ): boolean; export function regex_split_simple( pattern: string, string: string, compile_options: RegexCompileFlags, match_options: RegexMatchFlags ): string[]; export function reload_user_special_dirs_cache(): void; export function rmdir(filename: string): number; export function sequence_get(iter: SequenceIter): any | null; export function sequence_insert_before(iter: SequenceIter, data?: any | null): SequenceIter; export function sequence_move(src: SequenceIter, dest: SequenceIter): void; export function sequence_move_range(dest: SequenceIter, begin: SequenceIter, end: SequenceIter): void; export function sequence_range_get_midpoint(begin: SequenceIter, end: SequenceIter): SequenceIter; export function sequence_remove(iter: SequenceIter): void; export function sequence_remove_range(begin: SequenceIter, end: SequenceIter): void; export function sequence_set(iter: SequenceIter, data?: any | null): void; export function sequence_swap(a: SequenceIter, b: SequenceIter): void; export function set_application_name(application_name: string): void; export function set_error_literal(domain: Quark, code: number, message: string): Error | null; export function set_prgname(prgname: string): void; export function setenv(variable: string, value: string, overwrite: boolean): boolean; export function shell_error_quark(): Quark; export function shell_parse_argv(command_line: string): [boolean, string[] | null]; export function shell_quote(unquoted_string: string): string; export function shell_unquote(quoted_string: string): string; export function slice_alloc(block_size: number): any | null; export function slice_alloc0(block_size: number): any | null; export function slice_copy(block_size: number, mem_block?: any | null): any | null; export function slice_free1(block_size: number, mem_block?: any | null): void; export function slice_free_chain_with_offset(block_size: number, mem_chain: any | null, next_offset: number): void; export function slice_get_config(ckey: SliceConfig): number; export function slice_get_config_state(ckey: SliceConfig, address: number, n_values: number): number; export function slice_set_config(ckey: SliceConfig, value: number): void; export function source_remove(tag: number): boolean; export function source_remove_by_funcs_user_data(funcs: SourceFuncs, user_data?: any | null): boolean; export function source_remove_by_user_data(user_data?: any | null): boolean; export function source_set_name_by_id(tag: number, name: string): void; export function spaced_primes_closest(num: number): number; export function spawn_async( working_directory: string | null, argv: string[], envp: string[] | null, flags: SpawnFlags, child_setup?: SpawnChildSetupFunc | null ): [boolean, Pid | null]; export function spawn_async_with_fds( working_directory: string | null, argv: string[], envp: string[] | null, flags: SpawnFlags, child_setup: SpawnChildSetupFunc | null, stdin_fd: number, stdout_fd: number, stderr_fd: number ): [boolean, Pid | null]; export function spawn_async_with_pipes( working_directory: string | null, argv: string[], envp: string[] | null, flags: SpawnFlags, child_setup?: SpawnChildSetupFunc | null ): [boolean, Pid | null, number | null, number | null, number | null]; export function spawn_check_exit_status(exit_status: number): boolean; export function spawn_close_pid(pid: Pid): void; export function spawn_command_line_async(command_line: string): boolean; export function spawn_command_line_sync( command_line: string ): [boolean, Uint8Array | null, Uint8Array | null, number | null]; export function spawn_error_quark(): Quark; export function spawn_exit_error_quark(): Quark; export function spawn_sync( working_directory: string | null, argv: string[], envp: string[] | null, flags: SpawnFlags, child_setup?: SpawnChildSetupFunc | null ): [boolean, Uint8Array | null, Uint8Array | null, number | null]; export function stpcpy(dest: string, src: string): string; export function str_equal(v1: any, v2: any): boolean; export function str_has_prefix(str: string, prefix: string): boolean; export function str_has_suffix(str: string, suffix: string): boolean; export function str_hash(v: any): number; export function str_is_ascii(str: string): boolean; export function str_match_string(search_term: string, potential_hit: string, accept_alternates: boolean): boolean; export function str_to_ascii(str: string, from_locale?: string | null): string; export function str_tokenize_and_fold(string: string, translit_locale: string | null): [string[], string[]]; export function strcanon(string: string, valid_chars: string, substitutor: number): string; export function strcasecmp(s1: string, s2: string): number; export function strchomp(string: string): string; export function strchug(string: string): string; export function strcmp0(str1?: string | null, str2?: string | null): number; export function strcompress(source: string): string; export function strdelimit(string: string, delimiters: string | null, new_delimiter: number): string; export function strdown(string: string): string; export function strdup(str?: string | null): string; export function strerror(errnum: number): string; export function strescape(source: string, exceptions?: string | null): string; export function strfreev(str_array?: string | null): void; export function string_new(init?: string | null): String; export function string_new_len(init: string, len: number): String; export function string_sized_new(dfl_size: number): String; export function strip_context(msgid: string, msgval: string): string; export function strjoinv(separator: string | null, str_array: string): string; export function strlcat(dest: string, src: string, dest_size: number): number; export function strlcpy(dest: string, src: string, dest_size: number): number; export function strncasecmp(s1: string, s2: string, n: number): number; export function strndup(str: string, n: number): string; export function strnfill(length: number, fill_char: number): string; export function strreverse(string: string): string; export function strrstr(haystack: string, needle: string): string; export function strrstr_len(haystack: string, haystack_len: number, needle: string): string; export function strsignal(signum: number): string; export function strstr_len(haystack: string, haystack_len: number, needle: string): string; export function strtod(nptr: string): [number, string | null]; export function strup(string: string): string; export function strv_contains(strv: string, str: string): boolean; export function strv_equal(strv1: string, strv2: string): boolean; export function strv_get_type(): GObject.GType; export function strv_length(str_array: string): number; export function test_add_data_func(testpath: string, test_data: any | null, test_func: TestDataFunc): void; export function test_add_data_func_full(testpath: string, test_data: any | null, test_func: TestDataFunc): void; export function test_add_func(testpath: string, test_func: TestFunc): void; export function test_assert_expected_messages_internal(domain: string, file: string, line: number, func: string): void; export function test_bug(bug_uri_snippet: string): void; export function test_bug_base(uri_pattern: string): void; export function test_expect_message(log_domain: string | null, log_level: LogLevelFlags, pattern: string): void; export function test_fail(): void; export function test_failed(): boolean; export function test_get_dir(file_type: TestFileType): string; export function test_incomplete(msg?: string | null): void; export function test_log_type_name(log_type: TestLogType): string; export function test_queue_destroy(destroy_data?: any | null): void; export function test_queue_free(gfree_pointer?: any | null): void; export function test_rand_double(): number; export function test_rand_double_range(range_start: number, range_end: number): number; export function test_rand_int(): number; export function test_rand_int_range(begin: number, end: number): number; export function test_run(): number; export function test_run_suite(suite: TestSuite): number; export function test_set_nonfatal_assertions(): void; export function test_skip(msg?: string | null): void; export function test_subprocess(): boolean; export function test_summary(summary: string): void; export function test_timer_elapsed(): number; export function test_timer_last(): number; export function test_timer_start(): void; export function test_trap_assertions( domain: string, file: string, line: number, func: string, assertion_flags: number, pattern: string ): void; export function test_trap_fork(usec_timeout: number, test_trap_flags: TestTrapFlags): boolean; export function test_trap_has_passed(): boolean; export function test_trap_reached_timeout(): boolean; export function test_trap_subprocess( test_path: string | null, usec_timeout: number, test_flags: TestSubprocessFlags ): void; export function thread_error_quark(): Quark; export function thread_exit(retval?: any | null): void; export function thread_pool_get_max_idle_time(): number; export function thread_pool_get_max_unused_threads(): number; export function thread_pool_get_num_unused_threads(): number; export function thread_pool_set_max_idle_time(interval: number): void; export function thread_pool_set_max_unused_threads(max_threads: number): void; export function thread_pool_stop_unused_threads(): void; export function thread_self(): Thread; export function thread_yield(): void; export function time_val_from_iso8601(iso_date: string): [boolean, TimeVal]; export function timeout_add( priority: number, interval: number, _function: SourceFunc, notify?: DestroyNotify | null ): number; export function timeout_add_seconds( priority: number, interval: number, _function: SourceFunc, notify?: DestroyNotify | null ): number; export function timeout_source_new(interval: number): Source; export function timeout_source_new_seconds(interval: number): Source; export function trash_stack_height(stack_p: TrashStack): number; export function trash_stack_peek(stack_p: TrashStack): any | null; export function trash_stack_pop(stack_p: TrashStack): any | null; export function trash_stack_push(stack_p: TrashStack, data_p: any): void; export function try_malloc(n_bytes: number): any | null; export function try_malloc0(n_bytes: number): any | null; export function try_malloc0_n(n_blocks: number, n_block_bytes: number): any | null; export function try_malloc_n(n_blocks: number, n_block_bytes: number): any | null; export function try_realloc(mem: any | null, n_bytes: number): any | null; export function try_realloc_n(mem: any | null, n_blocks: number, n_block_bytes: number): any | null; export function ucs4_to_utf16(str: number, len: number): [number, number | null, number | null]; export function ucs4_to_utf8(str: number, len: number): [string, number | null, number | null]; export function unichar_break_type(c: number): UnicodeBreakType; export function unichar_combining_class(uc: number): number; export function unichar_compose(a: number, b: number): [boolean, number]; export function unichar_decompose(ch: number): [boolean, number, number]; export function unichar_digit_value(c: number): number; export function unichar_fully_decompose(ch: number, compat: boolean, result_len: number): [number, number | null]; export function unichar_get_mirror_char(ch: number, mirrored_ch: number): boolean; export function unichar_get_script(ch: number): UnicodeScript; export function unichar_isalnum(c: number): boolean; export function unichar_isalpha(c: number): boolean; export function unichar_iscntrl(c: number): boolean; export function unichar_isdefined(c: number): boolean; export function unichar_isdigit(c: number): boolean; export function unichar_isgraph(c: number): boolean; export function unichar_islower(c: number): boolean; export function unichar_ismark(c: number): boolean; export function unichar_isprint(c: number): boolean; export function unichar_ispunct(c: number): boolean; export function unichar_isspace(c: number): boolean; export function unichar_istitle(c: number): boolean; export function unichar_isupper(c: number): boolean; export function unichar_iswide(c: number): boolean; export function unichar_iswide_cjk(c: number): boolean; export function unichar_isxdigit(c: number): boolean; export function unichar_iszerowidth(c: number): boolean; export function unichar_to_utf8(c: number): [number, string | null]; export function unichar_tolower(c: number): number; export function unichar_totitle(c: number): number; export function unichar_toupper(c: number): number; export function unichar_type(c: number): UnicodeType; export function unichar_validate(ch: number): boolean; export function unichar_xdigit_value(c: number): number; export function unicode_canonical_decomposition(ch: number, result_len: number): number; export function unicode_canonical_ordering(string: number, len: number): void; export function unicode_script_from_iso15924(iso15924: number): UnicodeScript; export function unicode_script_to_iso15924(script: UnicodeScript): number; export function unix_error_quark(): Quark; export function unix_fd_add_full( priority: number, fd: number, condition: IOCondition, _function: UnixFDSourceFunc ): number; export function unix_fd_source_new(fd: number, condition: IOCondition): Source; export function unix_get_passwd_entry(user_name: string): any | null; export function unix_open_pipe(fds: number, flags: number): boolean; export function unix_set_fd_nonblocking(fd: number, nonblock: boolean): boolean; export function unix_signal_add(priority: number, signum: number, handler: SourceFunc): number; export function unix_signal_source_new(signum: number): Source; export function unlink(filename: string): number; export function unsetenv(variable: string): void; export function uri_build( flags: UriFlags, scheme: string, userinfo: string | null, host: string | null, port: number, path: string, query?: string | null, fragment?: string | null ): Uri; export function uri_build_with_user( flags: UriFlags, scheme: string, user: string | null, password: string | null, auth_params: string | null, host: string | null, port: number, path: string, query?: string | null, fragment?: string | null ): Uri; export function uri_error_quark(): Quark; export function uri_escape_bytes(unescaped: Uint8Array | string, reserved_chars_allowed?: string | null): string; export function uri_escape_string( unescaped: string, reserved_chars_allowed: string | null, allow_utf8: boolean ): string; export function uri_is_valid(uri_string: string, flags: UriFlags): boolean; export function uri_join( flags: UriFlags, scheme: string | null, userinfo: string | null, host: string | null, port: number, path: string, query?: string | null, fragment?: string | null ): string; export function uri_join_with_user( flags: UriFlags, scheme: string | null, user: string | null, password: string | null, auth_params: string | null, host: string | null, port: number, path: string, query?: string | null, fragment?: string | null ): string; export function uri_list_extract_uris(uri_list: string): string[]; export function uri_parse(uri_string: string, flags: UriFlags): Uri; export function uri_parse_params( params: string, length: number, separators: string, flags: UriParamsFlags ): HashTable<string, string>; export function uri_parse_scheme(uri: string): string | null; export function uri_peek_scheme(uri: string): string | null; export function uri_resolve_relative(base_uri_string: string | null, uri_ref: string, flags: UriFlags): string; export function uri_split( uri_ref: string, flags: UriFlags ): [boolean, string | null, string | null, string | null, number | null, string | null, string | null, string | null]; export function uri_split_network( uri_string: string, flags: UriFlags ): [boolean, string | null, string | null, number | null]; export function uri_split_with_user( uri_ref: string, flags: UriFlags ): [ boolean, string | null, string | null, string | null, string | null, string | null, number | null, string | null, string | null, string | null ]; export function uri_unescape_bytes(escaped_string: string, length: number, illegal_characters?: string | null): Bytes; export function uri_unescape_segment( escaped_string?: string | null, escaped_string_end?: string | null, illegal_characters?: string | null ): string; export function uri_unescape_string(escaped_string: string, illegal_characters?: string | null): string; export function usleep(microseconds: number): void; export function utf16_to_ucs4(str: number, len: number): [number, number | null, number | null]; export function utf16_to_utf8(str: number, len: number): [string, number | null, number | null]; export function utf8_casefold(str: string, len: number): string; export function utf8_collate(str1: string, str2: string): number; export function utf8_collate_key(str: string, len: number): string; export function utf8_collate_key_for_filename(str: string, len: number): string; export function utf8_find_next_char(p: string, end?: string | null): string | null; export function utf8_find_prev_char(str: string, p: string): string | null; export function utf8_get_char(p: string): number; export function utf8_get_char_validated(p: string, max_len: number): number; export function utf8_make_valid(str: string, len: number): string; export function utf8_normalize(str: string, len: number, mode: NormalizeMode): string | null; export function utf8_offset_to_pointer(str: string, offset: number): string; export function utf8_pointer_to_offset(str: string, pos: string): number; export function utf8_prev_char(p: string): string; export function utf8_strchr(p: string, len: number, c: number): string | null; export function utf8_strdown(str: string, len: number): string; export function utf8_strlen(p: string, max: number): number; export function utf8_strncpy(dest: string, src: string, n: number): string; export function utf8_strrchr(p: string, len: number, c: number): string | null; export function utf8_strreverse(str: string, len: number): string; export function utf8_strup(str: string, len: number): string; export function utf8_substring(str: string, start_pos: number, end_pos: number): string; export function utf8_to_ucs4(str: string, len: number): [number, number | null, number | null]; export function utf8_to_ucs4_fast(str: string, len: number): [number, number | null]; export function utf8_to_utf16(str: string, len: number): [number, number | null, number | null]; export function utf8_validate(str: Uint8Array | string): [boolean, string | null]; export function utf8_validate_len(str: Uint8Array | string): [boolean, string | null]; export function uuid_string_is_valid(str: string): boolean; export function uuid_string_random(): string; export function variant_get_gtype(): GObject.GType; export function variant_is_object_path(string: string): boolean; export function variant_is_signature(string: string): boolean; export function variant_parse( type: VariantType | null, text: string, limit?: string | null, endptr?: string | null ): Variant; export function variant_parse_error_print_context(error: Error, source_str: string): string; export function variant_parse_error_quark(): Quark; export function variant_parser_get_error_quark(): Quark; export function variant_type_checked_(arg0: string): VariantType; export function variant_type_string_get_depth_(type_string: string): number; export function variant_type_string_is_valid(type_string: string): boolean; export function variant_type_string_scan(string: string, limit?: string | null): [boolean, string | null]; export type ChildWatchFunc = (pid: Pid, status: number) => void; export type ClearHandleFunc = (handle_id: number) => void; export type CompareDataFunc = (a?: any | null, b?: any | null) => number; export type CompareFunc = (a?: any | null, b?: any | null) => number; export type CopyFunc = (src: any, data?: any | null) => any; export type DataForeachFunc = (key_id: Quark, data?: any | null) => void; export type DestroyNotify = (data?: any | null) => void; export type DuplicateFunc = (data?: any | null) => any | null; export type EqualFunc = (a?: any | null, b?: any | null) => boolean; export type FreeFunc = (data?: any | null) => void; export type Func = (data?: any | null) => void; export type HFunc = (key?: any | null, value?: any | null) => void; export type HRFunc = (key?: any | null, value?: any | null) => boolean; export type HashFunc = (key?: any | null) => number; export type HookCheckFunc = (data?: any | null) => boolean; export type HookCheckMarshaller = (hook: Hook, marshal_data?: any | null) => boolean; export type HookCompareFunc = (new_hook: Hook, sibling: Hook) => number; export type HookFinalizeFunc = (hook_list: HookList, hook: Hook) => void; export type HookFindFunc = (hook: Hook, data?: any | null) => boolean; export type HookFunc = (data?: any | null) => void; export type HookMarshaller = (hook: Hook, marshal_data?: any | null) => void; export type IOFunc = (source: IOChannel, condition: IOCondition, data?: any | null) => boolean; export type LogFunc = (log_domain: string, log_level: LogLevelFlags, message: string) => void; export type LogWriterFunc = (log_level: LogLevelFlags, fields: LogField[]) => LogWriterOutput; export type NodeForeachFunc = (node: Node, data?: any | null) => void; export type NodeTraverseFunc = (node: Node, data?: any | null) => boolean; export type OptionArgFunc = (option_name: string, value: string, data?: any | null) => boolean; export type OptionErrorFunc = (context: OptionContext, group: OptionGroup, data?: any | null) => void; export type OptionParseFunc = (context: OptionContext, group: OptionGroup, data?: any | null) => boolean; export type PollFunc = (ufds: PollFD, nfsd: number, timeout_: number) => number; export type PrintFunc = (string: string) => void; export type RegexEvalCallback = (match_info: MatchInfo, result: String) => boolean; export type ScannerMsgFunc = (scanner: Scanner, message: string, error: boolean) => void; export type SequenceIterCompareFunc = (a: SequenceIter, b: SequenceIter, data?: any | null) => number; export type SourceDisposeFunc = (source: Source) => void; export type SourceDummyMarshal = () => void; export type SourceFunc = () => boolean; export type SpawnChildSetupFunc = () => void; export type TestDataFunc = () => void; export type TestFixtureFunc = (fixture: any) => void; export type TestFunc = () => void; export type TestLogFatalFunc = (log_domain: string, log_level: LogLevelFlags, message: string) => boolean; export type ThreadFunc = (data?: any | null) => any | null; export type TranslateFunc = (str: string, data?: any | null) => string; export type TraverseFunc = (key?: any | null, value?: any | null, data?: any | null) => boolean; export type UnixFDSourceFunc = (fd: number, condition: IOCondition) => boolean; export type VoidFunc = () => void; export class BookmarkFileError extends Error { static $gtype: GObject.GType<BookmarkFileError>; constructor(options: { message: string; code: number }); constructor(copy: BookmarkFileError); // Properties static INVALID_URI: number; static INVALID_VALUE: number; static APP_NOT_REGISTERED: number; static URI_NOT_FOUND: number; static READ: number; static UNKNOWN_ENCODING: number; static WRITE: number; static FILE_NOT_FOUND: number; } export namespace ChecksumType { export const $gtype: GObject.GType<ChecksumType>; } export enum ChecksumType { MD5 = 0, SHA1 = 1, SHA256 = 2, SHA512 = 3, SHA384 = 4, } export class ConvertError extends Error { static $gtype: GObject.GType<ConvertError>; constructor(options: { message: string; code: number }); constructor(copy: ConvertError); // Properties static NO_CONVERSION: number; static ILLEGAL_SEQUENCE: number; static FAILED: number; static PARTIAL_INPUT: number; static BAD_URI: number; static NOT_ABSOLUTE_PATH: number; static NO_MEMORY: number; static EMBEDDED_NUL: number; } export namespace DateDMY { export const $gtype: GObject.GType<DateDMY>; } export enum DateDMY { DAY = 0, MONTH = 1, YEAR = 2, } export namespace DateMonth { export const $gtype: GObject.GType<DateMonth>; } export enum DateMonth { BAD_MONTH = 0, JANUARY = 1, FEBRUARY = 2, MARCH = 3, APRIL = 4, MAY = 5, JUNE = 6, JULY = 7, AUGUST = 8, SEPTEMBER = 9, OCTOBER = 10, NOVEMBER = 11, DECEMBER = 12, } export namespace DateWeekday { export const $gtype: GObject.GType<DateWeekday>; } export enum DateWeekday { BAD_WEEKDAY = 0, MONDAY = 1, TUESDAY = 2, WEDNESDAY = 3, THURSDAY = 4, FRIDAY = 5, SATURDAY = 6, SUNDAY = 7, } export namespace ErrorType { export const $gtype: GObject.GType<ErrorType>; } export enum ErrorType { UNKNOWN = 0, UNEXP_EOF = 1, UNEXP_EOF_IN_STRING = 2, UNEXP_EOF_IN_COMMENT = 3, NON_DIGIT_IN_CONST = 4, DIGIT_RADIX = 5, FLOAT_RADIX = 6, FLOAT_MALFORMED = 7, } export class FileError extends Error { static $gtype: GObject.GType<FileError>; constructor(options: { message: string; code: number }); constructor(copy: FileError); // Properties static EXIST: number; static ISDIR: number; static ACCES: number; static NAMETOOLONG: number; static NOENT: number; static NOTDIR: number; static NXIO: number; static NODEV: number; static ROFS: number; static TXTBSY: number; static FAULT: number; static LOOP: number; static NOSPC: number; static NOMEM: number; static MFILE: number; static NFILE: number; static BADF: number; static INVAL: number; static PIPE: number; static AGAIN: number; static INTR: number; static IO: number; static PERM: number; static NOSYS: number; static FAILED: number; } export class IOChannelError extends Error { static $gtype: GObject.GType<IOChannelError>; constructor(options: { message: string; code: number }); constructor(copy: IOChannelError); // Properties static FBIG: number; static INVAL: number; static IO: number; static ISDIR: number; static NOSPC: number; static NXIO: number; static OVERFLOW: number; static PIPE: number; static FAILED: number; } export namespace IOError { export const $gtype: GObject.GType<IOError>; } export enum IOError { NONE = 0, AGAIN = 1, INVAL = 2, UNKNOWN = 3, } export namespace IOStatus { export const $gtype: GObject.GType<IOStatus>; } export enum IOStatus { ERROR = 0, NORMAL = 1, EOF = 2, AGAIN = 3, } export class KeyFileError extends Error { static $gtype: GObject.GType<KeyFileError>; constructor(options: { message: string; code: number }); constructor(copy: KeyFileError); // Properties static UNKNOWN_ENCODING: number; static PARSE: number; static NOT_FOUND: number; static KEY_NOT_FOUND: number; static GROUP_NOT_FOUND: number; static INVALID_VALUE: number; } export namespace LogWriterOutput { export const $gtype: GObject.GType<LogWriterOutput>; } export enum LogWriterOutput { HANDLED = 1, UNHANDLED = 0, } export class MarkupError extends Error { static $gtype: GObject.GType<MarkupError>; constructor(options: { message: string; code: number }); constructor(copy: MarkupError); // Properties static BAD_UTF8: number; static EMPTY: number; static PARSE: number; static UNKNOWN_ELEMENT: number; static UNKNOWN_ATTRIBUTE: number; static INVALID_CONTENT: number; static MISSING_ATTRIBUTE: number; } export namespace NormalizeMode { export const $gtype: GObject.GType<NormalizeMode>; } export enum NormalizeMode { DEFAULT = 0, NFD = 0, DEFAULT_COMPOSE = 1, NFC = 1, ALL = 2, NFKD = 2, ALL_COMPOSE = 3, NFKC = 3, } export class NumberParserError extends Error { static $gtype: GObject.GType<NumberParserError>; constructor(options: { message: string; code: number }); constructor(copy: NumberParserError); // Properties static INVALID: number; static OUT_OF_BOUNDS: number; } export namespace OnceStatus { export const $gtype: GObject.GType<OnceStatus>; } export enum OnceStatus { NOTCALLED = 0, PROGRESS = 1, READY = 2, } export namespace OptionArg { export const $gtype: GObject.GType<OptionArg>; } export enum OptionArg { NONE = 0, STRING = 1, INT = 2, CALLBACK = 3, FILENAME = 4, STRING_ARRAY = 5, FILENAME_ARRAY = 6, DOUBLE = 7, INT64 = 8, } export class OptionError extends Error { static $gtype: GObject.GType<OptionError>; constructor(options: { message: string; code: number }); constructor(copy: OptionError); // Properties static UNKNOWN_OPTION: number; static BAD_VALUE: number; static FAILED: number; } export class RegexError extends Error { static $gtype: GObject.GType<RegexError>; constructor(options: { message: string; code: number }); constructor(copy: RegexError); // Properties static COMPILE: number; static OPTIMIZE: number; static REPLACE: number; static MATCH: number; static INTERNAL: number; static STRAY_BACKSLASH: number; static MISSING_CONTROL_CHAR: number; static UNRECOGNIZED_ESCAPE: number; static QUANTIFIERS_OUT_OF_ORDER: number; static QUANTIFIER_TOO_BIG: number; static UNTERMINATED_CHARACTER_CLASS: number; static INVALID_ESCAPE_IN_CHARACTER_CLASS: number; static RANGE_OUT_OF_ORDER: number; static NOTHING_TO_REPEAT: number; static UNRECOGNIZED_CHARACTER: number; static POSIX_NAMED_CLASS_OUTSIDE_CLASS: number; static UNMATCHED_PARENTHESIS: number; static INEXISTENT_SUBPATTERN_REFERENCE: number; static UNTERMINATED_COMMENT: number; static EXPRESSION_TOO_LARGE: number; static MEMORY_ERROR: number; static VARIABLE_LENGTH_LOOKBEHIND: number; static MALFORMED_CONDITION: number; static TOO_MANY_CONDITIONAL_BRANCHES: number; static ASSERTION_EXPECTED: number; static UNKNOWN_POSIX_CLASS_NAME: number; static POSIX_COLLATING_ELEMENTS_NOT_SUPPORTED: number; static HEX_CODE_TOO_LARGE: number; static INVALID_CONDITION: number; static SINGLE_BYTE_MATCH_IN_LOOKBEHIND: number; static INFINITE_LOOP: number; static MISSING_SUBPATTERN_NAME_TERMINATOR: number; static DUPLICATE_SUBPATTERN_NAME: number; static MALFORMED_PROPERTY: number; static UNKNOWN_PROPERTY: number; static SUBPATTERN_NAME_TOO_LONG: number; static TOO_MANY_SUBPATTERNS: number; static INVALID_OCTAL_VALUE: number; static TOO_MANY_BRANCHES_IN_DEFINE: number; static DEFINE_REPETION: number; static INCONSISTENT_NEWLINE_OPTIONS: number; static MISSING_BACK_REFERENCE: number; static INVALID_RELATIVE_REFERENCE: number; static BACKTRACKING_CONTROL_VERB_ARGUMENT_FORBIDDEN: number; static UNKNOWN_BACKTRACKING_CONTROL_VERB: number; static NUMBER_TOO_BIG: number; static MISSING_SUBPATTERN_NAME: number; static MISSING_DIGIT: number; static INVALID_DATA_CHARACTER: number; static EXTRA_SUBPATTERN_NAME: number; static BACKTRACKING_CONTROL_VERB_ARGUMENT_REQUIRED: number; static INVALID_CONTROL_CHAR: number; static MISSING_NAME: number; static NOT_SUPPORTED_IN_CLASS: number; static TOO_MANY_FORWARD_REFERENCES: number; static NAME_TOO_LONG: number; static CHARACTER_VALUE_TOO_LARGE: number; } export namespace SeekType { export const $gtype: GObject.GType<SeekType>; } export enum SeekType { CUR = 0, SET = 1, END = 2, } export class ShellError extends Error { static $gtype: GObject.GType<ShellError>; constructor(options: { message: string; code: number }); constructor(copy: ShellError); // Properties static BAD_QUOTING: number; static EMPTY_STRING: number; static FAILED: number; } export namespace SliceConfig { export const $gtype: GObject.GType<SliceConfig>; } export enum SliceConfig { ALWAYS_MALLOC = 1, BYPASS_MAGAZINES = 2, WORKING_SET_MSECS = 3, COLOR_INCREMENT = 4, CHUNK_SIZES = 5, CONTENTION_COUNTER = 6, } export class SpawnError extends Error { static $gtype: GObject.GType<SpawnError>; constructor(options: { message: string; code: number }); constructor(copy: SpawnError); // Properties static FORK: number; static READ: number; static CHDIR: number; static ACCES: number; static PERM: number; static TOO_BIG: number; static "2BIG": number; static NOEXEC: number; static NAMETOOLONG: number; static NOENT: number; static NOMEM: number; static NOTDIR: number; static LOOP: number; static TXTBUSY: number; static IO: number; static NFILE: number; static MFILE: number; static INVAL: number; static ISDIR: number; static LIBBAD: number; static FAILED: number; } export namespace TestFileType { export const $gtype: GObject.GType<TestFileType>; } export enum TestFileType { DIST = 0, BUILT = 1, } export namespace TestLogType { export const $gtype: GObject.GType<TestLogType>; } export enum TestLogType { NONE = 0, ERROR = 1, START_BINARY = 2, LIST_CASE = 3, SKIP_CASE = 4, START_CASE = 5, STOP_CASE = 6, MIN_RESULT = 7, MAX_RESULT = 8, MESSAGE = 9, START_SUITE = 10, STOP_SUITE = 11, } export namespace TestResult { export const $gtype: GObject.GType<TestResult>; } export enum TestResult { SUCCESS = 0, SKIPPED = 1, FAILURE = 2, INCOMPLETE = 3, } export class ThreadError extends Error { static $gtype: GObject.GType<ThreadError>; constructor(options: { message: string; code: number }); constructor(copy: ThreadError); // Properties static THREAD_ERROR_AGAIN: number; } export namespace TimeType { export const $gtype: GObject.GType<TimeType>; } export enum TimeType { STANDARD = 0, DAYLIGHT = 1, UNIVERSAL = 2, } export namespace TokenType { export const $gtype: GObject.GType<TokenType>; } export enum TokenType { EOF = 0, LEFT_PAREN = 40, RIGHT_PAREN = 41, LEFT_CURLY = 123, RIGHT_CURLY = 125, LEFT_BRACE = 91, RIGHT_BRACE = 93, EQUAL_SIGN = 61, COMMA = 44, NONE = 256, ERROR = 257, CHAR = 258, BINARY = 259, OCTAL = 260, INT = 261, HEX = 262, FLOAT = 263, STRING = 264, SYMBOL = 265, IDENTIFIER = 266, IDENTIFIER_NULL = 267, COMMENT_SINGLE = 268, COMMENT_MULTI = 269, } export namespace TraverseType { export const $gtype: GObject.GType<TraverseType>; } export enum TraverseType { IN_ORDER = 0, PRE_ORDER = 1, POST_ORDER = 2, LEVEL_ORDER = 3, } export namespace UnicodeBreakType { export const $gtype: GObject.GType<UnicodeBreakType>; } export enum UnicodeBreakType { MANDATORY = 0, CARRIAGE_RETURN = 1, LINE_FEED = 2, COMBINING_MARK = 3, SURROGATE = 4, ZERO_WIDTH_SPACE = 5, INSEPARABLE = 6, NON_BREAKING_GLUE = 7, CONTINGENT = 8, SPACE = 9, AFTER = 10, BEFORE = 11, BEFORE_AND_AFTER = 12, HYPHEN = 13, NON_STARTER = 14, OPEN_PUNCTUATION = 15, CLOSE_PUNCTUATION = 16, QUOTATION = 17, EXCLAMATION = 18, IDEOGRAPHIC = 19, NUMERIC = 20, INFIX_SEPARATOR = 21, SYMBOL = 22, ALPHABETIC = 23, PREFIX = 24, POSTFIX = 25, COMPLEX_CONTEXT = 26, AMBIGUOUS = 27, UNKNOWN = 28, NEXT_LINE = 29, WORD_JOINER = 30, HANGUL_L_JAMO = 31, HANGUL_V_JAMO = 32, HANGUL_T_JAMO = 33, HANGUL_LV_SYLLABLE = 34, HANGUL_LVT_SYLLABLE = 35, CLOSE_PARANTHESIS = 36, CONDITIONAL_JAPANESE_STARTER = 37, HEBREW_LETTER = 38, REGIONAL_INDICATOR = 39, EMOJI_BASE = 40, EMOJI_MODIFIER = 41, ZERO_WIDTH_JOINER = 42, } export namespace UnicodeScript { export const $gtype: GObject.GType<UnicodeScript>; } export enum UnicodeScript { INVALID_CODE = -1, COMMON = 0, INHERITED = 1, ARABIC = 2, ARMENIAN = 3, BENGALI = 4, BOPOMOFO = 5, CHEROKEE = 6, COPTIC = 7, CYRILLIC = 8, DESERET = 9, DEVANAGARI = 10, ETHIOPIC = 11, GEORGIAN = 12, GOTHIC = 13, GREEK = 14, GUJARATI = 15, GURMUKHI = 16, HAN = 17, HANGUL = 18, HEBREW = 19, HIRAGANA = 20, KANNADA = 21, KATAKANA = 22, KHMER = 23, LAO = 24, LATIN = 25, MALAYALAM = 26, MONGOLIAN = 27, MYANMAR = 28, OGHAM = 29, OLD_ITALIC = 30, ORIYA = 31, RUNIC = 32, SINHALA = 33, SYRIAC = 34, TAMIL = 35, TELUGU = 36, THAANA = 37, THAI = 38, TIBETAN = 39, CANADIAN_ABORIGINAL = 40, YI = 41, TAGALOG = 42, HANUNOO = 43, BUHID = 44, TAGBANWA = 45, BRAILLE = 46, CYPRIOT = 47, LIMBU = 48, OSMANYA = 49, SHAVIAN = 50, LINEAR_B = 51, TAI_LE = 52, UGARITIC = 53, NEW_TAI_LUE = 54, BUGINESE = 55, GLAGOLITIC = 56, TIFINAGH = 57, SYLOTI_NAGRI = 58, OLD_PERSIAN = 59, KHAROSHTHI = 60, UNKNOWN = 61, BALINESE = 62, CUNEIFORM = 63, PHOENICIAN = 64, PHAGS_PA = 65, NKO = 66, KAYAH_LI = 67, LEPCHA = 68, REJANG = 69, SUNDANESE = 70, SAURASHTRA = 71, CHAM = 72, OL_CHIKI = 73, VAI = 74, CARIAN = 75, LYCIAN = 76, LYDIAN = 77, AVESTAN = 78, BAMUM = 79, EGYPTIAN_HIEROGLYPHS = 80, IMPERIAL_ARAMAIC = 81, INSCRIPTIONAL_PAHLAVI = 82, INSCRIPTIONAL_PARTHIAN = 83, JAVANESE = 84, KAITHI = 85, LISU = 86, MEETEI_MAYEK = 87, OLD_SOUTH_ARABIAN = 88, OLD_TURKIC = 89, SAMARITAN = 90, TAI_THAM = 91, TAI_VIET = 92, BATAK = 93, BRAHMI = 94, MANDAIC = 95, CHAKMA = 96, MEROITIC_CURSIVE = 97, MEROITIC_HIEROGLYPHS = 98, MIAO = 99, SHARADA = 100, SORA_SOMPENG = 101, TAKRI = 102, BASSA_VAH = 103, CAUCASIAN_ALBANIAN = 104, DUPLOYAN = 105, ELBASAN = 106, GRANTHA = 107, KHOJKI = 108, KHUDAWADI = 109, LINEAR_A = 110, MAHAJANI = 111, MANICHAEAN = 112, MENDE_KIKAKUI = 113, MODI = 114, MRO = 115, NABATAEAN = 116, OLD_NORTH_ARABIAN = 117, OLD_PERMIC = 118, PAHAWH_HMONG = 119, PALMYRENE = 120, PAU_CIN_HAU = 121, PSALTER_PAHLAVI = 122, SIDDHAM = 123, TIRHUTA = 124, WARANG_CITI = 125, AHOM = 126, ANATOLIAN_HIEROGLYPHS = 127, HATRAN = 128, MULTANI = 129, OLD_HUNGARIAN = 130, SIGNWRITING = 131, ADLAM = 132, BHAIKSUKI = 133, MARCHEN = 134, NEWA = 135, OSAGE = 136, TANGUT = 137, MASARAM_GONDI = 138, NUSHU = 139, SOYOMBO = 140, ZANABAZAR_SQUARE = 141, DOGRA = 142, GUNJALA_GONDI = 143, HANIFI_ROHINGYA = 144, MAKASAR = 145, MEDEFAIDRIN = 146, OLD_SOGDIAN = 147, SOGDIAN = 148, ELYMAIC = 149, NANDINAGARI = 150, NYIAKENG_PUACHUE_HMONG = 151, WANCHO = 152, CHORASMIAN = 153, DIVES_AKURU = 154, KHITAN_SMALL_SCRIPT = 155, YEZIDI = 156, } export namespace UnicodeType { export const $gtype: GObject.GType<UnicodeType>; } export enum UnicodeType { CONTROL = 0, FORMAT = 1, UNASSIGNED = 2, PRIVATE_USE = 3, SURROGATE = 4, LOWERCASE_LETTER = 5, MODIFIER_LETTER = 6, OTHER_LETTER = 7, TITLECASE_LETTER = 8, UPPERCASE_LETTER = 9, SPACING_MARK = 10, ENCLOSING_MARK = 11, NON_SPACING_MARK = 12, DECIMAL_NUMBER = 13, LETTER_NUMBER = 14, OTHER_NUMBER = 15, CONNECT_PUNCTUATION = 16, DASH_PUNCTUATION = 17, CLOSE_PUNCTUATION = 18, FINAL_PUNCTUATION = 19, INITIAL_PUNCTUATION = 20, OTHER_PUNCTUATION = 21, OPEN_PUNCTUATION = 22, CURRENCY_SYMBOL = 23, MODIFIER_SYMBOL = 24, MATH_SYMBOL = 25, OTHER_SYMBOL = 26, LINE_SEPARATOR = 27, PARAGRAPH_SEPARATOR = 28, SPACE_SEPARATOR = 29, } export class UriError extends Error { static $gtype: GObject.GType<UriError>; constructor(options: { message: string; code: number }); constructor(copy: UriError); // Properties static FAILED: number; static BAD_SCHEME: number; static BAD_USER: number; static BAD_PASSWORD: number; static BAD_AUTH_PARAMS: number; static BAD_HOST: number; static BAD_PORT: number; static BAD_PATH: number; static BAD_QUERY: number; static BAD_FRAGMENT: number; } export namespace UserDirectory { export const $gtype: GObject.GType<UserDirectory>; } export enum UserDirectory { DIRECTORY_DESKTOP = 0, DIRECTORY_DOCUMENTS = 1, DIRECTORY_DOWNLOAD = 2, DIRECTORY_MUSIC = 3, DIRECTORY_PICTURES = 4, DIRECTORY_PUBLIC_SHARE = 5, DIRECTORY_TEMPLATES = 6, DIRECTORY_VIDEOS = 7, N_DIRECTORIES = 8, } export namespace VariantClass { export const $gtype: GObject.GType<VariantClass>; } export enum VariantClass { BOOLEAN = 98, BYTE = 121, INT16 = 110, UINT16 = 113, INT32 = 105, UINT32 = 117, INT64 = 120, UINT64 = 116, HANDLE = 104, DOUBLE = 100, STRING = 115, OBJECT_PATH = 111, SIGNATURE = 103, VARIANT = 118, MAYBE = 109, ARRAY = 97, TUPLE = 40, DICT_ENTRY = 123, } export class VariantParseError extends Error { static $gtype: GObject.GType<VariantParseError>; constructor(options: { message: string; code: number }); constructor(copy: VariantParseError); // Properties static FAILED: number; static BASIC_TYPE_EXPECTED: number; static CANNOT_INFER_TYPE: number; static DEFINITE_TYPE_EXPECTED: number; static INPUT_NOT_AT_END: number; static INVALID_CHARACTER: number; static INVALID_FORMAT_STRING: number; static INVALID_OBJECT_PATH: number; static INVALID_SIGNATURE: number; static INVALID_TYPE_STRING: number; static NO_COMMON_TYPE: number; static NUMBER_OUT_OF_RANGE: number; static NUMBER_TOO_BIG: number; static TYPE_ERROR: number; static UNEXPECTED_TOKEN: number; static UNKNOWN_KEYWORD: number; static UNTERMINATED_STRING_CONSTANT: number; static VALUE_EXPECTED: number; static RECURSION: number; } export namespace AsciiType { export const $gtype: GObject.GType<AsciiType>; } export enum AsciiType { ALNUM = 1, ALPHA = 2, CNTRL = 4, DIGIT = 8, GRAPH = 16, LOWER = 32, PRINT = 64, PUNCT = 128, SPACE = 256, UPPER = 512, XDIGIT = 1024, } export namespace FileSetContentsFlags { export const $gtype: GObject.GType<FileSetContentsFlags>; } export enum FileSetContentsFlags { NONE = 0, CONSISTENT = 1, DURABLE = 2, ONLY_EXISTING = 4, } export namespace FileTest { export const $gtype: GObject.GType<FileTest>; } export enum FileTest { IS_REGULAR = 1, IS_SYMLINK = 2, IS_DIR = 4, IS_EXECUTABLE = 8, EXISTS = 16, } export namespace FormatSizeFlags { export const $gtype: GObject.GType<FormatSizeFlags>; } export enum FormatSizeFlags { DEFAULT = 0, LONG_FORMAT = 1, IEC_UNITS = 2, BITS = 4, } export namespace HookFlagMask { export const $gtype: GObject.GType<HookFlagMask>; } export enum HookFlagMask { ACTIVE = 1, IN_CALL = 2, MASK = 15, } export namespace IOCondition { export const $gtype: GObject.GType<IOCondition>; } export enum IOCondition { IN = 1, OUT = 4, PRI = 2, ERR = 8, HUP = 16, NVAL = 32, } export namespace IOFlags { export const $gtype: GObject.GType<IOFlags>; } export enum IOFlags { APPEND = 1, NONBLOCK = 2, IS_READABLE = 4, IS_WRITABLE = 8, IS_WRITEABLE = 8, IS_SEEKABLE = 16, MASK = 31, GET_MASK = 31, SET_MASK = 3, } export namespace KeyFileFlags { export const $gtype: GObject.GType<KeyFileFlags>; } export enum KeyFileFlags { NONE = 0, KEEP_COMMENTS = 1, KEEP_TRANSLATIONS = 2, } export namespace LogLevelFlags { export const $gtype: GObject.GType<LogLevelFlags>; } export enum LogLevelFlags { FLAG_RECURSION = 1, FLAG_FATAL = 2, LEVEL_ERROR = 4, LEVEL_CRITICAL = 8, LEVEL_WARNING = 16, LEVEL_MESSAGE = 32, LEVEL_INFO = 64, LEVEL_DEBUG = 128, LEVEL_MASK = -4, } export namespace MarkupCollectType { export const $gtype: GObject.GType<MarkupCollectType>; } export enum MarkupCollectType { INVALID = 0, STRING = 1, STRDUP = 2, BOOLEAN = 3, TRISTATE = 4, OPTIONAL = 65536, } export namespace MarkupParseFlags { export const $gtype: GObject.GType<MarkupParseFlags>; } export enum MarkupParseFlags { DO_NOT_USE_THIS_UNSUPPORTED_FLAG = 1, TREAT_CDATA_AS_TEXT = 2, PREFIX_ERROR_POSITION = 4, IGNORE_QUALIFIED = 8, } export namespace OptionFlags { export const $gtype: GObject.GType<OptionFlags>; } export enum OptionFlags { NONE = 0, HIDDEN = 1, IN_MAIN = 2, REVERSE = 4, NO_ARG = 8, FILENAME = 16, OPTIONAL_ARG = 32, NOALIAS = 64, } export namespace RegexCompileFlags { export const $gtype: GObject.GType<RegexCompileFlags>; } export enum RegexCompileFlags { CASELESS = 1, MULTILINE = 2, DOTALL = 4, EXTENDED = 8, ANCHORED = 16, DOLLAR_ENDONLY = 32, UNGREEDY = 512, RAW = 2048, NO_AUTO_CAPTURE = 4096, OPTIMIZE = 8192, FIRSTLINE = 262144, DUPNAMES = 524288, NEWLINE_CR = 1048576, NEWLINE_LF = 2097152, NEWLINE_CRLF = 3145728, NEWLINE_ANYCRLF = 5242880, BSR_ANYCRLF = 8388608, JAVASCRIPT_COMPAT = 33554432, } export namespace RegexMatchFlags { export const $gtype: GObject.GType<RegexMatchFlags>; } export enum RegexMatchFlags { ANCHORED = 16, NOTBOL = 128, NOTEOL = 256, NOTEMPTY = 1024, PARTIAL = 32768, NEWLINE_CR = 1048576, NEWLINE_LF = 2097152, NEWLINE_CRLF = 3145728, NEWLINE_ANY = 4194304, NEWLINE_ANYCRLF = 5242880, BSR_ANYCRLF = 8388608, BSR_ANY = 16777216, PARTIAL_SOFT = 32768, PARTIAL_HARD = 134217728, NOTEMPTY_ATSTART = 268435456, } export namespace SpawnFlags { export const $gtype: GObject.GType<SpawnFlags>; } export enum SpawnFlags { DEFAULT = 0, LEAVE_DESCRIPTORS_OPEN = 1, DO_NOT_REAP_CHILD = 2, SEARCH_PATH = 4, STDOUT_TO_DEV_NULL = 8, STDERR_TO_DEV_NULL = 16, CHILD_INHERITS_STDIN = 32, FILE_AND_ARGV_ZERO = 64, SEARCH_PATH_FROM_ENVP = 128, CLOEXEC_PIPES = 256, } export namespace TestSubprocessFlags { export const $gtype: GObject.GType<TestSubprocessFlags>; } export enum TestSubprocessFlags { STDIN = 1, STDOUT = 2, STDERR = 4, } export namespace TestTrapFlags { export const $gtype: GObject.GType<TestTrapFlags>; } export enum TestTrapFlags { SILENCE_STDOUT = 128, SILENCE_STDERR = 256, INHERIT_STDIN = 512, } export namespace TraverseFlags { export const $gtype: GObject.GType<TraverseFlags>; } export enum TraverseFlags { LEAVES = 1, NON_LEAVES = 2, ALL = 3, MASK = 3, LEAFS = 1, NON_LEAFS = 2, } export namespace UriFlags { export const $gtype: GObject.GType<UriFlags>; } export enum UriFlags { NONE = 0, PARSE_RELAXED = 1, HAS_PASSWORD = 2, HAS_AUTH_PARAMS = 4, ENCODED = 8, NON_DNS = 16, ENCODED_QUERY = 32, ENCODED_PATH = 64, ENCODED_FRAGMENT = 128, } export namespace UriHideFlags { export const $gtype: GObject.GType<UriHideFlags>; } export enum UriHideFlags { NONE = 0, USERINFO = 1, PASSWORD = 2, AUTH_PARAMS = 4, QUERY = 8, FRAGMENT = 16, } export namespace UriParamsFlags { export const $gtype: GObject.GType<UriParamsFlags>; } export enum UriParamsFlags { NONE = 0, CASE_INSENSITIVE = 1, WWW_FORM = 2, PARSE_RELAXED = 4, } export class Array { static $gtype: GObject.GType<Array>; constructor( properties?: Partial<{ data?: string; len?: number; }> ); constructor(copy: Array); // Fields data: string; len: number; } export class AsyncQueue { static $gtype: GObject.GType<AsyncQueue>; constructor(copy: AsyncQueue); // Members length(): number; length_unlocked(): number; lock(): void; pop(): any | null; pop_unlocked(): any | null; push(data?: any | null): void; push_front(item?: any | null): void; push_front_unlocked(item?: any | null): void; push_unlocked(data?: any | null): void; ref_unlocked(): void; remove(item?: any | null): boolean; remove_unlocked(item?: any | null): boolean; timed_pop(end_time: TimeVal): any | null; timed_pop_unlocked(end_time: TimeVal): any | null; timeout_pop(timeout: number): any | null; timeout_pop_unlocked(timeout: number): any | null; try_pop(): any | null; try_pop_unlocked(): any | null; unlock(): void; unref(): void; unref_and_unlock(): void; } export class BookmarkFile { static $gtype: GObject.GType<BookmarkFile>; constructor(copy: BookmarkFile); // Members add_application(uri: string, name?: string | null, exec?: string | null): void; add_group(uri: string, group: string): void; free(): void; get_added(uri: string): number; get_added_date_time(uri: string): DateTime; get_app_info(uri: string, name: string): [boolean, string | null, number | null, number | null]; get_application_info(uri: string, name: string): [boolean, string | null, number | null, DateTime | null]; get_applications(uri: string): string[]; get_description(uri: string): string; get_groups(uri: string): string[]; get_icon(uri: string): [boolean, string | null, string | null]; get_is_private(uri: string): boolean; get_mime_type(uri: string): string; get_modified(uri: string): number; get_modified_date_time(uri: string): DateTime; get_size(): number; get_title(uri?: string | null): string; get_uris(): string[]; get_visited(uri: string): number; get_visited_date_time(uri: string): DateTime; has_application(uri: string, name: string): boolean; has_group(uri: string, group: string): boolean; has_item(uri: string): boolean; load_from_data(data: Uint8Array | string): boolean; load_from_data_dirs(file: string): [boolean, string | null]; load_from_file(filename: string): boolean; move_item(old_uri: string, new_uri?: string | null): boolean; remove_application(uri: string, name: string): boolean; remove_group(uri: string, group: string): boolean; remove_item(uri: string): boolean; set_added(uri: string, added: number): void; set_added_date_time(uri: string, added: DateTime): void; set_app_info(uri: string, name: string, exec: string, count: number, stamp: number): boolean; set_application_info(uri: string, name: string, exec: string, count: number, stamp?: DateTime | null): boolean; set_description(uri: string | null, description: string): void; set_groups(uri: string, groups?: string[] | null): void; set_icon(uri: string, href: string | null, mime_type: string): void; set_is_private(uri: string, is_private: boolean): void; set_mime_type(uri: string, mime_type: string): void; set_modified(uri: string, modified: number): void; set_modified_date_time(uri: string, modified: DateTime): void; set_title(uri: string | null, title: string): void; set_visited(uri: string, visited: number): void; set_visited_date_time(uri: string, visited: DateTime): void; to_data(): Uint8Array; to_file(filename: string): boolean; static error_quark(): Quark; } export class ByteArray { static $gtype: GObject.GType<ByteArray>; constructor( properties?: Partial<{ data?: number; len?: number; }> ); constructor(copy: ByteArray); // Fields data: number; len: number; // Members static free(array: Uint8Array | string, free_segment: boolean): number; static free_to_bytes(array: Uint8Array | string): Bytes; static new(): Uint8Array; static new_take(data: Uint8Array | string): Uint8Array; static steal(array: Uint8Array | string): [number, number | null]; static unref(array: Uint8Array | string): void; } export class Bytes { static $gtype: GObject.GType<Bytes>; constructor(data?: Uint8Array | null); constructor(copy: Bytes); // Constructors static ["new"](data?: Uint8Array | null): Bytes; static new_take(data?: Uint8Array | null): Bytes; // Members compare(bytes2: Bytes | Uint8Array): number; equal(bytes2: Bytes | Uint8Array): boolean; get_data(): Uint8Array | null; get_size(): number; hash(): number; new_from_bytes(offset: number, length: number): Bytes; ref(): Bytes; unref(): void; unref_to_array(): Uint8Array; unref_to_data(): Uint8Array; toArray(): Uint8Array; } export class Checksum { static $gtype: GObject.GType<Checksum>; constructor(checksum_type: ChecksumType); constructor(copy: Checksum); // Constructors static ["new"](checksum_type: ChecksumType): Checksum; // Members copy(): Checksum; free(): void; get_string(): string; reset(): void; update(data: Uint8Array | string): void; static type_get_length(checksum_type: ChecksumType): number; } export class Cond { static $gtype: GObject.GType<Cond>; constructor(copy: Cond); // Fields p: any; i: number[]; // Members broadcast(): void; clear(): void; init(): void; signal(): void; wait(mutex: Mutex): void; wait_until(mutex: Mutex, end_time: number): boolean; } export class Data { static $gtype: GObject.GType<Data>; constructor(copy: Data); } export class Date { static $gtype: GObject.GType<Date>; constructor(); constructor( properties?: Partial<{ julian_days?: number; julian?: number; dmy?: number; day?: number; month?: number; year?: number; }> ); constructor(copy: Date); // Fields julian_days: number; julian: number; dmy: number; day: number; month: number; year: number; // Constructors static ["new"](): Date; static new_dmy(day: DateDay, month: DateMonth, year: DateYear): Date; static new_julian(julian_day: number): Date; // Members add_days(n_days: number): void; add_months(n_months: number): void; add_years(n_years: number): void; clamp(min_date: Date, max_date: Date): void; clear(n_dates: number): void; compare(rhs: Date): number; copy(): Date; days_between(date2: Date): number; free(): void; get_day(): DateDay; get_day_of_year(): number; get_iso8601_week_of_year(): number; get_julian(): number; get_monday_week_of_year(): number; get_month(): DateMonth; get_sunday_week_of_year(): number; get_weekday(): DateWeekday; get_year(): DateYear; is_first_of_month(): boolean; is_last_of_month(): boolean; order(date2: Date): void; set_day(day: DateDay): void; set_dmy(day: DateDay, month: DateMonth, y: DateYear): void; set_julian(julian_date: number): void; set_month(month: DateMonth): void; set_parse(str: string): void; set_time(time_: Time): void; set_time_t(timet: number): void; set_time_val(timeval: TimeVal): void; set_year(year: DateYear): void; subtract_days(n_days: number): void; subtract_months(n_months: number): void; subtract_years(n_years: number): void; to_struct_tm(tm: any): void; valid(): boolean; static get_days_in_month(month: DateMonth, year: DateYear): number; static get_monday_weeks_in_year(year: DateYear): number; static get_sunday_weeks_in_year(year: DateYear): number; static is_leap_year(year: DateYear): boolean; static strftime(s: string, slen: number, format: string, date: Date): number; static valid_day(day: DateDay): boolean; static valid_dmy(day: DateDay, month: DateMonth, year: DateYear): boolean; static valid_julian(julian_date: number): boolean; static valid_month(month: DateMonth): boolean; static valid_weekday(weekday: DateWeekday): boolean; static valid_year(year: DateYear): boolean; } export class DateTime { static $gtype: GObject.GType<DateTime>; constructor(tz: TimeZone, year: number, month: number, day: number, hour: number, minute: number, seconds: number); constructor(copy: DateTime); // Constructors static ["new"]( tz: TimeZone, year: number, month: number, day: number, hour: number, minute: number, seconds: number ): DateTime; static new_from_iso8601(text: string, default_tz?: TimeZone | null): DateTime; static new_from_timeval_local(tv: TimeVal): DateTime; static new_from_timeval_utc(tv: TimeVal): DateTime; static new_from_unix_local(t: number): DateTime; static new_from_unix_utc(t: number): DateTime; static new_local(year: number, month: number, day: number, hour: number, minute: number, seconds: number): DateTime; static new_now(tz: TimeZone): DateTime; static new_now_local(): DateTime; static new_now_utc(): DateTime; static new_utc(year: number, month: number, day: number, hour: number, minute: number, seconds: number): DateTime; // Members add(timespan: TimeSpan): DateTime | null; add_days(days: number): DateTime | null; add_full( years: number, months: number, days: number, hours: number, minutes: number, seconds: number ): DateTime | null; add_hours(hours: number): DateTime | null; add_minutes(minutes: number): DateTime | null; add_months(months: number): DateTime | null; add_seconds(seconds: number): DateTime | null; add_weeks(weeks: number): DateTime | null; add_years(years: number): DateTime | null; difference(begin: DateTime): TimeSpan; format(format: string): string | null; format_iso8601(): string | null; get_day_of_month(): number; get_day_of_week(): number; get_day_of_year(): number; get_hour(): number; get_microsecond(): number; get_minute(): number; get_month(): number; get_second(): number; get_seconds(): number; get_timezone(): TimeZone; get_timezone_abbreviation(): string; get_utc_offset(): TimeSpan; get_week_numbering_year(): number; get_week_of_year(): number; get_year(): number; get_ymd(): [number | null, number | null, number | null]; is_daylight_savings(): boolean; ref(): DateTime; to_local(): DateTime | null; to_timeval(tv: TimeVal): boolean; to_timezone(tz: TimeZone): DateTime | null; to_unix(): number; to_utc(): DateTime | null; unref(): void; static compare(dt1: any, dt2: any): number; static equal(dt1: any, dt2: any): boolean; static hash(datetime: any): number; } export class DebugKey { static $gtype: GObject.GType<DebugKey>; constructor( properties?: Partial<{ key?: string; value?: number; }> ); constructor(copy: DebugKey); // Fields key: string; value: number; } export class Dir { static $gtype: GObject.GType<Dir>; constructor(copy: Dir); // Members close(): void; read_name(): string; rewind(): void; static make_tmp(tmpl?: string | null): string; } export class Error { static $gtype: GObject.GType<Error>; constructor(options: { message: string; code: number }); constructor(copy: Error); // Fields domain: Quark; code: number; message: string; // Constructors static new_literal(domain: Quark, code: number, message: string): Error; // Members copy(): Error; free(): void; matches(domain: Quark, code: number): boolean; } export class HashTable<A = string, B = any> { [key: string]: B; static $gtype: GObject.GType<HashTable>; constructor(copy: HashTable); // Members static add(hash_table: HashTable<any, any>, key?: any | null): boolean; static contains(hash_table: HashTable<any, any>, key?: any | null): boolean; static destroy(hash_table: HashTable<any, any>): void; static insert(hash_table: HashTable<any, any>, key?: any | null, value?: any | null): boolean; static lookup(hash_table: HashTable<any, any>, key?: any | null): any | null; static lookup_extended(hash_table: HashTable<any, any>, lookup_key?: any | null): [boolean, any | null, any | null]; static remove(hash_table: HashTable<any, any>, key?: any | null): boolean; static remove_all(hash_table: HashTable<any, any>): void; static replace(hash_table: HashTable<any, any>, key?: any | null, value?: any | null): boolean; static size(hash_table: HashTable<any, any>): number; static steal(hash_table: HashTable<any, any>, key?: any | null): boolean; static steal_all(hash_table: HashTable<any, any>): void; static steal_extended(hash_table: HashTable<any, any>, lookup_key?: any | null): [boolean, any | null, any | null]; static unref(hash_table: HashTable<any, any>): void; } export class HashTableIter { static $gtype: GObject.GType<HashTableIter>; constructor( properties?: Partial<{ dummy1?: any; dummy2?: any; dummy3?: any; dummy4?: number; dummy5?: boolean; dummy6?: any; }> ); constructor(copy: HashTableIter); // Fields dummy1: any; dummy2: any; dummy3: any; dummy4: number; dummy5: boolean; dummy6: any; // Members init(hash_table: HashTable<any, any>): void; next(): [boolean, any | null, any | null]; remove(): void; replace(value?: any | null): void; steal(): void; } export class Hmac { static $gtype: GObject.GType<Hmac>; constructor(copy: Hmac); // Members get_digest(buffer: Uint8Array | string): void; get_string(): string; unref(): void; update(data: Uint8Array | string): void; } export class Hook { static $gtype: GObject.GType<Hook>; constructor(copy: Hook); // Fields data: any; next: Hook; prev: Hook; ref_count: number; hook_id: number; flags: number; func: any; // Members compare_ids(sibling: Hook): number; static destroy(hook_list: HookList, hook_id: number): boolean; static destroy_link(hook_list: HookList, hook: Hook): void; static free(hook_list: HookList, hook: Hook): void; static insert_before(hook_list: HookList, sibling: Hook | null, hook: Hook): void; static prepend(hook_list: HookList, hook: Hook): void; static unref(hook_list: HookList, hook: Hook): void; } export class HookList { static $gtype: GObject.GType<HookList>; constructor(copy: HookList); // Fields seq_id: number; hook_size: number; is_setup: number; hooks: Hook; dummy3: any; finalize_hook: HookFinalizeFunc; dummy: any[]; // Members clear(): void; init(hook_size: number): void; invoke(may_recurse: boolean): void; invoke_check(may_recurse: boolean): void; } export class IOChannel { static $gtype: GObject.GType<IOChannel>; constructor(filename: string, mode: string); constructor(copy: IOChannel); // Fields ref_count: number; funcs: IOFuncs; encoding: string; line_term: string; line_term_len: number; buf_size: number; read_buf: String; encoded_read_buf: String; write_buf: String; partial_write_buf: number[]; use_buffer: number; do_encode: number; close_on_unref: number; is_readable: number; is_writeable: number; is_seekable: number; reserved1: any; reserved2: any; // Constructors static new_file(filename: string, mode: string): IOChannel; static unix_new(fd: number): IOChannel; // Members close(): void; flush(): IOStatus; get_buffer_condition(): IOCondition; get_buffer_size(): number; get_buffered(): boolean; get_close_on_unref(): boolean; get_encoding(): string; get_flags(): IOFlags; get_line_term(length: number): string; init(): void; read(buf: string, count: number, bytes_read: number): IOError; read_chars(): [IOStatus, Uint8Array, number | null]; read_line(): [IOStatus, string, number | null, number | null]; read_line_string(buffer: String, terminator_pos?: number | null): IOStatus; read_to_end(): [IOStatus, Uint8Array]; read_unichar(): [IOStatus, number]; ref(): IOChannel; seek(offset: number, type: SeekType): IOError; seek_position(offset: number, type: SeekType): IOStatus; set_buffer_size(size: number): void; set_buffered(buffered: boolean): void; set_close_on_unref(do_close: boolean): void; set_encoding(encoding?: string | null): IOStatus; set_flags(flags: IOFlags): IOStatus; set_line_term(line_term: string | null, length: number): void; shutdown(flush: boolean): IOStatus; unix_get_fd(): number; unref(): void; write(buf: string, count: number, bytes_written: number): IOError; write_chars(buf: Uint8Array | string, count: number): [IOStatus, number]; write_unichar(thechar: number): IOStatus; static error_from_errno(en: number): IOChannelError; static error_quark(): Quark; } export class IOFuncs { static $gtype: GObject.GType<IOFuncs>; constructor(copy: IOFuncs); } export class KeyFile { static $gtype: GObject.GType<KeyFile>; constructor(); constructor(copy: KeyFile); // Constructors static ["new"](): KeyFile; // Members get_boolean(group_name: string, key: string): boolean; get_boolean_list(group_name: string, key: string): boolean[]; get_comment(group_name: string | null, key: string): string; get_double(group_name: string, key: string): number; get_double_list(group_name: string, key: string): number[]; get_groups(): [string[], number | null]; get_int64(group_name: string, key: string): number; get_integer(group_name: string, key: string): number; get_integer_list(group_name: string, key: string): number[]; get_keys(group_name: string): [string[], number | null]; get_locale_for_key(group_name: string, key: string, locale?: string | null): string | null; get_locale_string(group_name: string, key: string, locale?: string | null): string; get_locale_string_list(group_name: string, key: string, locale?: string | null): string[]; get_start_group(): string; get_string(group_name: string, key: string): string; get_string_list(group_name: string, key: string): string[]; get_uint64(group_name: string, key: string): number; get_value(group_name: string, key: string): string; has_group(group_name: string): boolean; load_from_bytes(bytes: Bytes | Uint8Array, flags: KeyFileFlags): boolean; load_from_data(data: string, length: number, flags: KeyFileFlags): boolean; load_from_data_dirs(file: string, flags: KeyFileFlags): [boolean, string | null]; load_from_dirs(file: string, search_dirs: string[], flags: KeyFileFlags): [boolean, string | null]; load_from_file(file: string, flags: KeyFileFlags): boolean; remove_comment(group_name?: string | null, key?: string | null): boolean; remove_group(group_name: string): boolean; remove_key(group_name: string, key: string): boolean; save_to_file(filename: string): boolean; set_boolean(group_name: string, key: string, value: boolean): void; set_boolean_list(group_name: string, key: string, list: boolean[]): void; set_comment(group_name: string | null, key: string | null, comment: string): boolean; set_double(group_name: string, key: string, value: number): void; set_double_list(group_name: string, key: string, list: number[]): void; set_int64(group_name: string, key: string, value: number): void; set_integer(group_name: string, key: string, value: number): void; set_integer_list(group_name: string, key: string, list: number[]): void; set_list_separator(separator: number): void; set_locale_string(group_name: string, key: string, locale: string, string: string): void; set_locale_string_list(group_name: string, key: string, locale: string, list: string[]): void; set_string(group_name: string, key: string, string: string): void; set_string_list(group_name: string, key: string, list: string[]): void; set_uint64(group_name: string, key: string, value: number): void; set_value(group_name: string, key: string, value: string): void; to_data(): [string, number | null]; unref(): void; static error_quark(): Quark; } export class List { static $gtype: GObject.GType<List>; constructor(copy: List); // Fields data: any; next: any[]; prev: any[]; } export class LogField { static $gtype: GObject.GType<LogField>; constructor( properties?: Partial<{ key?: string; value?: any; length?: number; }> ); constructor(copy: LogField); // Fields key: string; value: any; length: number; } export class MainContext { static $gtype: GObject.GType<MainContext>; constructor(); constructor(copy: MainContext); // Constructors static ["new"](): MainContext; // Members acquire(): boolean; add_poll(fd: PollFD, priority: number): void; check(max_priority: number, fds: PollFD[]): boolean; dispatch(): void; find_source_by_funcs_user_data(funcs: SourceFuncs, user_data?: any | null): Source; find_source_by_id(source_id: number): Source; find_source_by_user_data(user_data?: any | null): Source; invoke_full(priority: number, _function: SourceFunc, notify?: DestroyNotify | null): void; is_owner(): boolean; iteration(may_block: boolean): boolean; pending(): boolean; pop_thread_default(): void; prepare(): [boolean, number | null]; push_thread_default(): void; query(max_priority: number): [number, number, PollFD[]]; ref(): MainContext; release(): void; remove_poll(fd: PollFD): void; unref(): void; wait(cond: Cond, mutex: Mutex): boolean; wakeup(): void; static default(): MainContext; static get_thread_default(): MainContext; static ref_thread_default(): MainContext; } export class MainLoop { static $gtype: GObject.GType<MainLoop>; constructor(context: MainContext | null, is_running: boolean); constructor(copy: MainLoop); // Constructors static ["new"](context: MainContext | null, is_running: boolean): MainLoop; // Members get_context(): MainContext; is_running(): boolean; quit(): void; ref(): MainLoop; run(): void; unref(): void; } export class MappedFile { static $gtype: GObject.GType<MappedFile>; constructor(filename: string, writable: boolean); constructor(copy: MappedFile); // Constructors static ["new"](filename: string, writable: boolean): MappedFile; static new_from_fd(fd: number, writable: boolean): MappedFile; // Members free(): void; get_bytes(): Bytes; get_contents(): string; get_length(): number; ref(): MappedFile; unref(): void; } export class MarkupParseContext { static $gtype: GObject.GType<MarkupParseContext>; constructor(parser: MarkupParser, flags: MarkupParseFlags, user_data?: any | null); constructor(copy: MarkupParseContext); // Constructors static ["new"](parser: MarkupParser, flags: MarkupParseFlags, user_data?: any | null): MarkupParseContext; // Members end_parse(): boolean; free(): void; get_element(): string; get_position(): [number | null, number | null]; get_user_data(): any | null; parse(text: string, text_len: number): boolean; pop(): any | null; push(parser: MarkupParser, user_data?: any | null): void; ref(): MarkupParseContext; unref(): void; } export class MarkupParser { static $gtype: GObject.GType<MarkupParser>; constructor(copy: MarkupParser); } export class MatchInfo { static $gtype: GObject.GType<MatchInfo>; constructor(copy: MatchInfo); // Members expand_references(string_to_expand: string): string | null; fetch(match_num: number): string | null; fetch_all(): string[]; fetch_named(name: string): string | null; fetch_named_pos(name: string): [boolean, number | null, number | null]; fetch_pos(match_num: number): [boolean, number | null, number | null]; free(): void; get_match_count(): number; get_regex(): Regex; get_string(): string; is_partial_match(): boolean; matches(): boolean; next(): boolean; ref(): MatchInfo; unref(): void; } export class MemVTable { static $gtype: GObject.GType<MemVTable>; constructor(copy: MemVTable); } export class Node { static $gtype: GObject.GType<Node>; constructor(copy: Node); // Fields data: any; next: Node; prev: Node; children: Node; // Members child_index(data?: any | null): number; child_position(child: Node): number; depth(): number; destroy(): void; is_ancestor(descendant: Node): boolean; max_height(): number; n_children(): number; n_nodes(flags: TraverseFlags): number; reverse_children(): void; unlink(): void; } export class Once { static $gtype: GObject.GType<Once>; constructor(copy: Once); // Fields status: OnceStatus; retval: any; // Members static init_enter(location: any): boolean; static init_leave(location: any, result: number): void; } export class OptionContext { static $gtype: GObject.GType<OptionContext>; constructor(copy: OptionContext); // Members add_group(group: OptionGroup): void; add_main_entries(entries: OptionEntry[], translation_domain?: string | null): void; free(): void; get_description(): string; get_help(main_help: boolean, group?: OptionGroup | null): string; get_help_enabled(): boolean; get_ignore_unknown_options(): boolean; get_main_group(): OptionGroup; get_strict_posix(): boolean; get_summary(): string; parse(argv?: string[]): [boolean, string[]]; parse_strv(_arguments?: string[]): [boolean, string[]]; set_description(description?: string | null): void; set_help_enabled(help_enabled: boolean): void; set_ignore_unknown_options(ignore_unknown: boolean): void; set_main_group(group: OptionGroup): void; set_strict_posix(strict_posix: boolean): void; set_summary(summary?: string | null): void; set_translate_func(func?: TranslateFunc | null, destroy_notify?: DestroyNotify | null): void; set_translation_domain(domain: string): void; } export class OptionEntry { static $gtype: GObject.GType<OptionEntry>; constructor(copy: OptionEntry); // Fields long_name: string; short_name: number; flags: number; arg: OptionArg; arg_data: any; description: string; arg_description: string; } export class OptionGroup { static $gtype: GObject.GType<OptionGroup>; constructor( name: string, description: string, help_description: string, user_data?: any | null, destroy?: DestroyNotify | null ); constructor(copy: OptionGroup); // Constructors static ["new"]( name: string, description: string, help_description: string, user_data?: any | null, destroy?: DestroyNotify | null ): OptionGroup; // Members add_entries(entries: OptionEntry[]): void; free(): void; ref(): OptionGroup; set_translate_func(func?: TranslateFunc | null, destroy_notify?: DestroyNotify | null): void; set_translation_domain(domain: string): void; unref(): void; } export class PatternSpec { static $gtype: GObject.GType<PatternSpec>; constructor(copy: PatternSpec); // Members equal(pspec2: PatternSpec): boolean; free(): void; } export class PollFD { static $gtype: GObject.GType<PollFD>; constructor( properties?: Partial<{ fd?: number; events?: number; revents?: number; }> ); constructor(copy: PollFD); // Fields fd: number; events: number; revents: number; } export class Private { static $gtype: GObject.GType<Private>; constructor(copy: Private); // Fields p: any; notify: DestroyNotify; future: any[]; // Members get(): any | null; replace(value?: any | null): void; set(value?: any | null): void; } export class PtrArray { static $gtype: GObject.GType<PtrArray>; constructor( properties?: Partial<{ pdata?: any; len?: number; }> ); constructor(copy: PtrArray); // Fields pdata: any; len: number; } export class Queue { static $gtype: GObject.GType<Queue>; constructor(copy: Queue); // Fields head: any[]; tail: any[]; length: number; // Members clear(): void; clear_full(free_func?: DestroyNotify | null): void; free(): void; free_full(): void; get_length(): number; index(data?: any | null): number; init(): void; is_empty(): boolean; peek_head(): any | null; peek_nth(n: number): any | null; peek_tail(): any | null; pop_head(): any | null; pop_nth(n: number): any | null; pop_tail(): any | null; push_head(data?: any | null): void; push_nth(data: any | null, n: number): void; push_tail(data?: any | null): void; remove(data?: any | null): boolean; remove_all(data?: any | null): number; reverse(): void; } export class RWLock { static $gtype: GObject.GType<RWLock>; constructor(copy: RWLock); // Fields p: any; i: number[]; // Members clear(): void; init(): void; reader_lock(): void; reader_trylock(): boolean; reader_unlock(): void; writer_lock(): void; writer_trylock(): boolean; writer_unlock(): void; } export class Rand { static $gtype: GObject.GType<Rand>; constructor(copy: Rand); // Members double(): number; double_range(begin: number, end: number): number; free(): void; int(): number; int_range(begin: number, end: number): number; set_seed(seed: number): void; set_seed_array(seed: number, seed_length: number): void; } export class RecMutex { static $gtype: GObject.GType<RecMutex>; constructor(copy: RecMutex); // Fields p: any; i: number[]; // Members clear(): void; init(): void; lock(): void; trylock(): boolean; unlock(): void; } export class Regex { static $gtype: GObject.GType<Regex>; constructor(pattern: string, compile_options: RegexCompileFlags, match_options: RegexMatchFlags); constructor(copy: Regex); // Constructors static ["new"](pattern: string, compile_options: RegexCompileFlags, match_options: RegexMatchFlags): Regex; // Members get_capture_count(): number; get_compile_flags(): RegexCompileFlags; get_has_cr_or_lf(): boolean; get_match_flags(): RegexMatchFlags; get_max_backref(): number; get_max_lookbehind(): number; get_pattern(): string; get_string_number(name: string): number; match(string: string, match_options: RegexMatchFlags): [boolean, MatchInfo | null]; match_all(string: string, match_options: RegexMatchFlags): [boolean, MatchInfo | null]; match_all_full( string: string[], start_position: number, match_options: RegexMatchFlags ): [boolean, MatchInfo | null]; match_full(string: string[], start_position: number, match_options: RegexMatchFlags): [boolean, MatchInfo | null]; ref(): Regex; replace(string: string[], start_position: number, replacement: string, match_options: RegexMatchFlags): string; replace_literal( string: string[], start_position: number, replacement: string, match_options: RegexMatchFlags ): string; split(string: string, match_options: RegexMatchFlags): string[]; split_full(string: string[], start_position: number, match_options: RegexMatchFlags, max_tokens: number): string[]; unref(): void; static check_replacement(replacement: string): [boolean, boolean | null]; static error_quark(): Quark; static escape_nul(string: string, length: number): string; static escape_string(string: string[]): string; static match_simple( pattern: string, string: string, compile_options: RegexCompileFlags, match_options: RegexMatchFlags ): boolean; static split_simple( pattern: string, string: string, compile_options: RegexCompileFlags, match_options: RegexMatchFlags ): string[]; } export class SList { static $gtype: GObject.GType<SList>; constructor(copy: SList); // Fields data: any; next: any[]; } export class Scanner { static $gtype: GObject.GType<Scanner>; constructor(copy: Scanner); // Fields user_data: any; max_parse_errors: number; parse_errors: number; input_name: string; qdata: Data; config: ScannerConfig; token: TokenType; value: TokenValue; line: number; position: number; next_token: TokenType; next_value: TokenValue; next_line: number; next_position: number; symbol_table: HashTable<any, any>; input_fd: number; text: string; text_end: string; buffer: string; scope_id: number; msg_handler: ScannerMsgFunc; // Members cur_line(): number; cur_position(): number; cur_token(): TokenType; destroy(): void; eof(): boolean; get_next_token(): TokenType; input_file(input_fd: number): void; input_text(text: string, text_len: number): void; lookup_symbol(symbol: string): any | null; peek_next_token(): TokenType; scope_add_symbol(scope_id: number, symbol: string, value?: any | null): void; scope_lookup_symbol(scope_id: number, symbol: string): any | null; scope_remove_symbol(scope_id: number, symbol: string): void; set_scope(scope_id: number): number; sync_file_offset(): void; unexp_token( expected_token: TokenType, identifier_spec: string, symbol_spec: string, symbol_name: string, message: string, is_error: number ): void; } export class ScannerConfig { static $gtype: GObject.GType<ScannerConfig>; constructor( properties?: Partial<{ cset_skip_characters?: string; cset_identifier_first?: string; cset_identifier_nth?: string; cpair_comment_single?: string; case_sensitive?: number; skip_comment_multi?: number; skip_comment_single?: number; scan_comment_multi?: number; scan_identifier?: number; scan_identifier_1char?: number; scan_identifier_NULL?: number; scan_symbols?: number; scan_binary?: number; scan_octal?: number; scan_float?: number; scan_hex?: number; scan_hex_dollar?: number; scan_string_sq?: number; scan_string_dq?: number; numbers_2_int?: number; int_2_float?: number; identifier_2_string?: number; char_2_token?: number; symbol_2_token?: number; scope_0_fallback?: number; store_int64?: number; padding_dummy?: number; }> ); constructor(copy: ScannerConfig); // Fields cset_skip_characters: string; cset_identifier_first: string; cset_identifier_nth: string; cpair_comment_single: string; case_sensitive: number; skip_comment_multi: number; skip_comment_single: number; scan_comment_multi: number; scan_identifier: number; scan_identifier_1char: number; scan_identifier_NULL: number; scan_symbols: number; scan_binary: number; scan_octal: number; scan_float: number; scan_hex: number; scan_hex_dollar: number; scan_string_sq: number; scan_string_dq: number; numbers_2_int: number; int_2_float: number; identifier_2_string: number; char_2_token: number; symbol_2_token: number; scope_0_fallback: number; store_int64: number; padding_dummy: number; } export class Sequence { static $gtype: GObject.GType<Sequence>; constructor(copy: Sequence); // Members append(data?: any | null): SequenceIter; free(): void; get_begin_iter(): SequenceIter; get_end_iter(): SequenceIter; get_iter_at_pos(pos: number): SequenceIter; get_length(): number; is_empty(): boolean; prepend(data?: any | null): SequenceIter; static get(iter: SequenceIter): any | null; static insert_before(iter: SequenceIter, data?: any | null): SequenceIter; static move(src: SequenceIter, dest: SequenceIter): void; static move_range(dest: SequenceIter, begin: SequenceIter, end: SequenceIter): void; static range_get_midpoint(begin: SequenceIter, end: SequenceIter): SequenceIter; static remove(iter: SequenceIter): void; static remove_range(begin: SequenceIter, end: SequenceIter): void; static set(iter: SequenceIter, data?: any | null): void; static swap(a: SequenceIter, b: SequenceIter): void; } export class SequenceIter { static $gtype: GObject.GType<SequenceIter>; constructor(copy: SequenceIter); // Members compare(b: SequenceIter): number; get_position(): number; get_sequence(): Sequence; is_begin(): boolean; is_end(): boolean; move(delta: number): SequenceIter; next(): SequenceIter; prev(): SequenceIter; } export class Source { static $gtype: GObject.GType<Source>; constructor(source_funcs: SourceFuncs, struct_size: number); constructor(copy: Source); // Fields callback_data: any; callback_funcs: SourceCallbackFuncs; source_funcs: SourceFuncs; ref_count: number; context: MainContext; priority: number; flags: number; source_id: number; poll_fds: any[]; prev: Source; next: Source; name: string; priv: SourcePrivate; // Constructors static ["new"](source_funcs: SourceFuncs, struct_size: number): Source; // Members add_child_source(child_source: Source): void; add_poll(fd: PollFD): void; add_unix_fd(fd: number, events: IOCondition): any; attach(context?: MainContext | null): number; destroy(): void; get_can_recurse(): boolean; get_context(): MainContext | null; get_current_time(timeval: TimeVal): void; get_id(): number; get_name(): string; get_priority(): number; get_ready_time(): number; get_time(): number; is_destroyed(): boolean; modify_unix_fd(tag: any, new_events: IOCondition): void; query_unix_fd(tag: any): IOCondition; ref(): Source; remove_child_source(child_source: Source): void; remove_poll(fd: PollFD): void; remove_unix_fd(tag: any): void; set_callback(func: SourceFunc, notify?: DestroyNotify | null): void; set_callback_indirect(callback_data: any | null, callback_funcs: SourceCallbackFuncs): void; set_can_recurse(can_recurse: boolean): void; set_funcs(funcs: SourceFuncs): void; set_name(name: string): void; set_priority(priority: number): void; set_ready_time(ready_time: number): void; unref(): void; static remove(tag: number): boolean; static remove_by_funcs_user_data(funcs: SourceFuncs, user_data?: any | null): boolean; static remove_by_user_data(user_data?: any | null): boolean; static set_name_by_id(tag: number, name: string): void; } export class SourceCallbackFuncs { static $gtype: GObject.GType<SourceCallbackFuncs>; constructor(copy: SourceCallbackFuncs); } export class SourceFuncs { static $gtype: GObject.GType<SourceFuncs>; constructor(copy: SourceFuncs); // Fields closure_callback: SourceFunc; closure_marshal: SourceDummyMarshal; } export class SourcePrivate { static $gtype: GObject.GType<SourcePrivate>; constructor(copy: SourcePrivate); } export class StatBuf { static $gtype: GObject.GType<StatBuf>; constructor(copy: StatBuf); } export class String { static $gtype: GObject.GType<String>; constructor( properties?: Partial<{ str?: string; len?: number; allocated_len?: number; }> ); constructor(copy: String); // Fields str: string; len: number; allocated_len: number; // Members append(val: string): String; append_c(c: number): String; append_len(val: string, len: number): String; append_unichar(wc: number): String; append_uri_escaped(unescaped: string, reserved_chars_allowed: string, allow_utf8: boolean): String; ascii_down(): String; ascii_up(): String; assign(rval: string): String; down(): String; equal(v2: String): boolean; erase(pos: number, len: number): String; free(free_segment: boolean): string | null; free_to_bytes(): Bytes; hash(): number; insert(pos: number, val: string): String; insert_c(pos: number, c: number): String; insert_len(pos: number, val: string, len: number): String; insert_unichar(pos: number, wc: number): String; overwrite(pos: number, val: string): String; overwrite_len(pos: number, val: string, len: number): String; prepend(val: string): String; prepend_c(c: number): String; prepend_len(val: string, len: number): String; prepend_unichar(wc: number): String; set_size(len: number): String; truncate(len: number): String; up(): String; } export class StringChunk { static $gtype: GObject.GType<StringChunk>; constructor(copy: StringChunk); // Members clear(): void; free(): void; insert(string: string): string; insert_const(string: string): string; insert_len(string: string, len: number): string; } export class TestCase { static $gtype: GObject.GType<TestCase>; constructor(copy: TestCase); } export class TestConfig { static $gtype: GObject.GType<TestConfig>; constructor( properties?: Partial<{ test_initialized?: boolean; test_quick?: boolean; test_perf?: boolean; test_verbose?: boolean; test_quiet?: boolean; test_undefined?: boolean; }> ); constructor(copy: TestConfig); // Fields test_initialized: boolean; test_quick: boolean; test_perf: boolean; test_verbose: boolean; test_quiet: boolean; test_undefined: boolean; } export class TestLogBuffer { static $gtype: GObject.GType<TestLogBuffer>; constructor(copy: TestLogBuffer); // Fields data: String; msgs: any[]; // Members free(): void; push(n_bytes: number, bytes: number): void; } export class TestLogMsg { static $gtype: GObject.GType<TestLogMsg>; constructor(copy: TestLogMsg); // Fields log_type: TestLogType; n_strings: number; strings: string; n_nums: number; // Members free(): void; } export class TestSuite { static $gtype: GObject.GType<TestSuite>; constructor(copy: TestSuite); // Members add(test_case: TestCase): void; add_suite(nestedsuite: TestSuite): void; } export class Thread { static $gtype: GObject.GType<Thread>; constructor(name: string | null, func: ThreadFunc); constructor(copy: Thread); // Constructors static ["new"](name: string | null, func: ThreadFunc): Thread; static try_new(name: string | null, func: ThreadFunc): Thread; // Members join(): any | null; ref(): Thread; unref(): void; static error_quark(): Quark; static exit(retval?: any | null): void; static self(): Thread; static yield(): void; } export class ThreadPool { static $gtype: GObject.GType<ThreadPool>; constructor(copy: ThreadPool); // Fields func: Func; user_data: any; exclusive: boolean; // Members free(immediate: boolean, wait_: boolean): void; get_max_threads(): number; get_num_threads(): number; move_to_front(data?: any | null): boolean; push(data?: any | null): boolean; set_max_threads(max_threads: number): boolean; unprocessed(): number; static get_max_idle_time(): number; static get_max_unused_threads(): number; static get_num_unused_threads(): number; static set_max_idle_time(interval: number): void; static set_max_unused_threads(max_threads: number): void; static stop_unused_threads(): void; } export class TimeVal { static $gtype: GObject.GType<TimeVal>; constructor( properties?: Partial<{ tv_sec?: number; tv_usec?: number; }> ); constructor(copy: TimeVal); // Fields tv_sec: number; tv_usec: number; // Members add(microseconds: number): void; to_iso8601(): string | null; static from_iso8601(iso_date: string): [boolean, TimeVal]; } export class TimeZone { static $gtype: GObject.GType<TimeZone>; constructor(identifier?: string | null); constructor(copy: TimeZone); // Constructors static ["new"](identifier?: string | null): TimeZone; static new_local(): TimeZone; static new_offset(seconds: number): TimeZone; static new_utc(): TimeZone; // Members adjust_time(type: TimeType, time_: number): number; find_interval(type: TimeType, time_: number): number; get_abbreviation(interval: number): string; get_identifier(): string; get_offset(interval: number): number; is_dst(interval: number): boolean; ref(): TimeZone; unref(): void; } export class Timer { static $gtype: GObject.GType<Timer>; constructor(copy: Timer); // Members ["continue"](): void; destroy(): void; elapsed(microseconds: number): number; is_active(): boolean; reset(): void; start(): void; stop(): void; } export class TrashStack { static $gtype: GObject.GType<TrashStack>; constructor(copy: TrashStack); // Fields next: TrashStack; // Members static height(stack_p: TrashStack): number; static peek(stack_p: TrashStack): any | null; static pop(stack_p: TrashStack): any | null; static push(stack_p: TrashStack, data_p: any): void; } export class Tree { static $gtype: GObject.GType<Tree>; constructor(copy: Tree); // Members destroy(): void; height(): number; insert(key?: any | null, value?: any | null): void; lookup(key?: any | null): any | null; lookup_extended(lookup_key?: any | null): [boolean, any | null, any | null]; nnodes(): number; remove(key?: any | null): boolean; replace(key?: any | null, value?: any | null): void; steal(key?: any | null): boolean; unref(): void; } export class Uri { static $gtype: GObject.GType<Uri>; constructor(copy: Uri); // Members get_auth_params(): string | null; get_flags(): UriFlags; get_fragment(): string | null; get_host(): string; get_password(): string | null; get_path(): string; get_port(): number; get_query(): string | null; get_scheme(): string; get_user(): string | null; get_userinfo(): string | null; parse_relative(uri_ref: string, flags: UriFlags): Uri; to_string(): string; to_string_partial(flags: UriHideFlags): string; static build( flags: UriFlags, scheme: string, userinfo: string | null, host: string | null, port: number, path: string, query?: string | null, fragment?: string | null ): Uri; static build_with_user( flags: UriFlags, scheme: string, user: string | null, password: string | null, auth_params: string | null, host: string | null, port: number, path: string, query?: string | null, fragment?: string | null ): Uri; static error_quark(): Quark; static escape_bytes(unescaped: Uint8Array | string, reserved_chars_allowed?: string | null): string; static escape_string(unescaped: string, reserved_chars_allowed: string | null, allow_utf8: boolean): string; static is_valid(uri_string: string, flags: UriFlags): boolean; static join( flags: UriFlags, scheme: string | null, userinfo: string | null, host: string | null, port: number, path: string, query?: string | null, fragment?: string | null ): string; static join_with_user( flags: UriFlags, scheme: string | null, user: string | null, password: string | null, auth_params: string | null, host: string | null, port: number, path: string, query?: string | null, fragment?: string | null ): string; static list_extract_uris(uri_list: string): string[]; static parse(uri_string: string, flags: UriFlags): Uri; static parse_params( params: string, length: number, separators: string, flags: UriParamsFlags ): HashTable<string, string>; static parse_scheme(uri: string): string | null; static peek_scheme(uri: string): string | null; static resolve_relative(base_uri_string: string | null, uri_ref: string, flags: UriFlags): string; static split( uri_ref: string, flags: UriFlags ): [ boolean, string | null, string | null, string | null, number | null, string | null, string | null, string | null ]; static split_network(uri_string: string, flags: UriFlags): [boolean, string | null, string | null, number | null]; static split_with_user( uri_ref: string, flags: UriFlags ): [ boolean, string | null, string | null, string | null, string | null, string | null, number | null, string | null, string | null, string | null ]; static unescape_bytes(escaped_string: string, length: number, illegal_characters?: string | null): Bytes; static unescape_segment( escaped_string?: string | null, escaped_string_end?: string | null, illegal_characters?: string | null ): string; static unescape_string(escaped_string: string, illegal_characters?: string | null): string; } export class UriParamsIter { static $gtype: GObject.GType<UriParamsIter>; constructor(copy: UriParamsIter); // Fields dummy0: number; dummy1: any; dummy2: any; dummy3: Uint8Array; // Members init(params: string, length: number, separators: string, flags: UriParamsFlags): void; next(): [boolean, string | null, string | null]; } export class DoubleIEEE754 { static $gtype: GObject.GType<DoubleIEEE754>; constructor( properties?: Partial<{ v_double?: number; }> ); constructor(copy: DoubleIEEE754); // Fields v_double: number; } export class FloatIEEE754 { static $gtype: GObject.GType<FloatIEEE754>; constructor( properties?: Partial<{ v_float?: number; }> ); constructor(copy: FloatIEEE754); // Fields v_float: number; } export class Mutex { static $gtype: GObject.GType<Mutex>; constructor(copy: Mutex); // Fields p: any; i: number[]; // Members clear(): void; init(): void; lock(): void; trylock(): boolean; unlock(): void; } export class TokenValue { static $gtype: GObject.GType<TokenValue>; constructor( properties?: Partial<{ v_symbol?: any; v_identifier?: string; v_binary?: number; v_octal?: number; v_int?: number; v_int64?: number; v_float?: number; v_hex?: number; v_string?: string; v_comment?: string; v_char?: number; v_error?: number; }> ); constructor(copy: TokenValue); // Fields v_symbol: any; v_identifier: string; v_binary: number; v_octal: number; v_int: number; v_int64: number; v_float: number; v_hex: number; v_string: string; v_comment: string; v_char: number; v_error: number; } export type DateDay = number; export type DateYear = number; export type MainContextPusher = void; export type MutexLocker = void; export type Pid = number; export type Quark = number; export type RWLockReaderLocker = void; export type RWLockWriterLocker = void; export type RecMutexLocker = void; export type RefString = number; export type Strv = string; export type Time = number; export type TimeSpan = number; export type Type = number; export function log_structured(logDomain: any, logLevel: any, stringFields: any): any; export function strstrip(str: string): string; // Variant parsing inspired by https://jamie.build/ slightly infamous JSON-in-TypeScript parsing. type CreateIndexType<Key extends string, Value extends any> = Key extends `s` | `o` | `g` ? { [key: string]: Value } : Key extends `n` | `q` | `t` | `d` | `u` | `i` | `x` | `y` ? { [key: number]: Value } : never; type VariantTypeError<T extends string> = { error: true } & T; /** * Handles the {kv} of a{kv} where k is a basic type and v is any possible variant type string. */ type $ParseDeepVariantDict<State extends string, Memo extends Record<string, any> = {}> = string extends State ? VariantTypeError<"$ParseDeepVariantDict: 'string' is not a supported type."> : // Hitting the first '}' indicates the dictionary type is complete State extends `}${infer State}` ? [Memo, State] : // This separates the key (basic type) from the rest of the remaining expression. State extends `${infer Key}${""}${infer State}` ? $ParseDeepVariantValue<State> extends [infer Value, `${infer State}`] ? State extends `}${infer State}` ? [CreateIndexType<Key, Value>, State] : VariantTypeError<`$ParseDeepVariantDict encountered an invalid variant string: ${State} (1)`> : VariantTypeError<`$ParseDeepVariantValue returned unexpected value for: ${State}`> : VariantTypeError<`$ParseDeepVariantDict encountered an invalid variant string: ${State} (2)`>; /** * Handles parsing values within a tuple (e.g. (vvv)) where v is any possible variant type string. */ type $ParseDeepVariantArray<State extends string, Memo extends any[] = []> = string extends State ? VariantTypeError<"$ParseDeepVariantArray: 'string' is not a supported type."> : State extends `)${infer State}` ? [Memo, State] : $ParseDeepVariantValue<State> extends [infer Value, `${infer State}`] ? State extends `${infer NextValue})${infer NextState}` ? $ParseDeepVariantArray<State, [...Memo, Value]> : State extends `)${infer State}` ? [[...Memo, Value], State] : VariantTypeError<`1: $ParseDeepVariantArray encountered an invalid variant string: ${State}`> : VariantTypeError<`2: $ParseDeepVariantValue returned unexpected value for: ${State}`>; /** * Handles parsing {kv} without an 'a' prefix (key-value pair) where k is a basic type * and v is any possible variant type string. */ type $ParseDeepVariantKeyValue<State extends string, Memo extends any[] = []> = string extends State ? VariantTypeError<"$ParseDeepVariantKeyValue: 'string' is not a supported type."> : State extends `}${infer State}` ? [Memo, State] : State extends `${infer Key}${""}${infer State}` ? $ParseDeepVariantValue<State> extends [infer Value, `${infer State}`] ? State extends `}${infer State}` ? [[...Memo, Key, Value], State] : VariantTypeError<`$ParseDeepVariantKeyValue encountered an invalid variant string: ${State} (1)`> : VariantTypeError<`$ParseDeepVariantKeyValue returned unexpected value for: ${State}`> : VariantTypeError<`$ParseDeepVariantKeyValue encountered an invalid variant string: ${State} (2)`>; /** * Handles parsing any variant 'value' or base unit. * * - ay - Array of bytes (Uint8Array) * - a* - Array of type * * - a{k*} - Dictionary * - {k*} - KeyValue * - (**) - tuple * - s | o | g - string types * - n | q | t | d | u | i | x | y - number types * - b - boolean type * - v - unknown Variant type * - h | ? - unknown types */ type $ParseDeepVariantValue<State extends string> = string extends State ? unknown : State extends `${`s` | `o` | `g`}${infer State}` ? [string, State] : State extends `${`n` | `q` | `t` | `d` | `u` | `i` | `x` | `y`}${infer State}` ? [number, State] : State extends `b${infer State}` ? [boolean, State] : State extends `v${infer State}` ? [Variant, State] : State extends `${"h" | "?"}${infer State}` ? [unknown, State] : State extends `(${infer State}` ? $ParseDeepVariantArray<State> : State extends `a{${infer State}` ? $ParseDeepVariantDict<State> : State extends `{${infer State}` ? $ParseDeepVariantKeyValue<State> : State extends `ay${infer State}` ? [Uint8Array, State] : State extends `a${infer State}` ? $ParseDeepVariantValue<State> extends [infer Value, `${infer State}`] ? [Value[], State] : VariantTypeError<`$ParseDeepVariantValue encountered an invalid variant string: ${State} (1)`> : VariantTypeError<`$ParseDeepVariantValue encountered an invalid variant string: ${State} (2)`>; type $ParseDeepVariant<T extends string> = $ParseDeepVariantValue<T> extends infer Result ? Result extends [infer Value, string] ? Value : Result extends VariantTypeError<any> ? Result : VariantTypeError<"$ParseDeepVariantValue returned unexpected Result"> : VariantTypeError<"$ParseDeepVariantValue returned uninferrable Result">; type $ParseRecursiveVariantDict<State extends string, Memo extends Record<string, any> = {}> = string extends State ? VariantTypeError<"$ParseRecursiveVariantDict: 'string' is not a supported type."> : State extends `}${infer State}` ? [Memo, State] : State extends `${infer Key}${""}${infer State}` ? $ParseRecursiveVariantValue<State> extends [infer Value, `${infer State}`] ? State extends `}${infer State}` ? [CreateIndexType<Key, Value>, State] : VariantTypeError<`$ParseRecursiveVariantDict encountered an invalid variant string: ${State} (1)`> : VariantTypeError<`$ParseRecursiveVariantValue returned unexpected value for: ${State}`> : VariantTypeError<`$ParseRecursiveVariantDict encountered an invalid variant string: ${State} (2)`>; type $ParseRecursiveVariantArray<State extends string, Memo extends any[] = []> = string extends State ? VariantTypeError<"$ParseRecursiveVariantArray: 'string' is not a supported type."> : State extends `)${infer State}` ? [Memo, State] : $ParseRecursiveVariantValue<State> extends [infer Value, `${infer State}`] ? State extends `${infer NextValue})${infer NextState}` ? $ParseRecursiveVariantArray<State, [...Memo, Value]> : State extends `)${infer State}` ? [[...Memo, Value], State] : VariantTypeError<`$ParseRecursiveVariantArray encountered an invalid variant string: ${State} (1)`> : VariantTypeError<`$ParseRecursiveVariantValue returned unexpected value for: ${State} (2)`>; type $ParseRecursiveVariantKeyValue<State extends string, Memo extends any[] = []> = string extends State ? VariantTypeError<"$ParseRecursiveVariantKeyValue: 'string' is not a supported type."> : State extends `}${infer State}` ? [Memo, State] : State extends `${infer Key}${""}${infer State}` ? $ParseRecursiveVariantValue<State> extends [infer Value, `${infer State}`] ? State extends `}${infer State}` ? [[...Memo, Key, Value], State] : VariantTypeError<`$ParseRecursiveVariantKeyValue encountered an invalid variant string: ${State} (1)`> : VariantTypeError<`$ParseRecursiveVariantKeyValue returned unexpected value for: ${State}`> : VariantTypeError<`$ParseRecursiveVariantKeyValue encountered an invalid variant string: ${State} (2)`>; type $ParseRecursiveVariantValue<State extends string> = string extends State ? unknown : State extends `${`s` | `o` | `g`}${infer State}` ? [string, State] : State extends `${`n` | `q` | `t` | `d` | `u` | `i` | `x` | `y`}${infer State}` ? [number, State] : State extends `b${infer State}` ? [boolean, State] : State extends `v${infer State}` ? [unknown, State] : State extends `${"h" | "?"}${infer State}` ? [unknown, State] : State extends `(${infer State}` ? $ParseRecursiveVariantArray<State> : State extends `a{${infer State}` ? $ParseRecursiveVariantDict<State> : State extends `{${infer State}` ? $ParseRecursiveVariantKeyValue<State> : State extends `ay${infer State}` ? [Uint8Array, State] : State extends `a${infer State}` ? $ParseRecursiveVariantValue<State> extends [infer Value, `${infer State}`] ? [Value[], State] : VariantTypeError<`$ParseRecursiveVariantValue encountered an invalid variant string: ${State} (1)`> : VariantTypeError<`$ParseRecursiveVariantValue encountered an invalid variant string: ${State} (2)`>; type $ParseRecursiveVariant<T extends string> = $ParseRecursiveVariantValue<T> extends infer Result ? Result extends [infer Value, string] ? Value : Result extends VariantTypeError<any> ? Result : never : never; type $ParseVariantDict<State extends string, Memo extends Record<string, any> = {}> = string extends State ? VariantTypeError<"$ParseVariantDict: 'string' is not a supported type."> : State extends `}${infer State}` ? [Memo, State] : State extends `${infer Key}${""}${infer State}` ? $ParseVariantValue<State> extends [infer Value, `${infer State}`] ? State extends `}${infer State}` ? [CreateIndexType<Key, Variant<Value extends string ? Value : any>>, State] : VariantTypeError<`$ParseVariantDict encountered an invalid variant string: ${State} (1)`> : VariantTypeError<`$ParseVariantValue returned unexpected value for: ${State}`> : VariantTypeError<`$ParseVariantDict encountered an invalid variant string: ${State} (2)`>; type $ParseVariantArray<State extends string, Memo extends any[] = []> = string extends State ? VariantTypeError<"$ParseVariantArray: 'string' is not a supported type."> : State extends `)${infer State}` ? [Memo, State] : $ParseVariantValue<State> extends [infer Value, `${infer State}`] ? State extends `${infer NextValue})${infer NextState}` ? $ParseVariantArray<State, [...Memo, Variant<Value extends string ? Value : any>]> : State extends `)${infer State}` ? [[...Memo, Variant<Value extends string ? Value : any>], State] : VariantTypeError<`$ParseVariantArray encountered an invalid variant string: ${State} (1)`> : VariantTypeError<`$ParseVariantValue returned unexpected value for: ${State} (2)`>; type $ParseVariantKeyValue<State extends string, Memo extends any[] = []> = string extends State ? VariantTypeError<"$ParseVariantKeyValue: 'string' is not a supported type."> : State extends `}${infer State}` ? [Memo, State] : State extends `${infer Key}${""}${infer State}` ? $ParseVariantValue<State> extends [infer Value, `${infer State}`] ? State extends `}${infer State}` ? [[...Memo, Variant<Key>, Variant<Value extends string ? Value : any>], State] : VariantTypeError<`$ParseVariantKeyValue encountered an invalid variant string: ${State} (1)`> : VariantTypeError<`$ParseVariantKeyValue returned unexpected value for: ${State}`> : VariantTypeError<`$ParseVariantKeyValue encountered an invalid variant string: ${State} (2)`>; type $ParseShallowRootVariantValue<State extends string> = string extends State ? unknown : State extends `${`s` | `o` | `g`}${infer State}` ? [string, State] : State extends `${`n` | `q` | `t` | `d` | `u` | `i` | `x` | `y`}${infer State}` ? [number, State] : State extends `b${infer State}` ? [boolean, State] : State extends `v${infer State}` ? [Variant, State] : State extends `h${infer State}` ? [unknown, State] : State extends `?${infer State}` ? [unknown, State] : State extends `(${infer State}` ? $ParseVariantArray<State> : State extends `a{${infer State}` ? $ParseVariantDict<State> : State extends `{${infer State}` ? $ParseVariantKeyValue<State> : State extends `ay${infer State}` ? [Uint8Array, State] : State extends `a${infer State}` ? $ParseVariantValue<State> extends [infer Value, `${infer State}`] ? [Value[], State] : VariantTypeError<`$ParseShallowRootVariantValue encountered an invalid variant string: ${State} (1)`> : VariantTypeError<`$ParseShallowRootVariantValue encountered an invalid variant string: ${State} (2)`>; type $ParseVariantValue<State extends string> = string extends State ? unknown : State extends `s${infer State}` ? ["s", State] : State extends `o${infer State}` ? ["o", State] : State extends `g${infer State}` ? ["g", State] : State extends `${`n` | `q` | `t` | `d` | `u` | `i` | `x` | `y`}${infer State}` ? // TODO ["u", State] : State extends `b${infer State}` ? ["b", State] : State extends `v${infer State}` ? ["v", State] : State extends `h${infer State}` ? ["h", State] : State extends `?${infer State}` ? ["?", State] : State extends `(${infer State}` ? $ParseVariantArray<State> : State extends `a{${infer State}` ? $ParseVariantDict<State> : State extends `{${infer State}` ? $ParseVariantKeyValue<State> : State extends `ay${infer State}` ? [Uint8Array, State] : State extends `a${infer State}` ? $ParseVariantValue<State> extends [infer Value, `${infer State}`] ? [Value[], State] : VariantTypeError<`$ParseVariantValue encountered an invalid variant string: ${State} (1)`> : VariantTypeError<`$ParseVariantValue encountered an invalid variant string: ${State} (2)`>; type $ParseVariant<T extends string> = $ParseShallowRootVariantValue<T> extends infer Result ? Result extends [infer Value, string] ? Value : Result extends VariantTypeError<any> ? Result : never : never; type $VariantTypeToString<T extends VariantType> = T extends VariantType<infer S> ? S : never; export class Variant<S extends string = any> { static $gtype: GObject.GType<Variant>; constructor(sig: S, value: $ParseDeepVariant<typeof sig>); constructor(copy: Variant<S>); _init(sig: S, value: any): Variant<S>; // Constructors static ["new"]<S extends string>(sig: S, value: $ParseDeepVariant<typeof sig>): Variant<S>; static _new_internal<S extends string>(sig: S, value: $ParseDeepVariant<typeof sig>): Variant<S>; static new_array<C extends string = "a?">( child_type: VariantType<C>, children?: Variant<$VariantTypeToString<typeof child_type>>[] | null ): Variant<`a${C}`>; static new_boolean(value: boolean): Variant<"b">; static new_byte(value: number): Variant<"y">; static new_bytestring(string: Uint8Array | string): Variant<"ay">; static new_bytestring_array(strv: string[]): Variant<"aay">; static new_dict_entry(key: Variant, value: Variant): Variant<"{vv}">; static new_double(value: number): Variant<"d">; static new_fixed_array<C extends string = "a?">( element_type: VariantType<C>, elements: Variant<$VariantTypeToString<typeof element_type>>[] | null, n_elements: number, element_size: number ): Variant<`a${C}`>; static new_from_bytes<C extends string>( type: VariantType<C>, bytes: Bytes | Uint8Array, trusted: boolean ): Variant<C>; static new_from_data<C extends string>( type: VariantType<C>, data: Uint8Array | string, trusted: boolean, user_data?: any | null ): Variant<C>; static new_handle(value: number): Variant<"h">; static new_int16(value: number): Variant<"n">; static new_int32(value: number): Variant<"i">; static new_int64(value: number): Variant<"x">; static new_maybe(child_type?: VariantType | null, child?: Variant | null): Variant<"mv">; static new_object_path(object_path: string): Variant<"o">; static new_objv(strv: string[]): Variant<"ao">; static new_signature(signature: string): Variant<"g">; static new_string(string: string): Variant<"s">; static new_strv(strv: string[]): Variant<"as">; static new_tuple<Items extends ReadonlyArray<VariantType> | readonly [VariantType]>( children: Items ): Variant<`(${$ToTuple<Items>})`>; static new_uint16(value: number): Variant<"q">; static new_uint32(value: number): Variant<"u">; static new_uint64(value: number): Variant<"t">; static new_variant(value: Variant): Variant<"v">; // Members byteswap(): Variant; check_format_string(format_string: string, copy_only: boolean): boolean; classify(): VariantClass; compare(two: Variant): number; dup_bytestring(): Uint8Array; dup_bytestring_array(): string[]; dup_objv(): string[]; dup_string(): [string, number]; dup_strv(): string[]; equal(two: Variant): boolean; get_boolean(): boolean; get_byte(): number; get_bytestring(): Uint8Array; get_bytestring_array(): string[]; get_child_value(index_: number): Variant; get_data(): any | null; get_data_as_bytes(): Bytes; get_double(): number; get_handle(): number; get_int16(): number; get_int32(): number; get_int64(): number; get_maybe(): Variant | null; get_normal_form(): Variant; get_objv(): string[]; get_size(): number; get_string(): [string, number | null]; get_strv(): string[]; get_type(): VariantType<S>; get_type_string(): string; get_uint16(): number; get_uint32(): number; get_uint64(): number; get_variant(): Variant; hash(): number; is_container(): boolean; is_floating(): boolean; is_normal_form(): boolean; is_of_type(type: VariantType): boolean; lookup_value(key: string, expected_type?: VariantType | null): Variant; n_children(): number; print(type_annotate: boolean): string; ref(): Variant; ref_sink(): Variant; store(data: any): void; take_ref(): Variant; unref(): void; static is_object_path(string: string): boolean; static is_signature(string: string): boolean; static parse(type: VariantType | null, text: string, limit?: string | null, endptr?: string | null): Variant; static parse_error_print_context(error: Error, source_str: string): string; static parse_error_quark(): Quark; static parser_get_error_quark(): Quark; unpack(): $ParseVariant<S>; deepUnpack(): $ParseDeepVariant<S>; deep_unpack(): $ParseDeepVariant<S>; recursiveUnpack(): $ParseRecursiveVariant<S>; } type $ElementSig<E extends any> = E extends [infer Element] ? Element : E extends [infer Element, ...infer Elements] ? Element | $ElementSig<Elements> : E extends globalThis.Array<infer Element> ? Element : never; export class VariantBuilder<S extends string = "a*"> { static $gtype: GObject.GType<VariantBuilder>; constructor(type: VariantType<S>); constructor(copy: VariantBuilder<S>); // Constructors static ["new"]<S extends string = "a*">(type: VariantType<S>): VariantBuilder<S>; // Members add_value(value: $ElementSig<$ParseDeepVariant<S>>): void; close(): void; end(): Variant<S>; open(type: VariantType): void; ref(): VariantBuilder; unref(): void; } export class VariantDict { static $gtype: GObject.GType<VariantDict>; constructor(from_asv?: Variant | null); constructor(copy: VariantDict); // Constructors static ["new"](from_asv?: Variant | null): VariantDict; // Members clear(): void; contains(key: string): boolean; end(): Variant; insert_value(key: string, value: Variant): void; lookup_value(key: string, expected_type?: VariantType | null): Variant; ref(): VariantDict; remove(key: string): boolean; unref(): void; lookup(key: any, variantType?: any, deep?: boolean): any; } type $ToTuple<T extends readonly VariantType[]> = T extends [] ? "" : T extends [VariantType<infer S>] ? `${S}` : T extends [VariantType<infer S>, ...infer U] ? U extends [...VariantType[]] ? `${S}${$ToTuple<U>}` : never : "?"; export class VariantType<S extends string = any> { static $gtype: GObject.GType<VariantType>; constructor(type_string: S); constructor(copy: VariantType<S>); // Constructors static ["new"]<S extends string>(type_string: S): VariantType<S>; static new_array<S extends string>(element: VariantType<S>): VariantType<`a${S}`>; static new_dict_entry<K extends string, V extends string>( key: VariantType<K>, value: VariantType<V> ): VariantType<`{${K}${V}}`>; static new_maybe<S extends string>(element: VariantType<S>): VariantType<`m${S}`>; static new_tuple<Items extends ReadonlyArray<VariantType> | readonly [VariantType]>( items: Items ): VariantType<`(${$ToTuple<Items>})`>; // Members copy(): VariantType<S>; dup_string(): string; element(): VariantType; equal(type2: VariantType): boolean; first(): VariantType; free(): void; get_string_length(): number; hash(): number; is_array(): boolean; is_basic(): boolean; is_container(): boolean; is_definite(): boolean; is_dict_entry(): boolean; is_maybe(): boolean; is_subtype_of(supertype: VariantType): boolean; is_tuple(): boolean; is_variant(): boolean; key(): VariantType; n_items(): number; next(): VariantType; value(): VariantType; static checked_(arg0: string): VariantType; static string_get_depth_(type_string: string): number; static string_is_valid(type_string: string): boolean; static string_scan(string: string, limit?: string | null): [boolean, string | null]; }
the_stack
import { gql } from "@apollo/client"; import * as Apollo from "@apollo/client"; export type Maybe<T> = T | null; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }; export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }; export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }; const defaultOptions = {}; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; Date: any; }; export type IEntry = { __typename?: "Entry"; id: Maybe<Scalars["ID"]>; title: Maybe<Scalars["String"]>; author: Maybe<IAuthor>; content: Maybe<Scalars["String"]>; public: Maybe<Scalars["Boolean"]>; dateAdded: Maybe<Scalars["Date"]>; dateModified: Maybe<Scalars["Date"]>; excerpt: Maybe<Scalars["String"]>; user: Maybe<Scalars["String"]>; }; export type IAuthor = { __typename?: "Author"; username: Maybe<Scalars["String"]>; gradient: Maybe<Array<Maybe<Scalars["String"]>>>; }; export type IPreview = { __typename?: "Preview"; title: Maybe<Scalars["String"]>; id: Maybe<Scalars["ID"]>; content: Maybe<Scalars["String"]>; author: Maybe<IAuthor>; dateAdded: Maybe<Scalars["Date"]>; }; export type IUser = { __typename?: "User"; username: Scalars["String"]; email: Scalars["String"]; admin: Maybe<Scalars["Boolean"]>; }; export type IUserSettingsInput = { username: Maybe<Scalars["String"]>; email: Maybe<Scalars["String"]>; }; export type IAuthUserPayload = { __typename?: "AuthUserPayload"; token: Maybe<Scalars["String"]>; }; export type IUsageDetails = { __typename?: "UsageDetails"; entryCount: Scalars["Int"]; privateEntries: Scalars["Int"]; publicEntries: Scalars["Int"]; }; export type IMe = { __typename?: "Me"; details: Maybe<IUser>; token: Maybe<Scalars["String"]>; usage: IUsageDetails; }; export type IQuery = { __typename?: "Query"; /** Markdown document */ entry: Maybe<IEntry>; /** List of Markdown documents */ feed: Array<IEntry>; /** Public preview of Markdown document */ preview: Maybe<IPreview>; /** User Settings */ settings: Maybe<IUser>; me: Maybe<IMe>; }; export type IQueryEntryArgs = { id: Scalars["ID"]; }; export type IQueryPreviewArgs = { id: Scalars["ID"]; }; export type IMutation = { __typename?: "Mutation"; createEntry: Maybe<IEntry>; updateEntry: Maybe<IEntry>; deleteEntry: Maybe<IEntry>; createUser: Maybe<IAuthUserPayload>; authenticateUser: Maybe<IAuthUserPayload>; updateUserSettings: Maybe<IUser>; updatePassword: Maybe<IAuthUserPayload>; }; export type IMutationCreateEntryArgs = { content: Maybe<Scalars["String"]>; title: Maybe<Scalars["String"]>; }; export type IMutationUpdateEntryArgs = { id: Scalars["String"]; content: Scalars["String"]; title: Scalars["String"]; status: Scalars["Boolean"]; }; export type IMutationDeleteEntryArgs = { id: Scalars["ID"]; }; export type IMutationCreateUserArgs = { username: Scalars["String"]; email: Scalars["String"]; password: Scalars["String"]; }; export type IMutationAuthenticateUserArgs = { username: Scalars["String"]; password: Scalars["String"]; }; export type IMutationUpdateUserSettingsArgs = { settings: IUserSettingsInput; }; export type IMutationUpdatePasswordArgs = { currentPassword: Scalars["String"]; newPassword: Scalars["String"]; }; export type IEntryInfoFragment = { __typename?: "Entry" } & Pick< IEntry, "title" | "dateAdded" | "id" | "public" >; export type IAllPostsQueryVariables = Exact<{ [key: string]: never }>; export type IAllPostsQuery = { __typename?: "Query" } & { feed: Array<{ __typename?: "Entry" } & IEntryInfoFragment>; }; export type IEditQueryVariables = Exact<{ id: Scalars["ID"]; }>; export type IEditQuery = { __typename?: "Query" } & { entry: Maybe< { __typename?: "Entry" } & Pick<IEntry, "content"> & IEntryInfoFragment >; }; export type IPreviewQueryVariables = Exact<{ id: Scalars["ID"]; }>; export type IPreviewQuery = { __typename?: "Query" } & { preview: Maybe< { __typename?: "Preview" } & Pick< IPreview, "title" | "dateAdded" | "id" | "content" > & { author: Maybe<{ __typename?: "Author" } & Pick<IAuthor, "username">> } >; }; export type IUserDetailsQueryVariables = Exact<{ [key: string]: never }>; export type IUserDetailsQuery = { __typename?: "Query" } & { settings: Maybe<{ __typename?: "User" } & Pick<IUser, "username" | "email">>; me: Maybe< { __typename?: "Me" } & { usage: { __typename?: "UsageDetails" } & Pick< IUsageDetails, "entryCount" | "publicEntries" | "privateEntries" >; } >; }; export type IUpdateEntryMutationVariables = Exact<{ id: Scalars["String"]; content: Scalars["String"]; title: Scalars["String"]; status: Scalars["Boolean"]; }>; export type IUpdateEntryMutation = { __typename?: "Mutation" } & { updateEntry: Maybe< { __typename?: "Entry" } & Pick<IEntry, "content"> & IEntryInfoFragment >; }; export type ICreateEntryMutationVariables = Exact<{ content: Maybe<Scalars["String"]>; title: Maybe<Scalars["String"]>; }>; export type ICreateEntryMutation = { __typename?: "Mutation" } & { createEntry: Maybe<{ __typename?: "Entry" } & IEntryInfoFragment>; }; export type IRemoveEntryMutationVariables = Exact<{ id: Scalars["ID"]; }>; export type IRemoveEntryMutation = { __typename?: "Mutation" } & { deleteEntry: Maybe<{ __typename?: "Entry" } & Pick<IEntry, "title" | "id">>; }; export type ILoginUserMutationVariables = Exact<{ username: Scalars["String"]; password: Scalars["String"]; }>; export type ILoginUserMutation = { __typename?: "Mutation" } & { authenticateUser: Maybe< { __typename?: "AuthUserPayload" } & Pick<IAuthUserPayload, "token"> >; }; export type ICreateUserMutationVariables = Exact<{ username: Scalars["String"]; email: Scalars["String"]; password: Scalars["String"]; }>; export type ICreateUserMutation = { __typename?: "Mutation" } & { createUser: Maybe< { __typename?: "AuthUserPayload" } & Pick<IAuthUserPayload, "token"> >; }; export type IUpdateUserSettingsMutationVariables = Exact<{ settings: IUserSettingsInput; }>; export type IUpdateUserSettingsMutation = { __typename?: "Mutation" } & { updateUserSettings: Maybe< { __typename?: "User" } & Pick<IUser, "username" | "email"> >; }; export type IUpdatePasswordMutationVariables = Exact<{ current: Scalars["String"]; newPassword: Scalars["String"]; }>; export type IUpdatePasswordMutation = { __typename?: "Mutation" } & { updatePassword: Maybe< { __typename?: "AuthUserPayload" } & Pick<IAuthUserPayload, "token"> >; }; export type IIsMeQueryVariables = Exact<{ [key: string]: never }>; export type IIsMeQuery = { __typename?: "Query" } & { me: Maybe<{ __typename?: "Me" } & Pick<IMe, "token">>; }; export const EntryInfoFragmentDoc = gql` fragment EntryInfo on Entry { title dateAdded id public } `; export const AllPostsDocument = gql` query AllPosts { feed { ...EntryInfo } } ${EntryInfoFragmentDoc} `; /** * __useAllPostsQuery__ * * To run a query within a React component, call `useAllPostsQuery` and pass it any options that fit your needs. * When your component renders, `useAllPostsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useAllPostsQuery({ * variables: { * }, * }); */ export function useAllPostsQuery( baseOptions?: Apollo.QueryHookOptions<IAllPostsQuery, IAllPostsQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions }; return Apollo.useQuery<IAllPostsQuery, IAllPostsQueryVariables>( AllPostsDocument, options ); } export function useAllPostsLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions<IAllPostsQuery, IAllPostsQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions }; return Apollo.useLazyQuery<IAllPostsQuery, IAllPostsQueryVariables>( AllPostsDocument, options ); } export type AllPostsQueryHookResult = ReturnType<typeof useAllPostsQuery>; export type AllPostsLazyQueryHookResult = ReturnType<typeof useAllPostsLazyQuery>; export type AllPostsQueryResult = Apollo.QueryResult< IAllPostsQuery, IAllPostsQueryVariables >; export const EditDocument = gql` query Edit($id: ID!) { entry(id: $id) { ...EntryInfo content } } ${EntryInfoFragmentDoc} `; /** * __useEditQuery__ * * To run a query within a React component, call `useEditQuery` and pass it any options that fit your needs. * When your component renders, `useEditQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useEditQuery({ * variables: { * id: // value for 'id' * }, * }); */ export function useEditQuery( baseOptions: Apollo.QueryHookOptions<IEditQuery, IEditQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions }; return Apollo.useQuery<IEditQuery, IEditQueryVariables>(EditDocument, options); } export function useEditLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions<IEditQuery, IEditQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions }; return Apollo.useLazyQuery<IEditQuery, IEditQueryVariables>(EditDocument, options); } export type EditQueryHookResult = ReturnType<typeof useEditQuery>; export type EditLazyQueryHookResult = ReturnType<typeof useEditLazyQuery>; export type EditQueryResult = Apollo.QueryResult<IEditQuery, IEditQueryVariables>; export const PreviewDocument = gql` query Preview($id: ID!) { preview(id: $id) { title dateAdded id content author { username } } } `; /** * __usePreviewQuery__ * * To run a query within a React component, call `usePreviewQuery` and pass it any options that fit your needs. * When your component renders, `usePreviewQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = usePreviewQuery({ * variables: { * id: // value for 'id' * }, * }); */ export function usePreviewQuery( baseOptions: Apollo.QueryHookOptions<IPreviewQuery, IPreviewQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions }; return Apollo.useQuery<IPreviewQuery, IPreviewQueryVariables>( PreviewDocument, options ); } export function usePreviewLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions<IPreviewQuery, IPreviewQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions }; return Apollo.useLazyQuery<IPreviewQuery, IPreviewQueryVariables>( PreviewDocument, options ); } export type PreviewQueryHookResult = ReturnType<typeof usePreviewQuery>; export type PreviewLazyQueryHookResult = ReturnType<typeof usePreviewLazyQuery>; export type PreviewQueryResult = Apollo.QueryResult< IPreviewQuery, IPreviewQueryVariables >; export const UserDetailsDocument = gql` query UserDetails { settings { username email } me { usage { entryCount publicEntries privateEntries } } } `; /** * __useUserDetailsQuery__ * * To run a query within a React component, call `useUserDetailsQuery` and pass it any options that fit your needs. * When your component renders, `useUserDetailsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useUserDetailsQuery({ * variables: { * }, * }); */ export function useUserDetailsQuery( baseOptions?: Apollo.QueryHookOptions< IUserDetailsQuery, IUserDetailsQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions }; return Apollo.useQuery<IUserDetailsQuery, IUserDetailsQueryVariables>( UserDetailsDocument, options ); } export function useUserDetailsLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions< IUserDetailsQuery, IUserDetailsQueryVariables > ) { const options = { ...defaultOptions, ...baseOptions }; return Apollo.useLazyQuery<IUserDetailsQuery, IUserDetailsQueryVariables>( UserDetailsDocument, options ); } export type UserDetailsQueryHookResult = ReturnType<typeof useUserDetailsQuery>; export type UserDetailsLazyQueryHookResult = ReturnType< typeof useUserDetailsLazyQuery >; export type UserDetailsQueryResult = Apollo.QueryResult< IUserDetailsQuery, IUserDetailsQueryVariables >; export const UpdateEntryDocument = gql` mutation UpdateEntry( $id: String! $content: String! $title: String! $status: Boolean! ) { updateEntry(id: $id, content: $content, title: $title, status: $status) { ...EntryInfo content } } ${EntryInfoFragmentDoc} `; export type IUpdateEntryMutationFn = Apollo.MutationFunction< IUpdateEntryMutation, IUpdateEntryMutationVariables >; /** * __useUpdateEntryMutation__ * * To run a mutation, you first call `useUpdateEntryMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useUpdateEntryMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [updateEntryMutation, { data, loading, error }] = useUpdateEntryMutation({ * variables: { * id: // value for 'id' * content: // value for 'content' * title: // value for 'title' * status: // value for 'status' * }, * }); */ export function useUpdateEntryMutation( baseOptions?: Apollo.MutationHookOptions< IUpdateEntryMutation, IUpdateEntryMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions }; return Apollo.useMutation<IUpdateEntryMutation, IUpdateEntryMutationVariables>( UpdateEntryDocument, options ); } export type UpdateEntryMutationHookResult = ReturnType< typeof useUpdateEntryMutation >; export type UpdateEntryMutationResult = Apollo.MutationResult<IUpdateEntryMutation>; export type UpdateEntryMutationOptions = Apollo.BaseMutationOptions< IUpdateEntryMutation, IUpdateEntryMutationVariables >; export const CreateEntryDocument = gql` mutation CreateEntry($content: String, $title: String) { createEntry(content: $content, title: $title) { ...EntryInfo } } ${EntryInfoFragmentDoc} `; export type ICreateEntryMutationFn = Apollo.MutationFunction< ICreateEntryMutation, ICreateEntryMutationVariables >; /** * __useCreateEntryMutation__ * * To run a mutation, you first call `useCreateEntryMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useCreateEntryMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [createEntryMutation, { data, loading, error }] = useCreateEntryMutation({ * variables: { * content: // value for 'content' * title: // value for 'title' * }, * }); */ export function useCreateEntryMutation( baseOptions?: Apollo.MutationHookOptions< ICreateEntryMutation, ICreateEntryMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions }; return Apollo.useMutation<ICreateEntryMutation, ICreateEntryMutationVariables>( CreateEntryDocument, options ); } export type CreateEntryMutationHookResult = ReturnType< typeof useCreateEntryMutation >; export type CreateEntryMutationResult = Apollo.MutationResult<ICreateEntryMutation>; export type CreateEntryMutationOptions = Apollo.BaseMutationOptions< ICreateEntryMutation, ICreateEntryMutationVariables >; export const RemoveEntryDocument = gql` mutation RemoveEntry($id: ID!) { deleteEntry(id: $id) { title id } } `; export type IRemoveEntryMutationFn = Apollo.MutationFunction< IRemoveEntryMutation, IRemoveEntryMutationVariables >; /** * __useRemoveEntryMutation__ * * To run a mutation, you first call `useRemoveEntryMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useRemoveEntryMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [removeEntryMutation, { data, loading, error }] = useRemoveEntryMutation({ * variables: { * id: // value for 'id' * }, * }); */ export function useRemoveEntryMutation( baseOptions?: Apollo.MutationHookOptions< IRemoveEntryMutation, IRemoveEntryMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions }; return Apollo.useMutation<IRemoveEntryMutation, IRemoveEntryMutationVariables>( RemoveEntryDocument, options ); } export type RemoveEntryMutationHookResult = ReturnType< typeof useRemoveEntryMutation >; export type RemoveEntryMutationResult = Apollo.MutationResult<IRemoveEntryMutation>; export type RemoveEntryMutationOptions = Apollo.BaseMutationOptions< IRemoveEntryMutation, IRemoveEntryMutationVariables >; export const LoginUserDocument = gql` mutation LoginUser($username: String!, $password: String!) { authenticateUser(username: $username, password: $password) { token } } `; export type ILoginUserMutationFn = Apollo.MutationFunction< ILoginUserMutation, ILoginUserMutationVariables >; /** * __useLoginUserMutation__ * * To run a mutation, you first call `useLoginUserMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useLoginUserMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [loginUserMutation, { data, loading, error }] = useLoginUserMutation({ * variables: { * username: // value for 'username' * password: // value for 'password' * }, * }); */ export function useLoginUserMutation( baseOptions?: Apollo.MutationHookOptions< ILoginUserMutation, ILoginUserMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions }; return Apollo.useMutation<ILoginUserMutation, ILoginUserMutationVariables>( LoginUserDocument, options ); } export type LoginUserMutationHookResult = ReturnType<typeof useLoginUserMutation>; export type LoginUserMutationResult = Apollo.MutationResult<ILoginUserMutation>; export type LoginUserMutationOptions = Apollo.BaseMutationOptions< ILoginUserMutation, ILoginUserMutationVariables >; export const CreateUserDocument = gql` mutation CreateUser($username: String!, $email: String!, $password: String!) { createUser(username: $username, email: $email, password: $password) { token } } `; export type ICreateUserMutationFn = Apollo.MutationFunction< ICreateUserMutation, ICreateUserMutationVariables >; /** * __useCreateUserMutation__ * * To run a mutation, you first call `useCreateUserMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useCreateUserMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [createUserMutation, { data, loading, error }] = useCreateUserMutation({ * variables: { * username: // value for 'username' * email: // value for 'email' * password: // value for 'password' * }, * }); */ export function useCreateUserMutation( baseOptions?: Apollo.MutationHookOptions< ICreateUserMutation, ICreateUserMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions }; return Apollo.useMutation<ICreateUserMutation, ICreateUserMutationVariables>( CreateUserDocument, options ); } export type CreateUserMutationHookResult = ReturnType<typeof useCreateUserMutation>; export type CreateUserMutationResult = Apollo.MutationResult<ICreateUserMutation>; export type CreateUserMutationOptions = Apollo.BaseMutationOptions< ICreateUserMutation, ICreateUserMutationVariables >; export const UpdateUserSettingsDocument = gql` mutation UpdateUserSettings($settings: UserSettingsInput!) { updateUserSettings(settings: $settings) { username email } } `; export type IUpdateUserSettingsMutationFn = Apollo.MutationFunction< IUpdateUserSettingsMutation, IUpdateUserSettingsMutationVariables >; /** * __useUpdateUserSettingsMutation__ * * To run a mutation, you first call `useUpdateUserSettingsMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useUpdateUserSettingsMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [updateUserSettingsMutation, { data, loading, error }] = useUpdateUserSettingsMutation({ * variables: { * settings: // value for 'settings' * }, * }); */ export function useUpdateUserSettingsMutation( baseOptions?: Apollo.MutationHookOptions< IUpdateUserSettingsMutation, IUpdateUserSettingsMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions }; return Apollo.useMutation< IUpdateUserSettingsMutation, IUpdateUserSettingsMutationVariables >(UpdateUserSettingsDocument, options); } export type UpdateUserSettingsMutationHookResult = ReturnType< typeof useUpdateUserSettingsMutation >; export type UpdateUserSettingsMutationResult = Apollo.MutationResult<IUpdateUserSettingsMutation>; export type UpdateUserSettingsMutationOptions = Apollo.BaseMutationOptions< IUpdateUserSettingsMutation, IUpdateUserSettingsMutationVariables >; export const UpdatePasswordDocument = gql` mutation UpdatePassword($current: String!, $newPassword: String!) { updatePassword(currentPassword: $current, newPassword: $newPassword) { token } } `; export type IUpdatePasswordMutationFn = Apollo.MutationFunction< IUpdatePasswordMutation, IUpdatePasswordMutationVariables >; /** * __useUpdatePasswordMutation__ * * To run a mutation, you first call `useUpdatePasswordMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useUpdatePasswordMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [updatePasswordMutation, { data, loading, error }] = useUpdatePasswordMutation({ * variables: { * current: // value for 'current' * newPassword: // value for 'newPassword' * }, * }); */ export function useUpdatePasswordMutation( baseOptions?: Apollo.MutationHookOptions< IUpdatePasswordMutation, IUpdatePasswordMutationVariables > ) { const options = { ...defaultOptions, ...baseOptions }; return Apollo.useMutation< IUpdatePasswordMutation, IUpdatePasswordMutationVariables >(UpdatePasswordDocument, options); } export type UpdatePasswordMutationHookResult = ReturnType< typeof useUpdatePasswordMutation >; export type UpdatePasswordMutationResult = Apollo.MutationResult<IUpdatePasswordMutation>; export type UpdatePasswordMutationOptions = Apollo.BaseMutationOptions< IUpdatePasswordMutation, IUpdatePasswordMutationVariables >; export const IsMeDocument = gql` query IsMe { me { token } } `; /** * __useIsMeQuery__ * * To run a query within a React component, call `useIsMeQuery` and pass it any options that fit your needs. * When your component renders, `useIsMeQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useIsMeQuery({ * variables: { * }, * }); */ export function useIsMeQuery( baseOptions?: Apollo.QueryHookOptions<IIsMeQuery, IIsMeQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions }; return Apollo.useQuery<IIsMeQuery, IIsMeQueryVariables>(IsMeDocument, options); } export function useIsMeLazyQuery( baseOptions?: Apollo.LazyQueryHookOptions<IIsMeQuery, IIsMeQueryVariables> ) { const options = { ...defaultOptions, ...baseOptions }; return Apollo.useLazyQuery<IIsMeQuery, IIsMeQueryVariables>(IsMeDocument, options); } export type IsMeQueryHookResult = ReturnType<typeof useIsMeQuery>; export type IsMeLazyQueryHookResult = ReturnType<typeof useIsMeLazyQuery>; export type IsMeQueryResult = Apollo.QueryResult<IIsMeQuery, IIsMeQueryVariables>;
the_stack
import { Input, Model, Value } from '@contember/schema' import { Mapper } from '../Mapper' import { UpdateBuilder } from './UpdateBuilder' import { UpdateInputProcessor } from '../../inputProcessing' import * as Context from '../../inputProcessing' import { ConstraintType, getInsertPrimary, MutationConstraintViolationError, MutationEntryNotFoundError, MutationNothingToDo, MutationResultList, MutationResultType, NothingToDoReason, } from '../Result' import { hasManyProcessor, hasOneProcessor } from '../MutationProcessorHelper' import { AbortUpdate } from './Updater' import { ImplementationException } from '../../exception' import { CheckedPrimary } from '../CheckedPrimary' export class SqlUpdateInputProcessor implements UpdateInputProcessor<MutationResultList> { constructor( private readonly primaryValue: Input.PrimaryValue, private readonly data: Input.UpdateDataInput, private readonly updateBuilder: UpdateBuilder, private readonly mapper: Mapper, ) {} public column({ entity, column }: Context.ColumnContext) { if (this.data[column.name] !== undefined) { this.updateBuilder.addFieldValue(column.name, this.data[column.name] as Value.AtomicValue) } return Promise.resolve([]) } manyHasManyInverse: UpdateInputProcessor<MutationResultList>['manyHasManyInverse'] = { connect: hasManyProcessor(async ({ targetEntity, targetRelation, input, entity }) => { const primaryValue = await this.mapper.getPrimaryValue(targetEntity, input) if (!primaryValue) { return [new MutationEntryNotFoundError([], input)] } return await this.mapper.connectJunction(targetEntity, targetRelation, primaryValue, this.primaryValue) }), create: hasManyProcessor(async ({ targetEntity, targetRelation, input, entity }) => { const insertResult = await this.mapper.insert(targetEntity, input) const primaryValue = getInsertPrimary(insertResult) if (!primaryValue) { return insertResult } return await this.mapper.connectJunction(targetEntity, targetRelation, primaryValue, this.primaryValue) }), update: hasManyProcessor(async ({ targetEntity, targetRelation, input: { where, data }, entity }) => { const primary = await this.mapper.getPrimaryValue(targetEntity, where) if (!primary) { return [new MutationEntryNotFoundError([], where)] } return [ ...(await this.mapper.update(targetEntity, { [targetEntity.primary]: primary }, data)), ...(await this.mapper.connectJunction(targetEntity, targetRelation, primary, this.primaryValue)), ] }), upsert: hasManyProcessor(async ({ targetEntity, targetRelation, input: { where, update, create }, entity }) => { const primary = await this.mapper.getPrimaryValue(targetEntity, where) if (primary) { const updateResult = await this.mapper.update(targetEntity, { [targetEntity.primary]: primary }, update) const connectResult = await this.mapper.connectJunction( targetEntity, targetRelation, primary, this.primaryValue, ) return [...updateResult, ...connectResult] } else { const insertResult = await this.mapper.insert(targetEntity, create) const primaryValue = getInsertPrimary(insertResult) if (!primaryValue) { return insertResult } const connectResult = await this.mapper.connectJunction( targetEntity, targetRelation, primaryValue, this.primaryValue, ) return [...insertResult, ...connectResult] } }), delete: hasManyProcessor(async ({ targetEntity, input }) => { return await this.mapper.delete(targetEntity, input) }), disconnect: hasManyProcessor(async ({ targetEntity, targetRelation, input, entity }) => { const primaryValue = await this.mapper.getPrimaryValue(targetEntity, input) if (!primaryValue) { return [new MutationEntryNotFoundError([], input)] } return await this.mapper.disconnectJunction(targetEntity, targetRelation, primaryValue, this.primaryValue) }), } manyHasManyOwning: UpdateInputProcessor<MutationResultList>['manyHasManyOwning'] = { connect: hasManyProcessor(async ({ input, entity, relation, targetEntity }) => { const primaryValue = await this.mapper.getPrimaryValue(targetEntity, input) if (!primaryValue) { return [new MutationEntryNotFoundError([], input)] } return await this.mapper.connectJunction(entity, relation, this.primaryValue, primaryValue) }), create: hasManyProcessor(async ({ targetEntity, input, entity, relation }) => { const insertResult = await this.mapper.insert(targetEntity, input) const insertPrimary = getInsertPrimary(insertResult) if (!insertPrimary) { return insertResult } return [ ...insertResult, ...(await this.mapper.connectJunction(entity, relation, this.primaryValue, insertPrimary)), ] }), update: hasManyProcessor(async ({ targetEntity, input: { where, data }, entity, relation }) => { const primary = await this.mapper.getPrimaryValue(targetEntity, where) if (!primary) { return [new MutationEntryNotFoundError([], where)] } return [ ...(await this.mapper.update(targetEntity, { [targetEntity.primary]: primary }, data)), ...(await this.mapper.connectJunction(entity, relation, this.primaryValue, primary)), ] }), upsert: hasManyProcessor(async ({ targetEntity, input: { where, update, create }, entity, relation }) => { const primary = await this.mapper.getPrimaryValue(targetEntity, where) if (primary) { const updateResult = await this.mapper.update(targetEntity, { [targetEntity.primary]: primary }, update) const connectResult = await this.mapper.connectJunction(entity, relation, this.primaryValue, primary) return [...updateResult, ...connectResult] } else { const insertResult = await this.mapper.insert(targetEntity, create) const primaryValue = getInsertPrimary(insertResult) if (!primaryValue) { return insertResult } const connectResult = await this.mapper.connectJunction(entity, relation, this.primaryValue, primaryValue) return [...insertResult, ...connectResult] } }), delete: hasManyProcessor(async ({ targetEntity, input }) => { return await this.mapper.delete(targetEntity, input) }), disconnect: hasManyProcessor(async ({ input, entity, relation, targetEntity }) => { const primaryValue = await this.mapper.getPrimaryValue(targetEntity, input) if (!primaryValue) { return [new MutationEntryNotFoundError([], input)] } return await this.mapper.disconnectJunction(entity, relation, this.primaryValue, primaryValue) }), } manyHasOne: UpdateInputProcessor<MutationResultList>['manyHasOne'] = { connect: hasOneProcessor(async ({ targetEntity, input, relation }) => { const primaryValue = this.mapper.getPrimaryValue(targetEntity, input) this.updateBuilder.addFieldValue(relation.name, async () => { const value = await primaryValue if (!value) { return AbortUpdate } return value }) if (!(await primaryValue)) { return [new MutationEntryNotFoundError([], input)] } return [] }), create: hasOneProcessor(async ({ targetEntity, input, relation }) => { // intentionally no await here const insert = this.mapper.insert(targetEntity, input) this.updateBuilder.addFieldValue(relation.name, async () => { const insertResult = await insert const value = getInsertPrimary(insertResult) if (!value) { return AbortUpdate } return value }) return await insert }), update: hasOneProcessor(async ({ targetEntity, input, entity, relation }) => { const inversePrimary = await this.mapper.selectField( entity, { [entity.primary]: this.primaryValue }, relation.name, ) if (!inversePrimary) { return [new MutationNothingToDo([], NothingToDoReason.emptyRelation)] } return await this.mapper.update(targetEntity, { [targetEntity.primary]: inversePrimary }, input) }), upsert: hasOneProcessor(async ({ targetEntity, input: { create, update }, entity, relation }) => { const select = this.mapper.selectField(entity, { [entity.primary]: this.primaryValue }, relation.name) const result: MutationResultList = [] // addFieldValue has to be called immediately await this.updateBuilder.addFieldValue(relation.name, async () => { const primary = await select if (primary) { return undefined } const insertResult = await this.mapper.insert(targetEntity, create) const insertPrimary = getInsertPrimary(insertResult) if (insertPrimary) { return insertPrimary } result.push(...insertResult) return AbortUpdate }) const inversePrimary = await select if (inversePrimary) { return await this.mapper.update(targetEntity, { [targetEntity.primary]: inversePrimary }, update) } else { return result } }), delete: hasOneProcessor(async ({ targetEntity, entity, relation }) => { if (!relation.nullable && relation.joiningColumn.onDelete !== Model.OnDelete.cascade) { return [new MutationConstraintViolationError([], ConstraintType.notNull)] } if (relation.joiningColumn.onDelete === Model.OnDelete.restrict) { // eslint-disable-next-line no-console console.error( '[DEPRECATED] You are deleting an entity over the relation where onDelete behaviour is set to restrict. This will fail in next version.', ) this.updateBuilder.addFieldValue(relation.name, null) } const inversePrimary = await this.mapper.selectField( entity, { [entity.primary]: this.primaryValue }, relation.name, ) await this.updateBuilder.update return await this.mapper.delete(targetEntity, { [targetEntity.primary]: inversePrimary }) }), disconnect: hasOneProcessor(async ({ entity, relation }) => { if (!relation.nullable) { return [new MutationConstraintViolationError([], ConstraintType.notNull)] } this.updateBuilder.addFieldValue(relation.name, null) return [] }), } oneHasMany: UpdateInputProcessor<MutationResultList>['oneHasMany'] = { connect: hasManyProcessor(async ({ targetEntity, targetRelation, input, entity }) => { return await this.mapper.update(targetEntity, input, { [targetRelation.name]: { connect: { [entity.primary]: this.primaryValue } }, }) }), create: hasManyProcessor(async ({ targetEntity, targetRelation, input, entity }) => { return await this.mapper.insert(targetEntity, { ...input, [targetRelation.name]: { connect: { [entity.primary]: this.primaryValue } }, }) }), update: hasManyProcessor(async ({ targetEntity, targetRelation, input: { where, data }, entity }) => { return await this.mapper.update( targetEntity, { ...where, [targetRelation.name]: { [entity.primary]: this.primaryValue } }, { ...data, // [targetRelation.name]: {connect: thisPrimary} }, ) }), upsert: hasManyProcessor(async ({ targetEntity, targetRelation, input: { create, where, update }, entity }) => { const result = await this.mapper.update( targetEntity, { ...where, [targetRelation.name]: { [entity.primary]: this.primaryValue } }, { ...update, // [targetRelation.name]: {connect: thisPrimary} }, ) if (result[0].result === MutationResultType.notFoundError) { return await this.mapper.insert(targetEntity, { ...create, [targetRelation.name]: { connect: { [entity.primary]: this.primaryValue } }, }) } return result }), delete: hasManyProcessor(async ({ targetEntity, targetRelation, input, entity }) => { return await this.mapper.delete(targetEntity, { ...input, [targetRelation.name]: { [entity.primary]: this.primaryValue }, }) }), disconnect: hasManyProcessor(async ({ targetEntity, targetRelation, input, entity }) => { return await this.mapper.update( targetEntity, { ...input, [targetRelation.name]: { [entity.primary]: this.primaryValue } }, { [targetRelation.name]: { disconnect: true } }, ) }), } oneHasOneInverse: UpdateInputProcessor<MutationResultList>['oneHasOneInverse'] = { connect: hasOneProcessor(async ({ targetEntity, targetRelation, input, entity }) => { return await this.mapper.update(targetEntity, input, { [targetRelation.name]: { connect: { [entity.primary]: this.primaryValue } }, }) }), create: hasOneProcessor(async ({ targetEntity, targetRelation, input, entity }) => { return [ ...( await this.mapper.update( targetEntity, { [targetRelation.name]: { [entity.primary]: this.primaryValue } }, { [targetRelation.name]: { disconnect: true } }, ) ).filter(it => it.result !== MutationResultType.notFoundError), ...(await this.mapper.insert(targetEntity, { ...input, [targetRelation.name]: { connect: { [entity.primary]: this.primaryValue } }, })), ] }), update: hasOneProcessor(async ({ targetEntity, targetRelation, input, entity }) => { return await this.mapper.update( targetEntity, { [targetRelation.name]: { [entity.primary]: this.primaryValue } }, input, ) }), upsert: hasOneProcessor(async ({ targetEntity, targetRelation, input: { create, update }, entity }) => { const result = await this.mapper.update( targetEntity, { [targetRelation.name]: { [entity.primary]: this.primaryValue } }, update, ) if (result[0].result === MutationResultType.notFoundError) { return await this.mapper.insert(targetEntity, { ...create, [targetRelation.name]: { connect: { [entity.primary]: this.primaryValue } }, }) } return result }), delete: hasOneProcessor(async ({ targetEntity, targetRelation, entity, relation }) => { if (!relation.nullable) { return [new MutationConstraintViolationError([], ConstraintType.notNull)] } return await this.mapper.delete(targetEntity, { [targetRelation.name]: { [entity.primary]: this.primaryValue } }) }), disconnect: hasOneProcessor(async ({ targetEntity, targetRelation, entity, relation }) => { if (!relation.nullable) { return [new MutationConstraintViolationError([], ConstraintType.notNull)] } return await this.mapper.update( targetEntity, { [targetRelation.name]: { [entity.primary]: this.primaryValue } }, { [targetRelation.name]: { disconnect: true } }, ) }), } oneHasOneOwning: UpdateInputProcessor<MutationResultList>['oneHasOneOwning'] = { connect: hasOneProcessor(async ({ targetEntity, input, entity, relation, targetRelation }) => { const result: MutationResultList = [] await this.updateBuilder.addFieldValue(relation.name, async () => { const targetPrimary = (await this.mapper.getPrimaryValue(targetEntity, input)) as Input.PrimaryValue if (!targetPrimary) { result.push(new MutationEntryNotFoundError([], input)) return AbortUpdate } const currentOwnerOfTarget = await this.mapper.getPrimaryValue(entity, { [relation.name]: { [targetEntity.primary]: targetPrimary }, }) if (currentOwnerOfTarget === this.primaryValue) { // same owner, nothing to do return undefined } if (targetRelation && !targetRelation.nullable) { const currentTargetPrimary = await this.mapper.selectField( entity, { [entity.primary]: this.primaryValue }, relation.name, ) if (currentTargetPrimary === targetPrimary) { // should be already handled in a currentOwnerOfTarget === this.primaryValue branch throw new ImplementationException() } if (currentTargetPrimary) { result.push(new MutationConstraintViolationError([], ConstraintType.uniqueKey)) return AbortUpdate } } if (currentOwnerOfTarget) { if (!relation.nullable) { result.push(new MutationConstraintViolationError([], ConstraintType.notNull)) return AbortUpdate } result.push( ...(await this.mapper.updateInternal( entity, { [entity.primary]: currentOwnerOfTarget, }, [relation.name], builder => { builder.addFieldValue(relation.name, null) }, )), ) } return targetPrimary }) return result }), create: hasOneProcessor(async ({ targetEntity, input, relation, entity, targetRelation }) => { const insert = this.mapper.insert(targetEntity, input) const result: MutationResultList = [] this.updateBuilder.addFieldValue(relation.name, async () => { if (targetRelation && !targetRelation.nullable) { const currentTargetPrimary = await this.mapper.selectField( entity, { [entity.primary]: this.primaryValue }, relation.name, ) if (currentTargetPrimary) { result.push(new MutationConstraintViolationError([], ConstraintType.uniqueKey)) return AbortUpdate } } const insertResult = await insert const insertPrimary = getInsertPrimary(insertResult) if (insertPrimary) { return insertPrimary } return AbortUpdate }) result.push(...(await insert)) return result }), update: hasOneProcessor(async ({ targetEntity, input, entity, relation }) => { const inversePrimary = await this.mapper.selectField( entity, { [entity.primary]: this.primaryValue }, relation.name, ) if (!inversePrimary) { return [new MutationNothingToDo([], NothingToDoReason.emptyRelation)] } return await this.mapper.update(targetEntity, { [targetEntity.primary]: inversePrimary }, input) }), upsert: hasOneProcessor(async ({ targetEntity, input: { create, update }, entity, relation }) => { const select = this.mapper.selectField(entity, { [entity.primary]: this.primaryValue }, relation.name) const result: MutationResultList = [] //addColumnData has to be called synchronously await this.updateBuilder.addFieldValue(relation.name, async () => { const primary = await select if (primary) { return undefined } const insertResult = await this.mapper.insert(targetEntity, create) const insertPrimary = getInsertPrimary(insertResult) if (insertPrimary) { return insertPrimary } result.push(...insertResult) return AbortUpdate }) const inversePrimary = await select if (inversePrimary) { return await this.mapper.update(targetEntity, { [targetEntity.primary]: inversePrimary }, update) } return result }), delete: hasOneProcessor(async ({ targetEntity, entity, relation }) => { if (!relation.nullable && relation.joiningColumn.onDelete !== Model.OnDelete.cascade) { return [new MutationConstraintViolationError([], ConstraintType.notNull)] } if (relation.joiningColumn.onDelete === Model.OnDelete.restrict) { // eslint-disable-next-line no-console console.error( '[DEPRECATED] You are deleting an entity over the relation where onDelete behaviour is set to restrict. This will fail in next version.', ) this.updateBuilder.addFieldValue(relation.name, null) } const targetPrimary = await this.mapper.selectField( entity, { [entity.primary]: this.primaryValue }, relation.name, ) if (!targetPrimary) { return [new MutationNothingToDo([], NothingToDoReason.emptyRelation)] } await this.updateBuilder.update return await this.mapper.delete(targetEntity, new CheckedPrimary(targetPrimary)) }), disconnect: hasOneProcessor(async ({ entity, relation, targetRelation, input }) => { if (!relation.nullable) { return [new MutationConstraintViolationError([], ConstraintType.notNull)] } if (targetRelation && !targetRelation.nullable) { const targetPrimary = await this.mapper.selectField( entity, { [entity.primary]: this.primaryValue }, relation.name, ) if (targetPrimary) { return [new MutationConstraintViolationError([], ConstraintType.notNull)] } } this.updateBuilder.addFieldValue(relation.name, null) return [] }), } }
the_stack
import { MochaJSDelegate } from './MochaJSDelegate'; import { uuidv4, coscriptKeepAround, coscriptNotKeepAround } from './keepAround'; import { logger } from '../meaxure/common/logger'; import { meaxure, wrapWebViewScripts } from './webviewScripts'; import { dispatchFirstClick } from './dispatchFirstClick'; export interface WebviewPanelOptions { identifier?: string, url: string, width: number, height: number, hideCloseButton?: boolean, acceptsFirstMouse?: boolean, } interface Webview { windowScriptObject(): any; mainFrameURL(); } interface PanelMessageBase<T> { __MESSAGE_TYPE__: string; __MESSAGE_SUCCESS__?: boolean; message: T; } interface PanelServerMessage<T> extends PanelMessageBase<T> { __SERVER_MESSAGE_ID__: string; } interface PanelClientMessage<T> extends PanelMessageBase<T> { __CLIENT_MESSAGE_ID__: string; } export function createWebviewPanel(options: WebviewPanelOptions): WebviewPanel { let panel = new WebviewPanel(options); if (!panel.panel) return undefined; return panel; } const BACKGROUND_COLOR = NSColor.colorWithRed_green_blue_alpha(0.13, 0.13, 0.13, 1); const BACKGROUND_COLOR_TITLE = NSColor.colorWithRed_green_blue_alpha(0.1, 0.1, 0.1, 1); export class WebviewPanel { private _panel: any; private _webview: Webview; private _options: WebviewPanelOptions; private _isModal: boolean; private _threadDictionary: any; private _keepAroundID: any; private _DOMReadyListener: (...args) => void; private _closeListener: (...args) => void private _messageListeners: { [key: string]: (data: any) => any } = {}; private _replyListeners: { [key: string]: (success: boolean, data: any) => void } = {}; constructor(options: WebviewPanelOptions) { if (options.identifier) { this._threadDictionary = NSThread.mainThread().threadDictionary(); if (this._threadDictionary[options.identifier]) { return undefined; } } this._keepAroundID = uuidv4(); this._options = Object.assign({ width: 240, height: 320, hideCloseButton: false, data: {}, }, options); if (!NSFileManager.defaultManager().fileExistsAtPath(this._options.url)) throw "file not found: " + this._options.url; this._panel = this._createPanel(); this._webview = this._createWebview(); this._initPanelViews(this._panel, this._webview); if (this._options.identifier) { this._threadDictionary[this._options.identifier] = this; } } get panel(): any { return this._panel; } get webview(): any { return this._webview; } /** * close the panel */ close() { if (this._isModal) { this._panel.orderOut(nil); NSApp.stopModal(); return; } this._panel.close(); // afterClose will be called by windowWillClose delegte // this.afterClose() } private afterClose() { if (this._options.identifier) { this._threadDictionary.removeObjectForKey(this._options.identifier); } if (this._closeListener) { this._closeListener(); } if (!this._isModal) { coscriptNotKeepAround(this._keepAroundID); } } /** * Show panel as modal */ showModal() { this._isModal = true; NSApp.runModalForWindow(this._panel); } /** * Show panel */ show() { this._isModal = false; this._panel.becomeKeyWindow(); this._panel.setLevel(NSFloatingWindowLevel); this._panel.center(); this._panel.makeKeyAndOrderFront(nil); coscriptKeepAround(this._keepAroundID); } /** * Post a message to webview, and get reply with promise. * If no reply handler registered in webview, we get undefined reply. * @param msg the msg to post */ postMessage<T>(type: string, msg: T): Promise<T> { let requestID = uuidv4(); let promise = new Promise<T>((resolve, reject) => { this._registerReplyListener(requestID, resolve, reject); }); this._postData<PanelServerMessage<T>>({ __SERVER_MESSAGE_ID__: requestID, __MESSAGE_TYPE__: type, message: msg, }); return promise; } /** * evaluate script in webview and get its return value with promise * @param script the script to run */ evaluateWebScript<T>(script: string): Promise<T> { let windowObject = this._webview.windowScriptObject(); let requestID = uuidv4(); let scriptWrapped = wrapWebViewScripts(script, requestID); // alert(scriptWrapped); let promise = new Promise<T>((resolve, reject) => { this._registerReplyListener(requestID, resolve, reject); }); windowObject.evaluateWebScript(scriptWrapped); return promise; } /** * register a response function to specific request * @param reply the function replies to the message * @param msgType to what type of request the function replies to. */ onDidReceiveMessage<T>(msgType: string, reply: (data: T) => any) { if (!msgType) msgType = ""; this._messageListeners[msgType] = reply; } /** * register a callback runs when the webview DOM is ready * @param callback */ onWebviewDOMReady<T>(callback: (webView, webFrame) => void) { this._DOMReadyListener = _tryCatchListener(callback); } /** * register a callback runs when the panel is closed * @param callback */ onClose(callback: () => void) { this._closeListener = _tryCatchListener(callback); } private _createPanel(): any { const TITLE_HEIGHT = 24; let frame = NSMakeRect(0, 0, this._options.width, (this._options.height + TITLE_HEIGHT)); let panel = NSPanel.alloc().init(); // panel.setTitleVisibility(NSWindowTitleHidden); panel.setTitlebarAppearsTransparent(true); panel.standardWindowButton(NSWindowCloseButton).setHidden(this._options.hideCloseButton); panel.standardWindowButton(NSWindowMiniaturizeButton).setHidden(true); panel.standardWindowButton(NSWindowZoomButton).setHidden(true); panel.setFrame_display(frame, false); panel.setBackgroundColor(BACKGROUND_COLOR); let contentView = panel.contentView(); let titlebarView = contentView.superview().titlebarViewController().view(); let titlebarContainerView = titlebarView.superview(); titlebarContainerView.setFrame(NSMakeRect(0, this._options.height, this._options.width, TITLE_HEIGHT)); titlebarView.setFrameSize(NSMakeSize(this._options.width, TITLE_HEIGHT)); titlebarView.setTransparent(true); titlebarView.setBackgroundColor(BACKGROUND_COLOR_TITLE); titlebarContainerView.superview().setBackgroundColor(BACKGROUND_COLOR_TITLE); let closeButton = panel.standardWindowButton(NSWindowCloseButton); closeButton.setFrameOrigin(NSMakePoint(8, 4)); // https://github.com/skpm/sketch-module-web-view/blob/master/lib/set-delegates.js#L97 let delegate = new MochaJSDelegate({ 'windowWillClose:': (sender) => { this.afterClose(); }, 'windowDidBecomeKey:': () => { if (!this._options.acceptsFirstMouse) return; let event = this._panel.currentEvent(); dispatchFirstClick(this, event); }, }); panel.setDelegate(delegate.getClassInstance()) return panel; } private _createWebview(): Webview { let webView = WebView.alloc().initWithFrame(NSMakeRect(0, 0, this._options.width, this._options.height)); let windowObject = webView.windowScriptObject(); let delegate = new MochaJSDelegate({ // https://developer.apple.com/documentation/webkit/webframeloaddelegate?language=objc "webView:didCommitLoadForFrame:": (webView, webFrame) => { windowObject.evaluateWebScript(meaxure); }, "webView:didFinishLoadForFrame:": (webView, webFrame) => { if (this._DOMReadyListener) { this._DOMReadyListener(webView, webFrame); } }, "webView:didChangeLocationWithinPageForFrame:": (webView, webFrame) => { let data = JSON.parse(windowObject.valueForKey("_MeaxurePostedData")); this._dispatchMessage(data); } }); webView.setBackgroundColor(BACKGROUND_COLOR); webView.setFrameLoadDelegate_(delegate.getClassInstance()); webView.setMainFrameURL_(this._options.url); return webView; } private _dispatchMessage(data: any): void { if (data.__SERVER_MESSAGE_ID__ !== undefined) { // reply message of server-to-client request // logger.debug('A reply of server request recieved.'); let reply = data as PanelServerMessage<any>; let callback = this._replyListeners[reply.__SERVER_MESSAGE_ID__]; callback(reply.__MESSAGE_SUCCESS__, reply.message); delete this._replyListeners[reply.__SERVER_MESSAGE_ID__]; return; } if (data.__CLIENT_MESSAGE_ID__ !== undefined) { // request message of client-to-server request let request = data as PanelClientMessage<any>; let requestType = request.__MESSAGE_TYPE__; if (!requestType) requestType = ''; // logger.debug('A "' + requestType + '" request from client recieved.'); let callback = this._messageListeners[requestType]; let response: any = undefined; let success = true; if (callback) { try { response = callback(request.message); } catch (error) { success = false; response = error; logger.error(error) } } this._replyRequest(request, success, response); } } private _initPanelViews(panel, webView) { let contentView = panel.contentView(); contentView.setWantsLayer(true); contentView.layer().setFrame(contentView.frame()); contentView.layer().setCornerRadius(6); contentView.layer().setMasksToBounds(true); contentView.addSubview(webView); } private _postData<T>(data: T): void { let windowObject = this._webview.windowScriptObject(); let script = ` meaxure.raiseReceiveMessageEvent("${encodeURIComponent(JSON.stringify(data))}"); ` windowObject.evaluateWebScript(script); } private _replyRequest<T>(request: PanelClientMessage<any>, success: boolean, response: T) { return this._postData(<PanelClientMessage<any>>{ __CLIENT_MESSAGE_ID__: request.__CLIENT_MESSAGE_ID__, __MESSAGE_SUCCESS__: success, message: response, }); } private _registerReplyListener<T>( requestID: string, resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void, ) { this._replyListeners[requestID] = function (success: boolean, msg: any) { if (success) { resolve(msg); return; } reject(msg); } setTimeout(() => { let callback = this._replyListeners[requestID]; if (!callback) return; // reject the promise after timeout, // or the coascript waits for them, // like always set 'coscript.setShouldKeepAround(true)' callback( false, 'A WebviewPanel server-to-client message not replied in 10 seconds.' ); delete this._replyListeners[requestID]; }, 10000); } } function _tryCatchListener(fn: Function) { return function (...args): void { try { fn(...args); } catch (error) { logger.error(error); } } }
the_stack
import * as path from 'path'; import * as fsx from 'fs-extra'; import * as klaw from 'klaw'; import * as BBPromise from 'bluebird'; import * as optional from 'optional-js'; import * as _ from 'lodash'; import { ForceIgnore } from '@salesforce/source-deploy-retrieve/lib/src/metadata-registry/forceIgnore'; import { fs as fsCore, SfdxError } from '@salesforce/core'; import * as Force from '../core/force'; import * as almError from '../core/almError'; import logger = require('../core/logApi'); const glob = BBPromise.promisify(require('glob')); import Messages = require('../messages'); import { WaveTemplateBundleMetadataType } from './metadataTypeImpl/waveTemplateBundleMetadataType'; import { AuraDefinitionBundleMetadataType } from './metadataTypeImpl/auraDefinitionBundleMetadataType'; import MetadataRegistry = require('./metadataRegistry'); const messages = Messages(); import { toReadableState } from './workspaceFileState'; import { parseToManifestEntriesArray } from './parseManifestEntriesArray'; import { MetadataTypeFactory } from './metadataTypeFactory'; import { LightningComponentBundleMetadataType } from './metadataTypeImpl/lightningComponentBundleMetadataType'; import { SourceWorkspaceAdapter } from './sourceWorkspaceAdapter'; import { ManifestEntry } from './types'; import { getFileName } from './sourcePathUtil'; import { AggregateSourceElements } from './aggregateSourceElements'; const fsx_ensureDir = BBPromise.promisify(fsx.ensureDir); /** * Helper to normalize a path * * @param {string} targetValue - the raw path * @returns {string} - a trimmed path without a trailing slash. * @private */ const _normalizePath = function (targetValue) { let localTargetValue = targetValue.trim(); if (localTargetValue.endsWith(path.sep)) { localTargetValue = localTargetValue.substr(0, localTargetValue.length - 1); } return path.resolve(localTargetValue); }; /** * Process a file from the metadata package. * * @param {object} typeDef - object type from the metadata registry * @param {string} pathWithPackage - the filepath including the metadata package * @param {string} fullName - the computed full name @see _getFullName * @param sourceWorkspaceAdapter - the org/source workspace adapter * @param {AggregateSourceElements} sourceElements - accumulator of created AggregateSourceElements * @private */ const _processFile = function ( metadataType, pathWithPackage, fullName, sourceWorkspaceAdapter, sourceElements: AggregateSourceElements ) { const fileProperties = { type: metadataType.getMetadataName(), fileName: pathWithPackage, fullName, }; const retrieveRoot = path.join(this._package_root, '..'); // Each Aura bundle has a definition file that has one of the suffixes: .app, .cmp, .design, .evt, etc. // In order to associate each sub-component of an aura bundle (e.g. controller, style, etc.) with // its parent aura definition type, we must find the parent's file properties // and pass those along to processMdapiFileProperty() const bundleDefinitionProperty = []; if (metadataType instanceof AuraDefinitionBundleMetadataType) { const definitionFileProperty = AuraDefinitionBundleMetadataType.getCorrespondingAuraDefinitionFileProperty( retrieveRoot, fileProperties.fileName, metadataType.getMetadataName(), sourceWorkspaceAdapter.metadataRegistry ); bundleDefinitionProperty.push(definitionFileProperty); } if (metadataType instanceof LightningComponentBundleMetadataType) { const metadataRegistry = sourceWorkspaceAdapter.metadataRegistry; const typeDefObj = metadataRegistry.getTypeDefinitionByMetadataName(metadataType.getMetadataName()); const bundle = new LightningComponentBundleMetadataType(typeDefObj); const definitionFileProperty = bundle.getCorrespondingLWCDefinitionFileProperty( retrieveRoot, fileProperties.fileName, metadataType.getMetadataName(), sourceWorkspaceAdapter.metadataRegistry ); bundleDefinitionProperty.push(definitionFileProperty); } if (metadataType instanceof WaveTemplateBundleMetadataType) { const definitionFileProperty = { type: metadataType.getMetadataName(), fileName: fileProperties.fileName, fullName, }; bundleDefinitionProperty.push(definitionFileProperty); } const element = sourceWorkspaceAdapter.processMdapiFileProperty( sourceElements, retrieveRoot, fileProperties, bundleDefinitionProperty ); if (!element) { this.logger.warn(`Unsupported type: ${metadataType.getMetadataName()} path: ${pathWithPackage}`); } }; /** * Process one file path within a metadata package directory * * @param {object} item - the path item * @param {object} metadataRegistry - describe metadata * @param {object} sourceWorkspaceAdapter - workspace adapter * @param {AggregateSourceElements} sourceElements - accumulator of created AggregateSourceElements * @private */ const _processPath = function ( item, metadataRegistry, sourceWorkspaceAdapter, sourceElements: AggregateSourceElements ) { const pkgRelativePath = path.relative(this._package_root, item.path); if (pkgRelativePath.length > 0) { // Ignore the package root itself const metadataType = MetadataTypeFactory.getMetadataTypeFromMdapiPackagePath(pkgRelativePath, metadataRegistry); if (metadataType) { if (!item.path.endsWith(MetadataRegistry.getMetadataFileExt()) || metadataType.isFolderType()) { const pathWithPackage = path.join(path.basename(this._package_root), pkgRelativePath); const fullName = metadataType.getAggregateFullNameFromMdapiPackagePath(pkgRelativePath); if (item.stats.isFile()) { _processFile.call(this, metadataType, pathWithPackage, fullName, sourceWorkspaceAdapter, sourceElements); } } else { if (metadataType.hasContent()) { const indexOfMetaExt: string = item.path.indexOf(MetadataRegistry.getMetadataFileExt()); const retrievedContentPath: string = item.path.substring(0, indexOfMetaExt); const throwMissingContentError = () => { const err = new Error(); err['name'] = 'Missing content file'; err['message'] = messages.getMessage('MissingContentFile', retrievedContentPath); throw err; }; // LightningComponentBundleMetadataTypes can have a .css or .js file as the main content // so check for both before erroring. if (metadataType instanceof LightningComponentBundleMetadataType) { const cssContentPath = retrievedContentPath.replace(/\.js$/, '.css'); if (!fsCore.existsSync(retrievedContentPath) && !fsCore.existsSync(cssContentPath)) { throwMissingContentError(); } } else { // Skipping content file validation for ExperienceBundle metadata type since it is // a special case and does not have a corresponding content file. if (metadataType.getMetadataName() !== 'ExperienceBundle' && !fsCore.existsSync(retrievedContentPath)) { throwMissingContentError(); } } } } } else { this.logger.warn(`The type definition cannot be found for ${item.path}`); } } }; /** * Converts an array of aggregateSourceElements into objects suitable for a return to the caller. * * @returns {[{state, fullName, type, filePath}]} */ const _mapToOutputElements = function (aggregateSourceElements: AggregateSourceElements) { let allWorkspaceElements = []; aggregateSourceElements.getAllSourceElements().forEach((aggregateSourceElement) => { allWorkspaceElements = allWorkspaceElements.concat(aggregateSourceElement.getWorkspaceElements()); }); return allWorkspaceElements.map((workspaceElement) => { const fullFilePath = workspaceElement.getSourcePath(); const paths = fullFilePath.split(this.projectPath); let filePath = paths[paths.length - 1]; // Remove the leading slash if (filePath && path.isAbsolute(filePath)) { filePath = filePath.substring(1); } return { fullName: workspaceElement.getFullName(), type: workspaceElement.getMetadataName(), filePath, state: toReadableState(workspaceElement.getState()), }; }); }; /** * Finds the filepath root containing the package.xml * * @private */ const _setPackageRoot = function () { const packageDotXmlPath = `${this.root}${path.sep}package.xml`; return glob(packageDotXmlPath).then((outerfiles) => { if (outerfiles.length > 0) { this._package_root = this.root; return BBPromise.resolve(); } else { const packageDotXmlGlobPath = `${this.root}${path.sep}**${path.sep}package.xml`; if (this.logger.isDebugEnabled()) { this.logger.debug(`Looking for package.xml here ${packageDotXmlGlobPath}`); } return glob(packageDotXmlGlobPath).then((innerfiles) => { if (innerfiles.length < 1) { const error = new Error(); error['code'] = 'ENOENT'; throw error; } this._package_root = path.dirname(innerfiles[0]); return BBPromise.resolve(); }); } }); }; /** * An api class for converting a source directory in mdapi package format into source compatible with an SFDX workspace. */ class MdapiConvertApi { // TODO: proper property typing // eslint-disable-next-line no-undef [property: string]: any; constructor(force?) { this.force = optional.ofNullable(force).orElse(new Force()); this.projectPath = this.force.getConfig().getProjectPath(); this._outputDirectory = this.force.getConfig().getAppConfig().defaultPackagePath; this.logger = logger.child('mdapiConvertApi'); } /** * @returns {string} the directory for the output */ get outputDirectory() { return this._outputDirectory; } /** * set the value of the output directory * * @param {string} outputDirectory - the new value of the output directory. */ set outputDirectory(outputDirectory) { if (_.isString(outputDirectory) && !_.isEmpty(outputDirectory)) { if (path.isAbsolute(outputDirectory)) { this._outputDirectory = path.relative(process.cwd(), outputDirectory); } else { this._outputDirectory = outputDirectory; } } else { throw almError('InvalidParameter', ['outputdir', outputDirectory]); } } /** * @returns {string} value of the root directory to convert. default to the project directory */ get root() { return this._root; } /** * set the value of the root directory to convert * * @param {string} sourceRootValue - a directory containing a package.xml file. Is should represents a valid mdapi * package. */ set root(sourceRootValue) { if (sourceRootValue && typeof sourceRootValue === 'string' && sourceRootValue.trim().length > 0) { this._root = _normalizePath(sourceRootValue); } else { throw almError('InvalidParameter', ['sourceRootValue', sourceRootValue]); } } isValidSourcePath(sourcePath) { const isValid = this.forceIgnore.accepts(sourcePath); // Skip directories/files beginning with '.' and that should be ignored return isValid && !path.basename(sourcePath).startsWith('.'); } /** * @param itemPath path of the metadata to convert * @param mdName name of metadata as given in -m parameter * @returns true if the file is a folder metadata type */ isFolder(itemPath, mdName?) { return mdName && itemPath.endsWith(`${path.sep}${mdName.split(path.sep)[0]}-meta.xml`); } /** * @param itemPath the path to the file in the local project * @param validMetatdata a filter against which the paths would be checked to see if the file needs to be converted * @param metadataRegistry {MetadataRegistry} * @returns { boolean} returns true if the path is valid path for covert */ checkMetadataFromType(itemPath: string, validMetatdata: string[], metadataRegistry: MetadataRegistry) { const typDef = metadataRegistry.getTypeDefinitionByFileName(itemPath); for (const md of validMetatdata) { const [mdType, mdName] = md.split(':'); if (!mdName && typDef) { if (mdType === typDef.metadataName) { return true; } } else if (mdName) { if (itemPath.includes(mdName) || this.isFolder(itemPath, mdName)) { return true; } } } return false; } /** * @param itemPath the path to the file in the local project * @param validMetatdata a filter against which the paths would be checked to see if the file needs to be converted */ checkMetadataFromPath(itemPath: string, validMetatdata: string[]): boolean { // eslint-disable-next-line @typescript-eslint/no-shadow for (const path of validMetatdata) { if (itemPath.includes(path)) { return true; } } return false; } /** * @param typeNamePairs type name pairs from manifest * @param itemPath the path to the file in the local project * @param metadataRegistry * @returns {boolean} true if the metadata type or, file name is present in the manifest */ checkMetadataFromManifest(typeNamePairs: ManifestEntry[], itemPath: string, metadataRegistry: MetadataRegistry) { const typDef = metadataRegistry.getTypeDefinitionByFileName(itemPath); const metadataName = getFileName(itemPath); let foundInManifest = false; typeNamePairs.forEach((entry: ManifestEntry) => { if (typDef && entry.name.includes('*') && foundInManifest === false) { if (typDef.metadataName === entry.type) { foundInManifest = true; } } if (metadataName === entry.name) { foundInManifest = true; } else if (itemPath.includes(entry.name)) { /** For folder type structure */ foundInManifest = true; } }); return foundInManifest; } /** * Returns a promise to convert a metadata api directory package into SFDX compatible source. * * @returns {BBPromise} */ convertSource(org, context?) { // Walk the metadata package elements. let validMetatdata; return org .resolveDefaultName() .then(() => fsx_ensureDir(this.root)) .then(() => fsx_ensureDir(this._outputDirectory)) .then(() => _setPackageRoot.call(this)) .then(() => { if (context) { if (context.manifest) { return parseToManifestEntriesArray(context.manifest); } if (context.metadata) { return context.metadata.split(','); } else if (context.metadatapath) { return context.metadatapath.split(','); } } }) .then((result) => { validMetatdata = result; return SourceWorkspaceAdapter.create({ org, metadataRegistryImpl: MetadataRegistry, defaultPackagePath: path.relative(this.projectPath, this.outputDirectory), fromConvert: true, }); }) .then((sourceWorkspaceAdapter: SourceWorkspaceAdapter) => { if (this.logger.isDebugEnabled()) { [ { name: 'root', value: this.root }, { name: 'outputdir', value: this._outputDirectory }, ].forEach((attribute) => { this.logger.debug(`Processing mdapi convert with ${attribute.name}: ${attribute.value}`); }); } this.logger.debug(`Processing mdapi convert with package root: ${this._package_root}`); const metadataRegistry = sourceWorkspaceAdapter.metadataRegistry; const aggregateSourceElements = new AggregateSourceElements(); this.forceIgnore = ForceIgnore.findAndCreate(this._package_root); // Use a "new" promise to block the promise chain until the source metadata package is processed. return new BBPromise((resolve, reject) => { let errorFoundProcessingPath = false; klaw(this._package_root) .on('data', (item) => { try { if (this.isValidSourcePath(item.path)) { if (!validMetatdata) { _processPath.call(this, item, metadataRegistry, sourceWorkspaceAdapter, aggregateSourceElements); } else if (context.metadatapath) { const isValidMetatadataPath = this.checkMetadataFromPath(item.path, validMetatdata); if (isValidMetatadataPath) { _processPath.call(this, item, metadataRegistry, sourceWorkspaceAdapter, aggregateSourceElements); } } else if (context.manifest) { const foundInManifest = this.checkMetadataFromManifest(validMetatdata, item.path, metadataRegistry); if (foundInManifest) { _processPath.call(this, item, metadataRegistry, sourceWorkspaceAdapter, aggregateSourceElements); } } else if (context.metadata) { const validMetatdataType = this.checkMetadataFromType(item.path, validMetatdata, metadataRegistry); if (validMetatdataType) { _processPath.call(this, item, metadataRegistry, sourceWorkspaceAdapter, aggregateSourceElements); } } } } catch (e) { this.logger.debug(e.message); errorFoundProcessingPath = true; if (e.name === 'Missing metadata file' || e.name === 'Missing content file') { reject(e); } else { const message = messages.getMessage('errorProcessingPath', [item.path], 'mdapiConvertApi'); const error = new SfdxError(message, 'errorProcessingPath', undefined, undefined, e); reject(error); } } }) // eslint-disable-next-line @typescript-eslint/no-misused-promises .on('end', async () => { if (!errorFoundProcessingPath && !aggregateSourceElements.isEmpty()) { await sourceWorkspaceAdapter.updateSource( aggregateSourceElements, undefined, true /** checkForDuplicates */, this.unsupportedMimeTypes ); if (this.logger.isDebugEnabled()) { const allPaths = []; aggregateSourceElements.getAllSourceElements().forEach((sourceElement) => { const workspaceElements = sourceElement.getWorkspaceElements(); workspaceElements.forEach((workspaceElement) => { allPaths.push(workspaceElement.getSourcePath()); }); }); this.logger.debug(allPaths); } } resolve(_mapToOutputElements.call(this, aggregateSourceElements)); }) .on('error', (err, item) => { reject(almError({ keyName: 'errorProcessingPath', bundle: 'mdapiConvertApi' }, [item.path])); }); }); }) .catch((err) => { // Catch invalid source package. if (err.code && err.code === 'ENOENT') { throw almError({ keyName: 'invalidPath', bundle: 'mdapiConvertApi' }); } else { throw err; } }); } } export = MdapiConvertApi;
the_stack
import rule from "./no-unsafe-mutable-readonly-assignment"; import { RuleTester } from "@typescript-eslint/experimental-utils/dist/ts-eslint"; import { AST_NODE_TYPES } from "@typescript-eslint/experimental-utils/dist/ts-estree"; const ruleTester = new RuleTester({ parserOptions: { sourceType: "module", project: "./tsconfig.tests.json", }, parser: require.resolve("@typescript-eslint/parser"), }); // eslint-disable-next-line functional/no-expression-statement ruleTester.run("no-unsafe-mutable-readonly-assignment", rule, { valid: [ /** * Call expressions */ // zero parameters { filename: "file.ts", code: ` const foo = () => { return undefined; }; foo(); `, }, // zero parameters with extra argument (TypeScript will catch this so we don't flag it) { filename: "file.ts", code: ` const foo = () => { return undefined; }; foo(""); `, }, // non-object parameter { filename: "file.ts", code: ` const foo = (a: string) => { return undefined; }; foo("a"); `, }, // missing arguments (TypeScript will catch this so we don't flag it) { filename: "file.ts", code: ` const foo = (a: string) => { return undefined; }; foo(); `, }, // readonly -> readonly (nested object; type doesn't change) { filename: "file.ts", code: ` type ReadonlyA = { readonly a: { readonly b: string } }; const func = (param: ReadonlyA): void => { return undefined; }; const readonlyA = { a: { b: "" } } as const; func(readonlyA); `, }, // mutable -> mutable (type doesn't change) { filename: "file.ts", code: ` type MutableA = {a: string}; const foo = (mut: MutableA) => { mut.a = "whoops"; }; const mut: MutableA = { a: "" }; foo(mut); `, }, // object literal -> mutable (no reference to object retained) { filename: "file.ts", code: ` type MutableA = {a: string}; const foo = (mut: MutableA) => { mut.a = "whoops"; }; foo({ a: "" }); `, }, // object literal -> mutable (mutable reference to property retained) { filename: "file.ts", code: ` type MutableB = { b: string }; type MutableA = { readonly a: MutableB }; const func = (param: MutableA): void => { return undefined; }; const b: MutableB = { b: "" }; func({ a: b } as const); `, }, // object literal -> readonly (readonly reference to property retained) { filename: "file.ts", code: ` type ReadonlyB = { readonly b: string }; type ReadonlyA = { readonly a: ReadonlyB }; const func = (param: ReadonlyA): void => { return undefined; }; const b: ReadonlyB = { b: "" } as const; func({ a: b } as const); `, }, // object literal -> readonly (no reference to object or its property retained) { filename: "file.ts", code: ` type ReadonlyB = { readonly b: string }; type ReadonlyA = { readonly a: ReadonlyB }; const func = (param: ReadonlyA): void => { return undefined; }; func({ a: { b: "" } } as const); `, }, // mutable (union) -> mutable { filename: "file.ts", code: ` type MutableA = {a: string}; const foo = (mut: MutableA) => { mut.a = "whoops"; }; const mut: MutableA | number = { a: "" }; foo(mut); `, }, // mutable -> mutable (union) { filename: "file.ts", code: ` type MutableA = {a: string}; const foo = (mut: MutableA | number): void => { return; }; const mut: MutableA = { a: "" }; foo(mut); `, }, // multiple type signatures (readonly -> readonly) { filename: "file.ts", code: ` type ReadonlyA = { readonly a: string }; export function func(a: number): number; export function func(a: ReadonlyA): ReadonlyA; export function func(a: any): any { return a; } const readonlyA: ReadonlyA = { a: "" } as const; func(readonlyA); `, }, // multiple type signatures (no matching signature) // we don't bother flagging this because TypeScript itself will catch it { filename: "file.ts", code: ` type ReadonlyA = { readonly a: string }; export function func(a: number): number; export function func(a: string): string; export function func(a: any): any { return a; } const readonlyA: ReadonlyA = { a: "" } as const; func(readonlyA); `, }, // readonly array concat. { filename: "file.ts", code: ` const arr: ReadonlyArray<never> = [] as const; const foo = arr.concat(arr, arr); `, }, // TODO: https://github.com/danielnixon/eslint-plugin-total-functions/issues/132 // // mutable array concat. // { // filename: "file.ts", // code: ` // const arr: Array<never> = []; // const foo = arr.concat(arr, arr); // `, // }, // // Mixed mutable and readonly array concat. // { // filename: "file.ts", // code: ` // const ro: ReadonlyArray<never> = [] as const; // const mut: Array<never> = []; // const foo = ro.concat(ro, mut); // `, // }, // mixed (union) -> mixed (union) // The readonlys align and mutables align, so no surprising mutation can arise. { filename: "file.ts", code: ` type MutableA = { a: string }; type ReadonlyB = { readonly b: string }; const func = (foo: MutableA | ReadonlyB): void => { return; }; const foo: MutableA | ReadonlyB = Date.now() > 0 ? { a: "" } : { b: "" } as const; func(foo); `, }, // readonly array of readonly object -> readonly array of readonly object { filename: "file.ts", code: ` type Obj = { readonly foo: string }; const foo = (a: ReadonlyArray<Obj>): number => a.length; const arr: ReadonlyArray<Obj> = [] as const; foo(arr); `, }, /** * Assignment expressions */ // TODO /** * Arrow functions */ // Arrow function (compact form) (readonly -> readonly) { filename: "file.ts", code: ` type ReadonlyA = { readonly a: string }; const ro: ReadonlyA = { a: "" } as const; const func = (): ReadonlyA => ro; `, }, // Arrow function (compact form) (object literal -> readonly) { filename: "file.ts", code: ` type ReadonlyA = { readonly a: string }; const func = (): ReadonlyA => ({ a: "" } as const); `, }, // Arrow function (compact form) (object literal -> mutable) { filename: "file.ts", code: ` type MutableA = { a: string }; const func = (): MutableA => { a: "" }; `, }, // Arrow function (compact form) (mutable -> mutable) { filename: "file.ts", code: ` type MutableA = { a: string }; const ro: MutableA = { a: "" }; const func = (): MutableA => ro; `, }, /** * type assertions */ // readonly -> readonly { filename: "file.ts", code: ` type ReadonlyA = { readonly a: string }; const ro: ReadonlyA = { a: "" } as const; const mut = ro as ReadonlyA; `, }, // mutable -> mutable { filename: "file.ts", code: ` type MutableA = { a: string }; const ro: MutableA = { a: "" }; const mut = ro as MutableA; `, }, // readonly -> readonly { filename: "file.ts", code: ` type ReadonlyA = { readonly a: string }; const ro: ReadonlyA = { a: "" } as const; const mut = <ReadonlyA>ro; `, }, // mutable -> mutable { filename: "file.ts", code: ` type MutableA = { a: string }; const ro: MutableA = { a: "" }; const mut = <MutableA>ro; `, }, // as const { filename: "file.ts", code: ` type ReadonlyA = { readonly a: string }; const ro: ReadonlyA = { a: "" } as const; `, }, // <const> { filename: "file.ts", code: ` type ReadonlyA = { readonly a: string }; const ro: ReadonlyA = <const>{ a: "" }; `, }, // as unknown { filename: "file.ts", code: ` const foo = [{ key: -1, label: "", value: "" }] as unknown; `, }, /** * Return statement */ // mutable -> mutable (function return) { filename: "file.ts", code: ` type MutableA = { a: string }; type ReadonlyA = { readonly a: string }; function foo(): MutableA { const ma: MutableA = { a: "" }; return ma; } `, }, // readonly -> readonly (function return) { filename: "file.ts", code: ` type MutableA = { a: string }; type ReadonlyA = { readonly a: string }; function foo(): ReadonlyA { const ma: ReadonlyA = { a: "" } as const; return ma; } `, }, // mutable -> mutable (type changes) { filename: "file.ts", code: ` type MutableA = { a: string }; type MutableB = { a: string | null }; const foo = (mut: MutableB): void => { mut.a = null; // whoops }; const mut: MutableA = { a: "" }; foo(mut); `, }, // tuple -> readonly array (nested objected property) { filename: "file.ts", code: ` type Foo = { readonly foo: ReadonlyArray<{ readonly a: string; readonly b: string; }>; }; const f: Foo = { foo: [{ a: "", b: "", }], } as const; `, }, // mutable function return -> mutable function return (multiple call signatures). { filename: "file.ts", code: ` type MutableA = { a: string }; interface MutableFunc { (b: number): MutableA; (b: string): MutableA; } const mf: MutableFunc = (b: number | string): MutableA => { return { a: "" }; }; const rf: MutableFunc = mf; `, }, // readonly function return -> readonly function return (multiple call signatures). { filename: "file.ts", code: ` type ReadonlyA = { readonly a: string }; interface ReadonlyFunc { (b: number): ReadonlyA; (b: string): ReadonlyA; } const mf: ReadonlyFunc = (b: number | string): ReadonlyA => { return { a: "" } as const; }; const rf: ReadonlyFunc = mf; `, }, // Return empty tuple from function that is declared to return some readonly array type. { filename: "file.ts", code: ` type Foo = ReadonlyArray<{ readonly a: string }>; const foo = (): Foo => { return [] as const; }; `, }, // Return empty tuple from function that is declared to return empty tuple. { filename: "file.ts", code: ` type Foo = readonly []; const foo = (): Foo => { return [] as const; }; `, }, ], invalid: [ // initalization using mutable (literal) -> readonly // TODO this should ideally be considered valid without requiring an `as const`. { filename: "file.ts", code: ` type ReadonlyA = { readonly a: string }; const readonlyA: ReadonlyA = { a: "" }; `, errors: [ { messageId: "errorStringVariableDeclaration", type: AST_NODE_TYPES.VariableDeclaration, }, ], }, // TODO `{ a: b } as const` is being flagged here. Is that correct? // // object literal -> readonly (mutable reference to property retained) // { // filename: "file.ts", // code: ` // type MutableB = { b: string }; // type ReadonlyA = { readonly a: { readonly b: string } }; // const func = (param: ReadonlyA): void => { // return undefined; // }; // const b: MutableB = { b: "" }; // func({ a: b } as const); // `, // errors: [ // { // messageId: "errorStringCallExpression", // type: AST_NODE_TYPES.Identifier, // }, // ], // }, /** * type assertions */ // mutable -> readonly { filename: "file.ts", code: ` type MutableA = { a: string }; type ReadonlyA = { readonly a: string }; const ro: MutableA = { a: "" }; const mut = <ReadonlyA>ro; `, errors: [ { messageId: "errorStringTSTypeAssertion", type: AST_NODE_TYPES.TSTypeAssertion, }, ], }, // mutable -> readonly { filename: "file.ts", code: ` type MutableA = { a: string }; type ReadonlyA = { readonly a: string }; const ro: MutableA = { a: "" }; const mut = ro as ReadonlyA; `, errors: [ { messageId: "errorStringTSAsExpression", type: AST_NODE_TYPES.TSAsExpression, }, ], }, // mutable -> readonly { filename: "file.ts", code: ` type MutableA = { a: string }; type ReadonlyA = Readonly<MutableA>; const func = (param: ReadonlyA): void => { return undefined; }; const mutableA: MutableA = { a: "" }; func(mutableA); `, errors: [ { messageId: "errorStringCallExpression", type: AST_NODE_TYPES.Identifier, }, ], }, // mutable -> readonly (function return) { filename: "file.ts", code: ` type MutableA = { a: string }; type ReadonlyA = { readonly a: string }; function foo(): ReadonlyA { const ma: MutableA = { a: "" }; return ma; } `, errors: [ { messageId: "errorStringArrowFunctionExpression", type: AST_NODE_TYPES.ReturnStatement, }, ], }, // mutable function return -> readonly function return (as part of intersection with object). { filename: "file.ts", code: ` type RandomObject = { readonly b?: string }; type MutableA = RandomObject & (() => { a: string }); type ReadonlyA = RandomObject & (() => { readonly a: string }); const ma: MutableA = () => ({ a: "" }); const ra: ReadonlyA = ma; `, errors: [ { messageId: "errorStringVariableDeclaration", type: AST_NODE_TYPES.VariableDeclaration, }, ], }, // mutable object prop -> readonly object prop (as part of intersection with non-object). { filename: "file.ts", code: ` type MutableA = { a?: string } & number; type ReadonlyA = { readonly a?: string } & number; const ma: MutableA = 42; const ra: ReadonlyA = ma; `, errors: [ { messageId: "errorStringVariableDeclaration", type: AST_NODE_TYPES.VariableDeclaration, }, ], }, // Return empty mutable array from function that is declared to return empty tuple. { filename: "file.ts", code: ` const foo = (): readonly [] => { return []; }; `, errors: [ { messageId: "errorStringArrowFunctionExpression", type: AST_NODE_TYPES.ReturnStatement, }, ], }, // mutable function return -> readonly function return (multiple call signatures). { filename: "file.ts", code: ` type MutableA = { a: string }; type ReadonlyA = { readonly a: string }; interface MutableFunc { (b: number): MutableA; (b: string): MutableA; } interface ReadonlyFunc { (b: number): ReadonlyA; (b: string): ReadonlyA; } const mf: MutableFunc = (b: number | string): MutableA => { return { a: "" }; }; const rf: ReadonlyFunc = mf; `, errors: [ { messageId: "errorStringVariableDeclaration", type: AST_NODE_TYPES.VariableDeclaration, }, ], }, ], } as const);
the_stack
// make TypeScript happy about external libraries (TODO: use .d.ts files) declare var heart: any; declare var PF: any; declare var pako: any; interface HeartImage { img: HTMLImageElement; getWidth(): number; getHeight(): number; } let gMap!: GameMap; const images: { [name: string]: HeartImage } = {} // Image cache var imageInfo: any = null // Metadata about images (Number of frames, FPS, etc) var currentElevation = 0 // current map elevation var hexOverlay: HeartImage|null = null var tempCanvas: HTMLCanvasElement|null = null // temporary canvas used for detecting single pixels var tempCanvasCtx: CanvasRenderingContext2D|null = null // and the context for it // position of viewport camera (will be overriden by map starts or scripts) var cameraX: number = 3580 var cameraY: number = 1020 const SCREEN_WIDTH: number = Config.ui.screenWidth const SCREEN_HEIGHT: number = Config.ui.screenHeight var gameTickTime: number = 0 // in Fallout 2 ticks (elapsed seconds * 10) var lastGameTick: number = 0 // real time of the last game tick var combat: Combat|null = null // combat object var inCombat: boolean = false // are we currently in combat? var gameHasFocus: boolean = false // do we have input focus? var lastMousePickTime: number = 0 // time when we last checked what's under the mouse cursor var _lastFPSTime: number = 0 // Time since FPS counter was last updated enum Skills { None = 0, Lockpick, Repair } var skillMode: Skills = Skills.None var isLoading: boolean = true // are we currently loading a map? var isWaitingOnRemote: boolean = false; // are we waiting on the remote server to send critical info? var isInitializing: boolean = true // are we initializing the engine? var loadingAssetsLoaded: number = 0 // how many images we've loaded var loadingAssetsTotal: number = 0 // out of this total var loadingLoadedCallback: (() => void)|null = null // loaded callback var lazyAssetLoadingQueue: { [name: string]: ((img: any) => void)[]|undefined } = {} // set of lazily-loaded assets being loaded interface FloatMessage { msg: string; obj: Obj; startTime: number; color: string; } const floatMessages: FloatMessage[] = [] // the global player object let player!: Player; let renderer!: Renderer; let audioEngine!: AudioEngine; let $fpsOverlay: HTMLElement|null = null; function repr(obj: any) { return JSON.stringify(obj, null, 2) } function lazyLoadImage(art: string, callback?: (x: any) => void, isHeartImg?: boolean) { if(images[art] !== undefined) { if(callback) callback(isHeartImg ? images[art] : images[art].img) return } if(lazyAssetLoadingQueue[art] !== undefined) { if(callback) lazyAssetLoadingQueue[art]!.push(callback) return } if(Config.engine.doLogLazyLoads) console.log("lazy loading " + art + "...") lazyAssetLoadingQueue[art] = (callback ? [callback] : []) var img = new Image() img.onload = function() { images[art] = new heart.HeartImage(img) var callbacks = lazyAssetLoadingQueue[art] if(callbacks !== undefined) { for(var i = 0; i < callbacks.length; i++) callbacks[i](images[art]) lazyAssetLoadingQueue[art] = undefined } } img.src = art + '.png' } function lookupScriptName(scriptID: number): string { console.log("SID: " + scriptID) const lookupName = getLstId("scripts/scripts", scriptID - 1); if(lookupName === null) throw Error("lookupScriptName: failed to look up script name"); return lookupName.split('.')[0].toLowerCase() } function dropObject(source: Obj, obj: Obj) { // drop inventory object obj from source var removed = false for(var i = 0; i < source.inventory.length; i++) { if(source.inventory[i].pid === obj.pid) { removed = true source.inventory.splice(i, 1) // remove from source break } } if(!removed) throw "dropObject: couldn't find object" gMap.addObject(obj) // add to objects var idx = gMap.getObjects().length - 1 // our new index obj.move({x: source.position.x, y: source.position.y}, idx) } function pickupObject(obj: Obj, source: Critter) { if(obj._script) { console.log("picking up %o", obj) Scripting.pickup(obj, source) } } // Draws a line between a and b, returning the first object hit function hexLinecast(a: Point, b: Point): Obj|null { var line = hexLine(a, b) if(line === null) return null line = line.slice(1, -1) for(var i = 0; i < line.length; i++) { // todo: we could optimize this by only // checking in a certain radius of `a` var obj = objectsAtPosition(line[i]) if(obj.length !== 0) return obj[0] } return null } function objectsAtPosition(position: Point): Obj[] { return gMap.getObjects().filter((obj: Obj) => obj.position.x === position.x && obj.position.y === position.y) } function critterAtPosition(position: Point): Critter|null { return objectsAtPosition(position).find(obj => obj.type === "critter") as Critter || null } function centerCamera(around: Point) { var scr = hexToScreen(around.x, around.y) cameraX = Math.max(0, scr.x - SCREEN_WIDTH/2 | 0) cameraY = Math.max(0, scr.y - SCREEN_HEIGHT/2 | 0) } function initGame() { // initialize player player = new Player() // initialize map gMap = new GameMap() uiLog("Welcome to DarkFO") if(location.search !== "") { // load map from query string (e.g. URL ending in ?modmain) // also check if it's trying to connect to a remote server const query = location.search.slice(1); if(query.indexOf("host=") === 0) { // host a multiplayer map const mapName = query.split("host=")[1] console.log("MP host map", mapName); // Disallow combat, for now, since it breaks things with guest players. Config.engine.doCombat = false; gMap.loadMap(mapName); Netcode.connect("ws://localhost:8090", () => { console.log("connected"); Netcode.identify("Host Player"); Netcode.host(); Netcode.changeMap(); }); } else if(query.indexOf("join=") === 0) { // join a multiplayer host const host = query.split("join=")[1]; console.log("MP server host: %s", host); // Disable scripts on the client as they'd differ from the remote host and muck up the simulation Config.engine.doLoadScripts = false; Config.engine.doUpdateCritters = false; Config.engine.doTimedEvents = false; Config.engine.doSaveDirtyMaps = false; Config.engine.doSpatials = false; Config.engine.doEncounters = false; // Also disallow things such as combat, for now. Config.engine.doCombat = false; isWaitingOnRemote = true; Netcode.connect(`ws://${host}:8090`, () => { console.log("connected"); Netcode.identify("Guest Player"); Netcode.join(); }); } else // single-player map gMap.loadMap(location.search.slice(1)) } else // load starting map gMap.loadMap("artemple") if(Config.engine.doCombat === true) CriticalEffects.loadTable() document.oncontextmenu = () => false; const $cnv = document.getElementById("cnv")!; $cnv.onmouseenter = () => { gameHasFocus = true; }; $cnv.onmouseleave = () => { gameHasFocus = false; }; tempCanvas = document.createElement("canvas") as HTMLCanvasElement; tempCanvas.width = SCREEN_WIDTH; tempCanvas.height = SCREEN_HEIGHT; tempCanvasCtx = tempCanvas.getContext("2d"); SaveLoad.init() Worldmap.init() initUI() if(Config.ui.hideRoofWhenUnder) { // Only show roofs if the player is not under them Events.on("playerMoved", (e: Point) => { Config.ui.showRoof = !gMap.hasRoofAt(e); }); } } heart.load = function() { isInitializing = true; $fpsOverlay = document.getElementById("fpsOverlay"); // initialize renderer if(Config.engine.renderer === "canvas") renderer = new CanvasRenderer() else if(Config.engine.renderer === "webgl") renderer = new WebGLRenderer() else { console.error("No renderer backend named '%s'", Config.engine.renderer) throw new Error("Invalid renderer backend"); } renderer.init() // initialize audio engine if(Config.engine.doAudio) audioEngine = new HTMLAudioEngine() else audioEngine = new NullAudioEngine() // initialize cached data function cachedJSON(key: string, path: string, callback: (value: any) => void): void { // load data from cache if possible, else load and cache it IDBCache.get(key, value => { if(value) { console.log("[Main] %s loaded from cache DB", key); callback(value); } else { value = getFileJSON(path); IDBCache.add(key, value); console.log("[Main] %s loaded and cached", key); callback(value); } }); } IDBCache.init(() => { cachedJSON("imageMap", "art/imageMap.json", value => { imageInfo = value; cachedJSON("proMap", "proto/pro.json", value => { proMap = value; // continue initialization initGame(); isInitializing = false; }); }); }); } function isSelectableObject(obj: any) { return obj.visible !== false && (canUseObject(obj) || obj.type === "critter") } // Is the skill passive, or does it require a targeted object to use? function isPassiveSkill(skill: Skills): boolean { switch(skill) { case Skills.Lockpick: return false case Skills.Repair: return false default: throw `TODO: is passive skill ${skill}` } } // Return the skill ID used by the Fallout 2 engine function getSkillID(skill: Skills): number { switch(skill) { case Skills.Lockpick: return 9 case Skills.Repair: return 13 } console.log("unimplemented skill %d", skill) return -1 } function playerUseSkill(skill: Skills, obj: Obj): void { console.log("use skill %o on %o", skill, obj) if(!obj && !isPassiveSkill(skill)) throw "trying to use non-passive skill without a target" if(!isPassiveSkill(skill)) { // use the skill on the object Scripting.useSkillOn(player, getSkillID(skill), obj) } else console.log("passive skills are not implemented") } function playerUse() { // TODO: playerUse should take an object var mousePos = heart.mouse.getPosition() var mouseHex = hexFromScreen(mousePos[0] + cameraX, mousePos[1] + cameraY) var obj = getObjectUnderCursor(isSelectableObject) var who = <Critter>obj if(uiMode === UI_MODE_USE_SKILL) { // using a skill on object obj = getObjectUnderCursor((_: Obj) => true) // obj might not be usable, so select non-usable ones too if(!obj) return try { playerUseSkill(skillMode, obj) } finally { skillMode = Skills.None uiMode = UI_MODE_NONE } return } if(obj === null) { // walk to the destination if there is no usable object // Walking in combat (TODO: This should probably be in Combat...) if(inCombat) { if(!(combat!.inPlayerTurn || Config.combat.allowWalkDuringAnyTurn)) { console.log("Wait your turn."); return; } if(player.AP!.getAvailableMoveAP() === 0) { uiLog(getProtoMsg(700)!); // "You don't have enough action points." return; } const maxWalkingDist = player.AP!.getAvailableMoveAP(); if(!player.walkTo(mouseHex, Config.engine.doAlwaysRun, undefined, maxWalkingDist)) { console.log("Cannot walk there"); } else { if(!player.AP!.subtractMoveAP(player.path.path.length - 1)) throw "subtraction issue: has AP: " + player.AP!.getAvailableMoveAP() + " needs AP:"+player.path.path.length+" and maxDist was:"+maxWalkingDist; } } // Walking out of combat if(!player.walkTo(mouseHex, Config.engine.doAlwaysRun)) console.log("Cannot walk there"); return; } if(obj.type === "critter") { if(obj === player) return // can't use yourself if(inCombat && !who.dead) { // attack a critter if(!combat!.inPlayerTurn || player.inAnim()) { console.log("You can't do that yet.") return } if(player.AP!.getAvailableCombatAP() < 4) { uiLog(getProtoMsg(700)!) // "You don't have enough action points." return } // TODO: move within range of target var weapon = critterGetEquippedWeapon(player) if(weapon === null) { console.log("You have no weapon equipped!") return } if(weapon.weapon!.isCalled()) { var art = "art/critters/hmjmpsna" // default art if(critterHasAnim(who, "called-shot")) art = critterGetAnim(who, "called-shot") console.log("art: %s", art) uiCalledShot(art, who, (region: string) => { player.AP!.subtractCombatAP(4) console.log("Attacking %s...", region) combat!.attack(player, <Critter>obj, region) uiCloseCalledShot() }) } else { player.AP!.subtractCombatAP(4) console.log("Attacking the torso...") combat!.attack(player, <Critter>obj, "torso") } return } } var callback = function() { player.clearAnim() if(!obj) throw Error(); // if there's an object under the cursor, use it if(obj.type === "critter") { if(who.dead !== true && inCombat !== true && obj._script && obj._script.talk_p_proc !== undefined) { // talk to a critter console.log("Talking to " + who.name) if(!who._script) { console.warn("obj has no script"); return; } Scripting.talk(who._script, who) } else if(who.dead === true) { // loot a dead body uiLoot(obj) } else console.log("Cannot talk to/loot that critter") } else useObject(obj, player) } if(Config.engine.doInfiniteUse === true) callback() else player.walkInFrontOf(obj.position, callback) } heart.mousepressed = (x: number, y: number, btn: string) => { if(isInitializing || isLoading || isWaitingOnRemote) return else if(btn === "l") playerUse() else if(btn === "r") { // item context menu var obj = getObjectUnderCursor(isSelectableObject) if(obj) uiContextMenu(obj, {clientX: x, clientY: y}) } } heart.keydown = (k: string) => { if(isLoading === true) return var mousePos = heart.mouse.getPosition() var mouseHex = hexFromScreen(mousePos[0] + cameraX, mousePos[1] + cameraY) if(k === Config.controls.cameraDown) cameraY += 15 if(k === Config.controls.cameraRight) cameraX += 15 if(k === Config.controls.cameraLeft) cameraX -= 15 if(k === Config.controls.cameraUp) cameraY -= 15 if(k === Config.controls.elevationDown) { if(currentElevation-1 >= 0) gMap.changeElevation(currentElevation-1, true) } if(k === Config.controls.elevationUp) { if(currentElevation+1 < gMap.numLevels) gMap.changeElevation(currentElevation+1, true) } if(k === Config.controls.showRoof) { Config.ui.showRoof = !Config.ui.showRoof } if(k === Config.controls.showFloor) { Config.ui.showFloor = !Config.ui.showFloor } if(k === Config.controls.showObjects) { Config.ui.showObjects = !Config.ui.showObjects } if(k === Config.controls.showWalls) Config.ui.showWalls = !Config.ui.showWalls if(k === Config.controls.talkTo) { var critter = critterAtPosition(mouseHex) if(critter) { if(critter._script && critter._script.talk_p_proc !== undefined) { console.log("talking to " + critter.name) Scripting.talk(critter._script, critter) } } } if(k === Config.controls.inspect) { gMap.getObjects().forEach((obj, idx) => { if(obj.position.x === mouseHex.x && obj.position.y === mouseHex.y) { var hasScripts = (obj.script !== undefined ? ("yes (" + obj.script + ")") : "no") + " " + (obj._script === undefined ? "and is NOT loaded" : "and is loaded") console.log("object is at index " + idx + ", of type " + obj.type + ", has art " + obj.art + ", and has scripts? " + hasScripts + " -> %o", obj) } }) } if(k === Config.controls.moveTo) { player.walkTo(mouseHex) } if(k === Config.controls.runTo) { player.walkTo(mouseHex, true) } if(k === Config.controls.attack) { if(!inCombat || !combat!.inPlayerTurn || player.anim !== "idle") { console.log("You can't do that yet.") return } if(player.AP!.getAvailableCombatAP() < 4) { uiLog(getProtoMsg(700)!) return } for(var i = 0; i < combat!.combatants.length; i++) { if(combat!.combatants[i].position.x === mouseHex.x && combat!.combatants[i].position.y === mouseHex.y && !combat!.combatants[i].dead) { player.AP!.subtractCombatAP(4) console.log("Attacking...") combat!.attack(player, combat!.combatants[i]) break } } } if(k === Config.controls.combat) { if(!Config.engine.doCombat) return if(inCombat === true && combat!.inPlayerTurn === true) { console.log("[TURN]") combat!.nextTurn() } else if(inCombat === true) { console.log("Wait your turn...") } else { console.log("[COMBAT BEGIN]") inCombat = true combat = new Combat(gMap.getObjects()) combat.nextTurn() } } if(k === Config.controls.playerToTargetRaycast) { var obj = objectsAtPosition(mouseHex)[0] if(obj !== undefined) { var hit = hexLinecast(player.position, obj.position) if(!hit) return; console.log("hit obj: " + hit.art) } } if(k === Config.controls.showTargetInventory) { var obj = objectsAtPosition(mouseHex)[0] if(obj !== undefined) { console.log("PID: " + obj.pid) console.log("inventory: " + JSON.stringify(obj.inventory)) uiLoot(obj) } } if(k === Config.controls.use) { var objs = objectsAtPosition(mouseHex) for(var i = 0; i < objs.length; i++) { useObject(objs[i]) } } if(k === 'h') player.move(mouseHex) if(k === Config.controls.kill) { var critter = critterAtPosition(mouseHex) if(critter) critterKill(critter, player) } if(k === Config.controls.worldmap) uiWorldMap() if(k === Config.controls.saveKey) uiSaveLoad(true) if(k === Config.controls.loadKey) uiSaveLoad(false) //if(k == calledShotKey) // uiCalledShot() //if(k == 'a') // Worldmap.checkEncounters() } function recalcPath(start: Point, goal: Point, isGoalBlocking?: boolean) { const matrix = new Array(HEX_GRID_SIZE) for(let y = 0; y < HEX_GRID_SIZE; y++) matrix[y] = new Array(HEX_GRID_SIZE) for(const obj of gMap.getObjects()) { // if there are multiple, any blocking one will block matrix[obj.position.y][obj.position.x] |= <any>obj.blocks() } if(isGoalBlocking === false) matrix[goal.y][goal.x] = 0 const grid = new PF.Grid(HEX_GRID_SIZE, HEX_GRID_SIZE, matrix) const finder = new PF.BestFirstFinder() return finder.findPath(start.x, start.y, goal.x, goal.y, grid) } function changeCursor(image: string) { document.getElementById("cnv")!.style.cursor = image; } function objectTransparentAt(obj: Obj, position: Point) { var frame = obj.frame !== undefined ? obj.frame : 0 var sx = imageInfo[obj.art].frameOffsets[obj.orientation][frame].sx if(!tempCanvasCtx) throw Error(); tempCanvasCtx.clearRect(0, 0, 1, 1) // clear previous color tempCanvasCtx.drawImage(images[obj.art].img, sx+position.x, position.y, 1, 1, 0, 0, 1, 1) var pixelAlpha = tempCanvasCtx.getImageData(0, 0, 1, 1).data[3] return (pixelAlpha === 0) } function getObjectUnderCursor(p: (obj: Obj) => boolean) { var mouse = heart.mouse.getPosition() mouse = {x: mouse[0] + cameraX, y: mouse[1] + cameraY} // reverse z-ordered search var objects = gMap.getObjects() for(var i = objects.length - 1; i > 0; i--) { var bbox = objectBoundingBox(objects[i]) if(bbox === null) continue if(pointInBoundingBox(mouse, bbox)) if(p === undefined || p(objects[i]) === true) { var mouseRel = {x: mouse.x - bbox.x, y: mouse.y - bbox.y} if(!objectTransparentAt(objects[i], mouseRel)) return objects[i] } } return null } heart.update = function() { if(isInitializing || isWaitingOnRemote) return; else if(isLoading) { if(loadingAssetsLoaded === loadingAssetsTotal) { isLoading = false if(loadingLoadedCallback) loadingLoadedCallback() } else return } if(uiMode !== UI_MODE_NONE) return var time = heart.timer.getTime() if(time - _lastFPSTime >= 500) { $fpsOverlay!.textContent = "fps: " + heart.timer.getFPS(); _lastFPSTime = time; } if(gameHasFocus) { var mousePos = heart.mouse.getPosition() if(mousePos[0] <= Config.ui.scrollPadding) cameraX -= 15 if(mousePos[0] >= SCREEN_WIDTH-Config.ui.scrollPadding) cameraX += 15 if(mousePos[1] <= Config.ui.scrollPadding) cameraY -= 15 if(mousePos[1] >= SCREEN_HEIGHT-Config.ui.scrollPadding) cameraY += 15 if(time >= lastMousePickTime + 750) { // every .75 seconds, check the object under the cursor lastMousePickTime = time var obj = getObjectUnderCursor(isSelectableObject) if(obj !== null) changeCursor("pointer") else changeCursor("auto") } for(var i = 0; i < floatMessages.length; i++) { if(time >= floatMessages[i].startTime + 1000*Config.ui.floatMessageDuration) { floatMessages.splice(i--, 1) continue } } } var didTick = (time - lastGameTick >= 1000/10) // 10 Hz game tick if(didTick) { lastGameTick = time gameTickTime++ if(Config.engine.doTimedEvents && !inCombat) { // check and update timed events var timedEvents = Scripting.timeEventList var numEvents = timedEvents.length for(var i = 0; i < numEvents; i++) { const event = timedEvents[i]; const obj = event.obj; // remove events for dead objects if(obj && obj instanceof Critter && obj.dead) { console.log("removing timed event for dead object") timedEvents.splice(i--, 1) numEvents-- continue } event.ticks-- if(event.ticks <= 0) { Scripting.info("timed event triggered", "timer") event.fn() timedEvents.splice(i--, 1) numEvents-- } } } audioEngine.tick() } for(const obj of gMap.getObjects()) { if(obj.type === "critter") { if(didTick && Config.engine.doUpdateCritters && !inCombat && !(<Critter>obj).dead && !obj.inAnim() && obj._script) Scripting.updateCritter(obj._script, obj as Critter); } obj.updateAnim(); } } // get an object's bounding box in screen-space (note: not camera-space) function objectBoundingBox(obj: Obj): BoundingBox|null { var scr = hexToScreen(obj.position.x, obj.position.y) if(images[obj.art] === undefined) // no art return null var info = imageInfo[obj.art] if(info === undefined) throw "No image map info for: " + obj.art var frameIdx = 0 if(obj.frame !== undefined) frameIdx += obj.frame if(!(obj.orientation in info.frameOffsets)) obj.orientation = 0 // ... var frameInfo = info.frameOffsets[obj.orientation][frameIdx] var dirOffset = info.directionOffsets[obj.orientation] var offsetX = Math.floor(frameInfo.w / 2) - dirOffset.x - frameInfo.ox var offsetY = frameInfo.h - dirOffset.y - frameInfo.oy return {x: scr.x - offsetX, y: scr.y - offsetY, w: frameInfo.w, h: frameInfo.h} } function objectOnScreen(obj: Obj): boolean { var bbox = objectBoundingBox(obj) if(bbox === null) return false if(bbox.x + bbox.w < cameraX || bbox.y + bbox.h < cameraY || bbox.x >= cameraX+SCREEN_WIDTH || bbox.y >= cameraY+SCREEN_HEIGHT) return false return true } heart.draw = () => { if(isWaitingOnRemote) return; return renderer.render() } // some utility functions for use in the console function allCritters() { return gMap.getObjects().filter(obj => obj instanceof Critter) } // global callbacks for dialogue UI function dialogueReply(id: number) { Scripting.dialogueReply(id) } function dialogueEnd() { Scripting.dialogueEnd() }
the_stack
import React from 'react'; import {useIntl, FormattedMessage} from 'gatsby-plugin-intl'; import {Accordion} from '@trussworks/react-uswds'; // Components: import Category from '../Category'; import DisadvantageDot from '../DisadvantageDot'; import Indicator from '../Indicator'; // Styles and constants import * as styles from './areaDetail.module.scss'; import * as constants from '../../data/constants'; import * as EXPLORE_COPY from '../../data/copy/explore'; interface IAreaDetailProps { properties: constants.J40Properties, } /** * This interface is used as define the various fields for each indicator in the side panel * label: the indicator label or title * description: the description of the indicator used in the side panel * value: the number from the geoJSON tile * isDisadvagtaged: the flag from the geoJSON tile * isPercent: is the value a percent or percentile * */ export interface indicatorInfo { label: string, description: string, value: number, isDisadvagtaged: boolean, isPercent?: boolean, } const AreaDetail = ({properties}:IAreaDetailProps) => { const intl = useIntl(); // console.log the properties of the census that is selected: console.log("Area Detail properies: ", properties); const score = properties[constants.SCORE_PROPERTY_HIGH] ? properties[constants.SCORE_PROPERTY_HIGH] as number : 0; const blockGroup = properties[constants.GEOID_PROPERTY] ? properties[constants.GEOID_PROPERTY] : "N/A"; const population = properties[constants.TOTAL_POPULATION] ? properties[constants.TOTAL_POPULATION] : "N/A"; const countyName = properties[constants.COUNTY_NAME] ? properties[constants.COUNTY_NAME] : "N/A"; const stateName = properties[constants.STATE_NAME] ? properties[constants.STATE_NAME] : "N/A"; const isCommunityFocus = score >= constants.SCORE_BOUNDARY_THRESHOLD; // Define each indicator in the side panel with constants from copy file (for intl) // Indicators are grouped by category const expAgLoss:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.EXP_AG_LOSS), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.EXP_AG_LOSS), value: properties[constants.EXP_AGRICULTURE_LOSS_PERCENTILE] ? properties[constants.EXP_AGRICULTURE_LOSS_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_EXP_AGR_LOSS_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_EXP_AGR_LOSS_AND_IS_LOW_INCOME] : null, }; const expBldLoss:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.EXP_BLD_LOSS), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.EXP_BLD_LOSS), value: properties[constants.EXP_BUILDING_LOSS_PERCENTILE] ? properties[constants.EXP_BUILDING_LOSS_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_EXP_BLD_LOSS_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_EXP_BLD_LOSS_AND_IS_LOW_INCOME] : null, }; const expPopLoss:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.EXP_POP_LOSS), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.EXP_POP_LOSS), value: properties[constants.EXP_POPULATION_LOSS_PERCENTILE] ? properties[constants.EXP_POPULATION_LOSS_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_EXP_POP_LOSS_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_EXP_POP_LOSS_AND_IS_LOW_INCOME] : null, }; const lowInc:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.LOW_INCOME), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.LOW_INCOME), value: properties[constants.POVERTY_BELOW_200_PERCENTILE] ? properties[constants.POVERTY_BELOW_200_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_FEDERAL_POVERTY_LEVEL_200] ? properties[constants.IS_FEDERAL_POVERTY_LEVEL_200] : null, }; const energyBurden:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.ENERGY_BURDEN), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.ENERGY_BURDEN), value: properties[constants.ENERGY_PERCENTILE] ? properties[constants.ENERGY_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_ENERGY_BURDEN_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_ENERGY_BURDEN_AND_IS_LOW_INCOME] : null, }; const pm25:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.PM_2_5), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.PM_2_5), value: properties[constants.PM25_PERCENTILE] ? properties[constants.PM25_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_PM25_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_PM25_AND_IS_LOW_INCOME] : null, }; const dieselPartMatter:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.DIESEL_PARTICULATE_MATTER), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.DIESEL_PARTICULATE_MATTER), value: properties[constants.DIESEL_MATTER_PERCENTILE] ? properties[constants.DIESEL_MATTER_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_DIESEL_PM_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_DIESEL_PM_AND_IS_LOW_INCOME] : null, }; const trafficVolume:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.TRAFFIC_VOLUME), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.TRAFFIC_VOLUME), value: properties[constants.TRAFFIC_PERCENTILE] ? properties[constants.TRAFFIC_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_TRAFFIC_PROX_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_TRAFFIC_PROX_AND_IS_LOW_INCOME] : null, }; const houseBurden:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.HOUSE_BURDEN), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.HOUSE_BURDEN), value: properties[constants.HOUSING_BURDEN_PROPERTY_PERCENTILE] ? properties[constants.HOUSING_BURDEN_PROPERTY_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_HOUSE_BURDEN_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_HOUSE_BURDEN_AND_IS_LOW_INCOME] : null, }; const leadPaint:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.LEAD_PAINT), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.LEAD_PAINT), value: properties[constants.LEAD_PAINT_PERCENTILE] ? properties[constants.LEAD_PAINT_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_LEAD_PAINT_AND_MEDIAN_HOME_VAL_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_LEAD_PAINT_AND_MEDIAN_HOME_VAL_AND_IS_LOW_INCOME] : null, }; // const medHomeVal:indicatorInfo = { // label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.MED_HOME_VAL), // description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.MED_HOME_VAL), // value: properties[constants.MEDIAN_HOME_VALUE_PERCENTILE] ? // properties[constants.MEDIAN_HOME_VALUE_PERCENTILE] : null, // isDisadvagtaged: false, // TODO // }; const proxHaz:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.PROX_HAZ), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.PROX_HAZ), value: properties[constants.PROXIMITY_TSDF_SITES_PERCENTILE] ? properties[constants.PROXIMITY_TSDF_SITES_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_HAZARD_WASTE_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_HAZARD_WASTE_AND_IS_LOW_INCOME] : null, }; const proxNPL:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.PROX_NPL), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.PROX_NPL), value: properties[constants.PROXIMITY_NPL_SITES_PERCENTILE] ? properties[constants.PROXIMITY_NPL_SITES_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_SUPERFUND_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_SUPERFUND_AND_IS_LOW_INCOME] : null, }; const proxRMP:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.PROX_RMP), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.PROX_RMP), value: properties[constants.PROXIMITY_RMP_SITES_PERCENTILE] ? properties[constants.PROXIMITY_RMP_SITES_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_RMP_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_RMP_AND_IS_LOW_INCOME] : null, }; const wasteWater:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.WASTE_WATER), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.WASTE_WATER), value: properties[constants.WASTEWATER_PERCENTILE] ? properties[constants.WASTEWATER_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_WASTEWATER_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_WASTEWATER_AND_IS_LOW_INCOME] : null, }; const asthma:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.ASTHMA), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.ASTHMA), value: properties[constants.ASTHMA_PERCENTILE] ? properties[constants.ASTHMA_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_ASTHMA_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_ASTHMA_AND_IS_LOW_INCOME] : null, }; const diabetes:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.DIABETES), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.DIABETES), value: properties[constants.DIABETES_PERCENTILE] ? properties[constants.DIABETES_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_DIABETES_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_DIABETES_AND_IS_LOW_INCOME] : null, }; const heartDisease:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.HEART_DISEASE), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.HEART_DISEASE), value: properties[constants.HEART_PERCENTILE] ? properties[constants.HEART_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_HEART_DISEASE_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_HEART_DISEASE_AND_IS_LOW_INCOME] : null, }; const lifeExpect:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.LIFE_EXPECT), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.LOW_LIFE_EXPECT), value: properties[constants.LIFE_PERCENTILE] ? properties[constants.LIFE_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_LOW_LIFE_EXP_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_LOW_LIFE_EXP_AND_IS_LOW_INCOME] : null, }; const lowMedInc:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.LOW_MED_INC), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.LOW_MED_INCOME), value: properties[constants.LOW_MEDIAN_INCOME_PERCENTILE] ? properties[constants.LOW_MEDIAN_INCOME_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_LOW_MEDIAN_INCOME_AND_LOW_HIGH_SCHOOL_EDU] ? properties[constants.IS_GTE_90_LOW_MEDIAN_INCOME_AND_LOW_HIGH_SCHOOL_EDU] : null, }; const lingIso:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.LING_ISO), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.LING_ISO), value: properties[constants.LINGUISTIC_ISOLATION_PROPERTY_PERCENTILE] ? properties[constants.LINGUISTIC_ISOLATION_PROPERTY_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_LINGUISITIC_ISO_AND_IS_LOW_INCOME] ? properties[constants.IS_GTE_90_LINGUISITIC_ISO_AND_IS_LOW_INCOME] : null, }; const unemploy:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.UNEMPLOY), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.UNEMPLOY), value: properties[constants.UNEMPLOYMENT_PROPERTY_PERCENTILE] ? properties[constants.UNEMPLOYMENT_PROPERTY_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_UNEMPLOYMENT_AND_LOW_HIGH_SCHOOL_EDU] ? properties[constants.IS_GTE_90_UNEMPLOYMENT_AND_LOW_HIGH_SCHOOL_EDU] : null, }; const poverty:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.POVERTY), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.POVERTY), value: properties[constants.POVERTY_PROPERTY_PERCENTILE] ? properties[constants.POVERTY_PROPERTY_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_BELOW_100_POVERTY_AND_LOW_HIGH_SCHOOL_EDU] ? properties[constants.IS_GTE_90_BELOW_100_POVERTY_AND_LOW_HIGH_SCHOOL_EDU] : null, }; const highSchool:indicatorInfo = { label: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATORS.HIGH_SCL), description: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_INDICATOR_DESCRIPTION.HIGH_SKL), value: properties[constants.HIGH_SCHOOL_PROPERTY_PERCENTILE] ? properties[constants.HIGH_SCHOOL_PROPERTY_PERCENTILE] : null, isDisadvagtaged: properties[constants.IS_GTE_90_UNEMPLOYMENT_AND_LOW_HIGH_SCHOOL_EDU] ? properties[constants.IS_GTE_90_UNEMPLOYMENT_AND_LOW_HIGH_SCHOOL_EDU] : null, isPercent: true, }; // Aggregate indicators based on categories const categories = [ { id: 'climate-change', titleText: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_CATEGORY.CLIMATE), indicators: [expAgLoss, expBldLoss, expPopLoss, lowInc], isDisadvagtaged: properties[constants.IS_CLIMATE_FACTOR_DISADVANTAGED_L] ? properties[constants.IS_CLIMATE_FACTOR_DISADVANTAGED_L] : null, }, { id: 'clean-energy', titleText: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_CATEGORY.CLEAN_ENERGY), indicators: [energyBurden, pm25, lowInc], isDisadvagtaged: properties[constants.IS_ENERGY_FACTOR_DISADVANTAGED_L] ? properties[constants.IS_ENERGY_FACTOR_DISADVANTAGED_L] : null, }, { id: 'clean-transport', titleText: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_CATEGORY.CLEAN_TRANSPORT), indicators: [dieselPartMatter, trafficVolume, lowInc], isDisadvagtaged: properties[constants.IS_TRANSPORT_FACTOR_DISADVANTAGED_L] ? properties[constants.IS_TRANSPORT_FACTOR_DISADVANTAGED_L] : null, }, { id: 'sustain-house', titleText: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_CATEGORY.SUSTAIN_HOUSE), indicators: [houseBurden, leadPaint, lowInc], isDisadvagtaged: properties[constants.IS_HOUSING_FACTOR_DISADVANTAGED_L] ? properties[constants.IS_HOUSING_FACTOR_DISADVANTAGED_L] : null, }, { id: 'leg-pollute', titleText: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_CATEGORY.LEG_POLLUTE), indicators: [proxHaz, proxNPL, proxRMP, lowInc], isDisadvagtaged: properties[constants.IS_POLLUTION_FACTOR_DISADVANTAGED_L] ? properties[constants.IS_POLLUTION_FACTOR_DISADVANTAGED_L] : null, }, { id: 'clean-water', titleText: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_CATEGORY.CLEAN_WATER), indicators: [wasteWater, lowInc], isDisadvagtaged: properties[constants.IS_WATER_FACTOR_DISADVANTAGED_L] ? properties[constants.IS_WATER_FACTOR_DISADVANTAGED_L] : null, }, { id: 'health-burdens', titleText: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_CATEGORY.HEALTH_BURDEN), indicators: [asthma, diabetes, heartDisease, lifeExpect, lowInc], isDisadvagtaged: properties[constants.IS_HEALTH_FACTOR_DISADVANTAGED_L] ? properties[constants.IS_HEALTH_FACTOR_DISADVANTAGED_L] : null, }, { id: 'work-dev', titleText: intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_CATEGORY.WORK_DEV), indicators: [lowMedInc, lingIso, unemploy, poverty, highSchool], isDisadvagtaged: properties[constants.IS_WORKFORCE_FACTOR_DISADVANTAGED_L] ? properties[constants.IS_WORKFORCE_FACTOR_DISADVANTAGED_L] : null, }, ]; // Create the AccoridionItems by mapping over the categories array. In this array we define the // various indicators for a specific category. This is an array which then maps over the <Indicator /> // component to render the actual Indicator const categoryItems = categories.map((category) => ({ id: category.id, title: <Category name={category.titleText} isDisadvantaged={category.isDisadvagtaged}/>, content: ( <> {/* Category Header */} <div className={styles.categoryHeader}> <div>{intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_CATEGORY.INDICATOR)}</div> <div>{intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_CATEGORY.PERCENTILE)}</div> </div> {/* Category Indicators */} {category.indicators.map((indicator:any, index:number) => { return <Indicator key={`ind${index}`} indicator={indicator}/>; })} </> ), expanded: false, })); return ( <aside className={styles.areaDetailContainer} data-cy={'aside'}> {/* Methodology version */} <div className={styles.versionInfo}> {EXPLORE_COPY.SIDE_PANEL_VERION.TITLE} </div> {/* Census Info */} <ul className={styles.censusRow}> <li> <span className={styles.censusLabel}> {intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_CBG_INFO.CENSUS_BLOCK_GROUP)} </span> <span className={styles.censusText}>{` ${blockGroup}`}</span> </li> <li> <span className={styles.censusLabel}> {intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_CBG_INFO.COUNTY)} </span> <span className={styles.censusText}>{` ${countyName}`}</span> </li> <li> <span className={styles.censusLabel}> {intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_CBG_INFO.STATE)} </span> <span className={styles.censusText}>{` ${stateName}`}</span> </li> <li> <span className={styles.censusLabel}> {intl.formatMessage(EXPLORE_COPY.SIDE_PANEL_CBG_INFO.POPULATION)} </span> <span className={styles.censusText}>{` ${population.toLocaleString()}`}</span> </li> </ul> {/* Disadvantaged? */} <div className={styles.categorization}> <div className={styles.isInFocus}> {EXPLORE_COPY.COMMUNITY.IS_FOCUS} </div> <div className={styles.communityOfFocus}> {isCommunityFocus ? <> <h3>{EXPLORE_COPY.COMMUNITY.OF_FOCUS}</h3> <DisadvantageDot isDisadvantaged={isCommunityFocus}/> </> : <h3>{EXPLORE_COPY.COMMUNITY.NOT_OF_FOCUS}</h3> } </div> <div className={ properties[constants.TOTAL_NUMBER_OF_DISADVANTAGE_INDICATORS] > 0 ? styles.showThresholdExceed : styles.hideThresholdExceed }> <FormattedMessage id={'explore.page.threshold.count.exceed'} description={"threshold exceeded count"} defaultMessage={'{disadvCount} of {totalCount} thresholds exceeded'} values={{ disadvCount: properties[constants.TOTAL_NUMBER_OF_DISADVANTAGE_INDICATORS], totalCount: constants.TOTAL_NUMBER_OF_INDICATORS, }}/> </div> {/* <a className={styles.feedbackLink} href={sidePanelFeedbackHref}> {EXPLORE_COPY.COMMUNITY.SEND_FEEDBACK} </a> */} </div> {/* All category accordions in this component */} <Accordion multiselectable={true} items={categoryItems}/> </aside> ); }; export default AreaDetail;
the_stack
import { computeStackTrace } from './compute-stack-trace'; export const OPERA_25 = { message: "Cannot read property 'undef' of null", name: 'TypeError', stack: "TypeError: Cannot read property 'undef' of null\n" + ' at http://path/to/file.js:47:22\n' + ' at foo (http://path/to/file.js:52:15)\n' + ' at bar (http://path/to/file.js:108:168)', }; export const CHROME_15 = { name: 'foo', arguments: ['undef'], message: "Object #<Object> has no method 'undef'", stack: "TypeError: Object #<Object> has no method 'undef'\n" + ' at bar (http://path/to/file.js:13:17)\n' + ' at bar (http://path/to/file.js:16:5)\n' + ' at foo (http://path/to/file.js:20:5)\n' + ' at http://path/to/file.js:24:4', }; export const CHROME_36 = { message: 'Default error', name: 'Error', stack: 'Error: Default error\n' + ' at dumpExceptionError (http://localhost:8080/file.js:41:27)\n' + ' at HTMLButtonElement.onclick (http://localhost:8080/file.js:107:146)\n' + ' at I.e.fn.(anonymous function) [as index] (http://localhost:8080/file.js:10:3651)', }; // can be generated when Webpack is built with { devtool: eval } export const CHROME_XX_WEBPACK = { message: "Cannot read property 'error' of undefined", name: 'TypeError', stack: "TypeError: Cannot read property 'error' of undefined\n" + ' at TESTTESTTEST.eval(webpack:///./src/components/test/test.jsx?:295:108)\n' + ' at TESTTESTTEST.render(webpack:///./src/components/test/test.jsx?:272:32)\n' + ' at TESTTESTTEST.tryRender(webpack:///./~/react-transform-catch-errors/lib/index.js?:34:31)\n' + ' at TESTTESTTEST.proxiedMethod(webpack:///./~/react-proxy/modules/createPrototypeProxy.js?:44:30)', }; export const FIREFOX_3 = { fileName: 'http://127.0.0.1:8000/js/stacktrace.js', lineNumber: 44, message: 'this.undef is not a function', name: 'TypeError', stack: '()@http://127.0.0.1:8000/js/stacktrace.js:44\n' + '(null)@http://127.0.0.1:8000/js/stacktrace.js:31\n' + 'printStackTrace()@http://127.0.0.1:8000/js/stacktrace.js:18\n' + 'bar(1)@http://127.0.0.1:8000/js/file.js:13\n' + 'bar(2)@http://127.0.0.1:8000/js/file.js:16\n' + 'foo()@http://127.0.0.1:8000/js/file.js:20\n' + '@http://127.0.0.1:8000/js/file.js:24\n' + '', }; export const FIREFOX_7 = { name: 'foo', message: 'bar', fileName: 'file:///G:/js/stacktrace.js', lineNumber: 44, stack: '()@file:///G:/js/stacktrace.js:44\n' + '(null)@file:///G:/js/stacktrace.js:31\n' + 'printStackTrace()@file:///G:/js/stacktrace.js:18\n' + 'bar(1)@file:///G:/js/file.js:13\n' + 'bar(2)@file:///G:/js/file.js:16\n' + 'foo()@file:///G:/js/file.js:20\n' + '@file:///G:/js/file.js:24\n' + '', }; export const FIREFOX_14 = { name: 'foo', message: 'x is null', stack: '@http://path/to/file.js:48\n' + 'dumpException3@http://path/to/file.js:52\n' + 'onclick@http://path/to/file.js:1\n' + '', fileName: 'http://path/to/file.js', lineNumber: 48, }; export const FIREFOX_31 = { message: 'Default error', name: 'Error', stack: 'foo@http://path/to/file.js:41:13\n' + 'bar@http://path/to/file.js:1:1\n' + '.plugin/e.fn[c]/<@http://path/to/file.js:1:1\n' + '', fileName: 'http://path/to/file.js', lineNumber: 41, columnNumber: 12, }; export const FIREFOX_43_EVAL = { name: 'foo', columnNumber: 30, fileName: 'http://localhost:8080/file.js line 25 > eval line 2 > eval', lineNumber: 1, message: 'message string', stack: 'baz@http://localhost:8080/file.js line 26 > eval line 2 > eval:1:30\n' + 'foo@http://localhost:8080/file.js line 26 > eval:2:96\n' + '@http://localhost:8080/file.js line 26 > eval:4:18\n' + 'speak@http://localhost:8080/file.js:26:17\n' + '@http://localhost:8080/file.js:33:9', }; // Internal errors sometimes thrown by Firefox // More here: https://developer.mozilla.org/en-US/docs/Mozilla/Errors // // Note that such errors are instanceof "Exception", not "Error" export const FIREFOX_44_NS_EXCEPTION = { message: '', name: 'NS_ERROR_FAILURE', stack: '[2]</Bar.prototype._baz/</<@http://path/to/file.js:703:28\n' + 'App.prototype.foo@file:///path/to/file.js:15:2\n' + 'bar@file:///path/to/file.js:20:3\n' + '@file:///path/to/index.html:23:1\n' + // inside <script> tag '', fileName: 'http://path/to/file.js', columnNumber: 0, lineNumber: 703, result: 2147500037, }; export const FIREFOX_50_RESOURCE_URL = { stack: 'render@resource://path/data/content/bundle.js:5529:16\n' + 'dispatchEvent@resource://path/data/content/vendor.bundle.js:18:23028\n' + 'wrapped@resource://path/data/content/bundle.js:7270:25', fileName: 'resource://path/data/content/bundle.js', lineNumber: 5529, columnNumber: 16, message: 'this.props.raw[this.state.dataSource].rows is undefined', name: 'TypeError', }; export const SAFARI_6 = { name: 'foo', message: "'null' is not an object (evaluating 'x.undef')", stack: '@http://path/to/file.js:48\n' + 'dumpException3@http://path/to/file.js:52\n' + 'onclick@http://path/to/file.js:82\n' + '[native code]', line: 48, sourceURL: 'http://path/to/file.js', }; export const SAFARI_7 = { message: "'null' is not an object (evaluating 'x.undef')", name: 'TypeError', stack: 'http://path/to/file.js:48:22\n' + 'foo@http://path/to/file.js:52:15\n' + 'bar@http://path/to/file.js:108:107', line: 47, sourceURL: 'http://path/to/file.js', }; export const SAFARI_8 = { message: "null is not an object (evaluating 'x.undef')", name: 'TypeError', stack: 'http://path/to/file.js:47:22\n' + 'foo@http://path/to/file.js:52:15\n' + 'bar@http://path/to/file.js:108:23', line: 47, column: 22, sourceURL: 'http://path/to/file.js', }; export const IE_11 = { message: "Unable to get property 'undef' of undefined or null reference", name: 'TypeError', stack: "TypeError: Unable to get property 'undef' of undefined or null reference\n" + ' at Anonymous function (http://path/to/file.js:47:21)\n' + ' at foo (http://path/to/file.js:45:13)\n' + ' at bar (http://path/to/file.js:108:1)', description: "Unable to get property 'undef' of undefined or null reference", number: -2146823281, }; export const CHROME_48_BLOB = { message: 'Error: test', name: 'Error', stack: 'Error: test\n' + ' at Error (native)\n' + ' at s (blob:http%3A//localhost%3A8080/abfc40e9-4742-44ed-9dcd-af8f99a29379:31:29146)\n' + ' at Object.d [as add] (blob:http%3A//localhost%3A8080/abfc40e9-4742-44ed-9dcd-af8f99a29379:31:30039)\n' + ' at blob:http%3A//localhost%3A8080/d4eefe0f-361a-4682-b217-76587d9f712a:15:10978\n' + ' at blob:http%3A//localhost%3A8080/abfc40e9-4742-44ed-9dcd-af8f99a29379:1:6911\n' + ' at n.fire (blob:http%3A//localhost%3A8080/abfc40e9-4742-44ed-9dcd-af8f99a29379:7:3019)\n' + ' at n.handle (blob:http%3A//localhost%3A8080/abfc40e9-4742-44ed-9dcd-af8f99a29379:7:2863)', }; describe('Tracekit - Original Tests', () => { it('should parse Safari 6 error', () => { expect(computeStackTrace(SAFARI_6).stacktrace?.frames).toEqual([ { colno: null, filename: '[native code]', function: '?', lineno: null, }, { colno: null, filename: 'http://path/to/file.js', function: 'onclick', lineno: 82, }, { colno: null, filename: 'http://path/to/file.js', function: 'dumpException3', lineno: 52, }, { colno: null, filename: 'http://path/to/file.js', function: '?', lineno: 48, }, ]); }); it('should parse Safari 7 error', () => { expect(computeStackTrace(SAFARI_7).stacktrace?.frames).toEqual([ { colno: 107, filename: 'http://path/to/file.js', function: 'bar', lineno: 108, }, { colno: 15, filename: 'http://path/to/file.js', function: 'foo', lineno: 52, }, { colno: 22, filename: 'http://path/to/file.js', function: '?', lineno: 48, }, ]); }); it('should parse Safari 8 error', () => { expect(computeStackTrace(SAFARI_8).stacktrace?.frames).toEqual([ { colno: 23, filename: 'http://path/to/file.js', function: 'bar', lineno: 108, }, { colno: 15, filename: 'http://path/to/file.js', function: 'foo', lineno: 52, }, { colno: 22, filename: 'http://path/to/file.js', function: '?', lineno: 47, }, ]); }); it('should parse Firefox 3 error', () => { expect(computeStackTrace(FIREFOX_3).stacktrace?.frames).toEqual([ { colno: null, filename: 'http://127.0.0.1:8000/js/file.js', function: '?', lineno: 24, }, { colno: null, filename: 'http://127.0.0.1:8000/js/file.js', function: 'foo', lineno: 20, }, { colno: null, filename: 'http://127.0.0.1:8000/js/file.js', function: 'bar', lineno: 16, }, { colno: null, filename: 'http://127.0.0.1:8000/js/file.js', function: 'bar', lineno: 13, }, { colno: null, filename: 'http://127.0.0.1:8000/js/stacktrace.js', function: 'printStackTrace', lineno: 18, }, { colno: null, filename: 'http://127.0.0.1:8000/js/stacktrace.js', function: '?', lineno: 31, }, { colno: null, filename: 'http://127.0.0.1:8000/js/stacktrace.js', function: '?', lineno: 44, }, ]); }); it('should parse Firefox 7 error', () => { expect(computeStackTrace(FIREFOX_7).stacktrace?.frames).toEqual([ { colno: null, filename: 'file:///G:/js/file.js', function: '?', lineno: 24, }, { colno: null, filename: 'file:///G:/js/file.js', function: 'foo', lineno: 20, }, { colno: null, filename: 'file:///G:/js/file.js', function: 'bar', lineno: 16, }, { colno: null, filename: 'file:///G:/js/file.js', function: 'bar', lineno: 13, }, { colno: null, filename: 'file:///G:/js/stacktrace.js', function: 'printStackTrace', lineno: 18, }, { colno: null, filename: 'file:///G:/js/stacktrace.js', function: '?', lineno: 31, }, { colno: null, filename: 'file:///G:/js/stacktrace.js', function: '?', lineno: 44, }, ]); }); it('should parse Firefox 14 error', () => { expect(computeStackTrace(FIREFOX_14).stacktrace?.frames).toEqual([ { colno: null, filename: 'http://path/to/file.js', function: 'onclick', lineno: 1, }, { colno: null, filename: 'http://path/to/file.js', function: 'dumpException3', lineno: 52, }, { colno: null, filename: 'http://path/to/file.js', function: '?', lineno: 48, }, ]); }); it('should parse Firefox 31 error', () => { expect(computeStackTrace(FIREFOX_31).stacktrace?.frames).toEqual([ { colno: 1, filename: 'http://path/to/file.js', function: '.plugin/e.fn[c]/<', lineno: 1, }, { colno: 1, filename: 'http://path/to/file.js', function: 'bar', lineno: 1, }, { colno: 13, filename: 'http://path/to/file.js', function: 'foo', lineno: 41, }, ]); }); it('should parse Firefox 44 ns exceptions', () => { expect( computeStackTrace(FIREFOX_44_NS_EXCEPTION).stacktrace?.frames ).toEqual([ { colno: 1, filename: 'file:///path/to/index.html', function: '?', lineno: 23, }, { colno: 3, filename: 'file:///path/to/file.js', function: 'bar', lineno: 20, }, { colno: 2, filename: 'file:///path/to/file.js', function: 'App.prototype.foo', lineno: 15, }, { colno: 28, filename: 'http://path/to/file.js', function: '[2]</Bar.prototype._baz/</<', lineno: 703, }, ]); }); it('should parse Chrome error with no location', () => { expect( computeStackTrace({ message: 'foo', name: 'bar', stack: 'error\n at Array.forEach (native)', }).stacktrace?.frames ).toEqual([ { colno: null, filename: 'native', function: 'Array.forEach', lineno: null, }, ]); }); it('should parse Chrome 15 error', () => { expect(computeStackTrace(CHROME_15).stacktrace?.frames).toEqual([ { colno: 4, filename: 'http://path/to/file.js', function: '?', lineno: 24, }, { colno: 5, filename: 'http://path/to/file.js', function: 'foo', lineno: 20, }, { colno: 5, filename: 'http://path/to/file.js', function: 'bar', lineno: 16, }, { colno: 17, filename: 'http://path/to/file.js', function: 'bar', lineno: 13, }, ]); }); it('should parse Chrome 36 error with port numbers', () => { expect(computeStackTrace(CHROME_36).stacktrace?.frames).toEqual([ { colno: 3651, filename: 'http://localhost:8080/file.js', function: 'I.e.fn.(anonymous function) [as index]', lineno: 10, }, { colno: 146, filename: 'http://localhost:8080/file.js', function: 'HTMLButtonElement.onclick', lineno: 107, }, { colno: 27, filename: 'http://localhost:8080/file.js', function: 'dumpExceptionError', lineno: 41, }, ]); }); it('should parse Chrome error with webpack URLs', () => { expect(computeStackTrace(CHROME_XX_WEBPACK).stacktrace?.frames).toEqual([ { colno: 30, filename: 'webpack:///./~/react-proxy/modules/createPrototypeProxy.js?', function: 'TESTTESTTEST.proxiedMethod', lineno: 44, }, { colno: 31, filename: 'webpack:///./~/react-transform-catch-errors/lib/index.js?', function: 'TESTTESTTEST.tryRender', lineno: 34, }, { colno: 32, filename: 'webpack:///./src/components/test/test.jsx?', function: 'TESTTESTTEST.render', lineno: 272, }, { colno: 108, filename: 'webpack:///./src/components/test/test.jsx?', function: 'TESTTESTTEST.eval', lineno: 295, }, ]); }); it('should parse Chrome error with blob URLs', () => { expect(computeStackTrace(CHROME_48_BLOB).stacktrace?.frames).toEqual([ { colno: 2863, filename: 'blob:http%3A//localhost%3A8080/abfc40e9-4742-44ed-9dcd-af8f99a29379', function: 'n.handle', lineno: 7, }, { colno: 3019, filename: 'blob:http%3A//localhost%3A8080/abfc40e9-4742-44ed-9dcd-af8f99a29379', function: 'n.fire', lineno: 7, }, { colno: 6911, filename: 'blob:http%3A//localhost%3A8080/abfc40e9-4742-44ed-9dcd-af8f99a29379', function: '?', lineno: 1, }, { colno: 10978, filename: 'blob:http%3A//localhost%3A8080/d4eefe0f-361a-4682-b217-76587d9f712a', function: '?', lineno: 15, }, { colno: 30039, filename: 'blob:http%3A//localhost%3A8080/abfc40e9-4742-44ed-9dcd-af8f99a29379', function: 'Object.d [as add]', lineno: 31, }, { colno: 29146, filename: 'blob:http%3A//localhost%3A8080/abfc40e9-4742-44ed-9dcd-af8f99a29379', function: 's', lineno: 31, }, { colno: null, filename: 'native', function: 'Error', lineno: null, }, ]); }); it('should parse IE 11 error', () => { expect(computeStackTrace(IE_11).stacktrace?.frames).toEqual([ { colno: 1, filename: 'http://path/to/file.js', function: 'bar', lineno: 108, }, { colno: 13, filename: 'http://path/to/file.js', function: 'foo', lineno: 45, }, { colno: 21, filename: 'http://path/to/file.js', function: 'Anonymous function', lineno: 47, }, ]); }); it('should parse Opera 25 error', () => { expect(computeStackTrace(OPERA_25).stacktrace?.frames).toEqual([ { colno: 168, filename: 'http://path/to/file.js', function: 'bar', lineno: 108, }, { colno: 15, filename: 'http://path/to/file.js', function: 'foo', lineno: 52, }, { colno: 22, filename: 'http://path/to/file.js', function: '?', lineno: 47, }, ]); }); it('should parse Firefox errors with resource: URLs', () => { expect( computeStackTrace(FIREFOX_50_RESOURCE_URL).stacktrace?.frames ).toEqual([ { colno: 25, filename: 'resource://path/data/content/bundle.js', function: 'wrapped', lineno: 7270, }, { colno: 23028, filename: 'resource://path/data/content/vendor.bundle.js', function: 'dispatchEvent', lineno: 18, }, { colno: 16, filename: 'resource://path/data/content/bundle.js', function: 'render', lineno: 5529, }, ]); }); it('should parse Firefox errors with eval URLs', () => { expect(computeStackTrace(FIREFOX_43_EVAL).stacktrace?.frames).toEqual([ { colno: 9, filename: 'http://localhost:8080/file.js', function: '?', lineno: 33, }, { colno: 17, filename: 'http://localhost:8080/file.js', function: 'speak', lineno: 26, }, { colno: 18, filename: 'http://localhost:8080/file.js line 26 > eval', function: '?', lineno: 4, }, { colno: 96, filename: 'http://localhost:8080/file.js line 26 > eval', function: 'foo', lineno: 2, }, { colno: 30, filename: 'http://localhost:8080/file.js line 26 > eval line 2 > eval', function: 'baz', lineno: 1, }, ]); }); }); describe('Tracekit - Custom Tests', () => { it('should parse errors with custom schemes', () => { const CHROMIUM_EMBEDDED_FRAMEWORK_CUSTOM_SCHEME = { message: 'message string', name: 'Error', stack: `Error: message string at examplescheme://examplehost/cd351f7250857e22ceaa.worker.js:70179:15`, }; expect( computeStackTrace(CHROMIUM_EMBEDDED_FRAMEWORK_CUSTOM_SCHEME).stacktrace ?.frames ).toEqual([ { colno: 15, filename: 'examplescheme://examplehost/cd351f7250857e22ceaa.worker.js', function: '?', lineno: 70179, }, ]); }); describe('should parse exceptions with native code frames', () => { it('in Chrome 73', () => { const CHROME73_NATIVE_CODE_EXCEPTION = { message: 'test', name: 'Error', stack: `Error: test at fooIterator (http://localhost:5000/test:20:17) at Array.map (<anonymous>) at foo (http://localhost:5000/test:19:19) at http://localhost:5000/test:24:7`, }; expect( computeStackTrace(CHROME73_NATIVE_CODE_EXCEPTION).stacktrace?.frames ).toEqual([ { colno: 7, filename: 'http://localhost:5000/test', function: '?', lineno: 24, }, { colno: 19, filename: 'http://localhost:5000/test', function: 'foo', lineno: 19, }, { colno: null, filename: '<anonymous>', function: 'Array.map', lineno: null, }, { colno: 17, filename: 'http://localhost:5000/test', function: 'fooIterator', lineno: 20, }, ]); }); it('in Firefox 66', () => { const FIREFOX66_NATIVE_CODE_EXCEPTION = { message: 'test', name: 'Error', stack: `fooIterator@http://localhost:5000/test:20:17 foo@http://localhost:5000/test:19:19 @http://localhost:5000/test:24:7`, }; expect( computeStackTrace(FIREFOX66_NATIVE_CODE_EXCEPTION).stacktrace?.frames ).toEqual([ { colno: 7, filename: 'http://localhost:5000/test', function: '?', lineno: 24, }, { colno: 19, filename: 'http://localhost:5000/test', function: 'foo', lineno: 19, }, { colno: 17, filename: 'http://localhost:5000/test', function: 'fooIterator', lineno: 20, }, ]); }); it('in Safari 12', () => { const SAFARI12_NATIVE_CODE_EXCEPTION = { message: 'test', name: 'Error', stack: `fooIterator@http://localhost:5000/test:20:26 map@[native code] foo@http://localhost:5000/test:19:22 global code@http://localhost:5000/test:24:10`, }; expect( computeStackTrace(SAFARI12_NATIVE_CODE_EXCEPTION).stacktrace?.frames ).toEqual([ { colno: 10, filename: 'http://localhost:5000/test', function: 'global code', lineno: 24, }, { colno: 22, filename: 'http://localhost:5000/test', function: 'foo', lineno: 19, }, { colno: null, filename: '[native code]', function: 'map', lineno: null, }, { colno: 26, filename: 'http://localhost:5000/test', function: 'fooIterator', lineno: 20, }, ]); }); it('in Edge 44', () => { const EDGE44_NATIVE_CODE_EXCEPTION = { message: 'test', name: 'Error', stack: `Error: test at fooIterator (http://localhost:5000/test:20:11) at Array.prototype.map (native code) at foo (http://localhost:5000/test:19:9) at Global code (http://localhost:5000/test:24:7)`, }; expect( computeStackTrace(EDGE44_NATIVE_CODE_EXCEPTION).stacktrace?.frames ).toEqual([ { colno: 7, filename: 'http://localhost:5000/test', function: 'Global code', lineno: 24, }, { colno: 9, filename: 'http://localhost:5000/test', function: 'foo', lineno: 19, }, { colno: null, filename: 'native code', function: 'Array.prototype.map', lineno: null, }, { colno: 11, filename: 'http://localhost:5000/test', function: 'fooIterator', lineno: 20, }, ]); }); }); });
the_stack
import * as collabs from "@collabs/collabs"; import { YataSave } from "../generated/proto_compiled"; type YataOpArgs<T> = [ string, string, string, T, Record<string, any>, Record<string, any>? ]; export class YataOp<T> extends collabs.CObject { readonly creatorId: string; // TODO: readonly (broken only by initial values) public originId: string; // TODO: leftId, rightId need saving public leftId: string; public rightId: string; readonly _deleted: collabs.LWWCVariable<boolean>; readonly content: T; readonly pos: number; readonly attributes: collabs.LWWCMap<string, any>; // Doesn't need saving because it is only used on the // deleting replica, and any loading replica will // necessarily not be the deleter. public locallyDeleted: boolean; public readonly originAttributesAtInput: Record<string, any>; public readonly attributesArg: [string, any][]; static readonly attributesMapCollabName = "attributes"; static readonly deletedFlagCollabName = "deleted"; sameFormatAsPrev(attrName: string) { return ( this.attributes.get(attrName) === this.originAttributesAtInput[attrName] ); } delete(): void { this.locallyDeleted = true; this._deleted.value = true; } get deleted(): boolean { return this._deleted.value; } constructor( initToken: collabs.InitToken, creatorId: string, originId: string, leftId: string, rightId: string, content: T, pos: number, originAttributesAtInput: Record<string, any>, attributes: [string, any][] = [] ) { super(initToken); this.creatorId = creatorId; this.originId = originId; this.leftId = leftId; this.rightId = rightId; this._deleted = this.addChild( YataOp.deletedFlagCollabName, collabs.Pre(collabs.LWWCVariable)<boolean>(false) ); this.locallyDeleted = false; this.content = content; this.pos = pos; this.attributes = this.addChild( YataOp.attributesMapCollabName, collabs.Pre(collabs.LWWCMap)(undefined, undefined) ); this.attributesArg = attributes; this.originAttributesAtInput = originAttributesAtInput; } initAttributes( runLocallyLayer: collabs.RunLocallyLayer, meta: collabs.MessageMeta ) { runLocallyLayer.runLocally(meta, () => { for (const [key, value] of this.attributesArg) { this.attributes.set(key, value); } }); } } interface YataEvent extends collabs.CollabEvent { uid: string; idx: number; } export interface YataInsertEvent<T> extends YataEvent { newOp: YataOp<T>; } export interface YataDeleteEvent<T> extends YataEvent {} export interface YataFormatExistingEvent<T> extends YataEvent { key: string; value: any; } interface YataEventsRecord<T> extends collabs.CollabEventsRecord { Insert: YataInsertEvent<T>; Delete: YataDeleteEvent<T>; FormatExisting: YataFormatExistingEvent<T>; } type m1Args = [ids: string[], attributes: Record<string, any>]; type m2Args<T> = [ uniqueNumber: number, replicaID: string, leftIntent: string, rightIntent: string, content: T, originAttributeEntries: Record<string, any>, attributeEntries?: Record<string, any> ]; export class YataLinear<T> extends collabs.SemidirectProductRev< YataEventsRecord<T>, collabs.Collab, m1Args, m2Args<T> > { private start: string = ""; private end: string = ""; readonly defaultContent: T; public readonly opMap: collabs.DeletingMutCSet<YataOp<T>, YataOpArgs<T>>; protected lastEventType?: string; protected lastEventSender?: string; protected lastEventTime?: number; deletedMessageEventHandler = (yata: YataLinear<T>, uid: string) => ({ meta }: collabs.CollabEvent, caller: collabs.LWWCVariable<boolean>) => { if (caller.value) { if (!yata.op(uid).locallyDeleted) { yata.emit("Delete", { uid, idx: yata.getIdxOfId(uid) + 1, meta, }); } } }; attributesSetEventHandler = (yata: YataLinear<T>, uid: string) => ({ key, meta }: collabs.CMapSetEvent<string, any>) => { if (!yata.op(uid).deleted) { yata.emit("FormatExisting", { uid, idx: yata.getIdxOfId(uid), key, value: yata.op(uid).attributes.get(key), meta, }); } }; opMapAddEventHandler = (yata: YataLinear<T>) => ({ value: newOp, meta }: collabs.CSetEvent<YataOp<T>>) => { // Link YataLinearOp list const uid = yata.idOf(newOp); yata.op(newOp.rightId).leftId = uid; yata.op(newOp.leftId).rightId = uid; // Copy initial attributes to the attributes map newOp.initAttributes(this.runLocallyLayer, meta); // Register event handler for YataOp.deleted "change" event newOp._deleted.on("Set", yata.deletedMessageEventHandler(yata, uid)); // Register event handler for YataOp.attributes "set" event newOp.attributes.on("Set", yata.attributesSetEventHandler(yata, uid)); const insertEvent = { uid, idx: yata.getIdxOfId(uid), newOp, meta, }; yata.emit("Insert", insertEvent); yata.trackM2Event("Insert", insertEvent); }; private readonly idSerializer: collabs.Serializer< collabs.CollabID<YataOp<T>> >; constructor( initToken: collabs.InitToken, defaultContent: T, initialContents: T[] ) { super(initToken); this.defaultContent = defaultContent; // 0 const startArgs: YataOpArgs<T> = ["", "", "", defaultContent, {}]; // Number.MAX_VALUE const endArgs: YataOpArgs<T> = ["", "", "", defaultContent, {}]; // ((idx + 1) * Number.MAX_VALUE) / (initialContents.length + 1) const initialContentsArgs: YataOpArgs<T>[] = initialContents.map((c) => [ "", "", "", c, {}, ]); let inConstructor = true; let constructorIndex = 0; let startOp!: YataOp<T>; let endOp!: YataOp<T>; let initialContentOps: YataOp<T>[] = []; const outerThis = this; this.opMap = this.addSemidirectChild( "nodeMap", collabs.Pre(collabs.DeletingMutCSet)( ( valueInitToken, replicaID, leftIntent, rightIntent, content, originAttributesMapAtInput, attributesMap = {} ) => { if (inConstructor) { let op: YataOp<T>; if (constructorIndex === 0) { // startOp op = startOp = new YataOp( valueInitToken, "", "", "", "", defaultContent, 0, [] ); } else if (constructorIndex === 1) { // endOp op = endOp = new YataOp( valueInitToken, "", "", "", "", defaultContent, Number.MAX_VALUE, [] ); } else { // initialContent op = new YataOp( valueInitToken, "", "", "", "", content, ((constructorIndex - 1) * Number.MAX_VALUE) / (initialContents.length + 1), [] ); initialContentOps.push(op); } constructorIndex++; return op; } else { const originId = leftIntent; let leftId = leftIntent; while (this.op(leftId).rightId !== rightIntent) { const o_id = this.op(leftId).rightId; const o = this.op(this.op(leftId).rightId); const i_origin = this.op(originId); const o_origin = this.op(o.originId); if ( (o.pos < i_origin.pos || i_origin.pos <= o_origin.pos) && (o.originId !== originId || o.creatorId < replicaID) ) { leftId = o_id; } else { if (i_origin.pos >= o_origin.pos) { break; } } } const rightId = this.op(leftId).rightId; // TODO: Replace this with a binary tree (rbtree) const pos = (this.op(leftId).pos + this.op(rightId).pos) / 2; const originAttributesEntriesAtCreate = [ ...this.op(originId).attributes.entries(), ]; for (const [key, value] of originAttributesEntriesAtCreate) { if ( attributesMap[key] !== value && attributesMap[key] === originAttributesMapAtInput[key] ) { attributesMap[key] = value; } } return new YataOp<T>( valueInitToken, replicaID, originId, leftId, rightId, content, pos, originAttributesMapAtInput, Object.entries(attributesMap) ); } }, [startArgs, endArgs, ...initialContentsArgs] ) ); inConstructor = false; this.opMap.on("Add", this.opMapAddEventHandler(this)); this.idSerializer = new collabs.CollabIDSerializer(this.opMap); // Configure the initial ops (like in valueConstructor). this.START = this.idOf(startOp); this.END = this.idOf(endOp); const idOfFn = (c: YataOp<T>) => this.idOf(c); const uids = [this.START] .concat(initialContentOps.map(idOfFn)) .concat([this.END]); initialContentOps.forEach((op, idx) => { op.originId = uids[idx]; op.leftId = uids[idx]; op.rightId = uids[idx + 2]; }); startOp.rightId = uids[1]; endOp.originId = uids[uids.length - 2]; endOp.leftId = uids[uids.length - 2]; const addInitialContentOpEventHandlers = (yata: YataLinear<T>) => (op: YataOp<T>, uid: string) => { // Register event handler for YataOp.deleted "change" event op._deleted.on("Any", yata.deletedMessageEventHandler(yata, uid)); // Register event handler for YataOp.attributes "set" event op.attributes.on("Set", yata.attributesSetEventHandler(yata, uid)); }; initialContentOps.forEach((op) => addInitialContentOpEventHandlers(this)(op, idOfFn(op)) ); } // OPT: ids are actually just names converted to Uint8Arrays, // so this redundantly converts string -> Uint8Array -> string. private idOf(op: YataOp<T>): string { return collabs.bytesAsString( this.idSerializer.serialize(collabs.CollabID.fromCollab(op, this.opMap)) ); } private getById(id: string): YataOp<T> { return ( this.idSerializer .deserialize(collabs.stringAsBytes(id)) // Existence assertion is okay because we never delete from opMap. .get(this.opMap)! ); } private delete(id: string): void { this.op(id).delete(); } m1(ids: string[], attributes: Record<string, any>) { // Formatting operation for (const id of ids) { for (const attr in attributes) { this.op(id).attributes.set(attr, attributes[attr]); } } } m2(...args: m2Args<T>): void { // Insertion operation this.opMap.pureAdd(...args); } protected action( m2TargetPath: string[], m2Timestamp: collabs.CRDTMeta | null, m2Message: collabs.m2Start<m2Args<T>>, // User-defined m2TrackedEvents: [string, any][], m1TargetPath: string[], m1Timestamp: collabs.CRDTMeta, m1Message: collabs.m1Start<m1Args> // User-defined ) { // Conflict resolution function let newM1 = m1Message; for (let [name, event] of m2TrackedEvents) { if (name === "Insert") { const insertion = (event as YataInsertEvent<string>).newOp; const insertionUid = (event as YataInsertEvent<string>).uid; if (m1Message.args[0].includes(insertion.originId)) { for (const [attrName, _] of Object.entries(m1Message.args[1])) { if (insertion.sameFormatAsPrev(attrName)) { newM1.args[0] = newM1.args[0].concat([insertionUid]); } } } } } return { m1TargetPath, m1Message: newM1 }; } private insert( replicaID: string, leftIntent: string, rightIntent: string, content: T, originAttributeEntries: Record<string, any>, attributeEntries?: Record<string, any> ): void { this.m2( this.runtime.getReplicaUniqueNumber(), replicaID, leftIntent, rightIntent, content, originAttributeEntries, attributeEntries ); } private changeAttributes(id: string, attributes: Record<string, any>): void { this.m1([id], attributes); } // TODO: Make iterative instead of recursive private toArrayNode( nodeId: string ): { insert: T; attributes: Record<string, any> }[] { const node = this.op(nodeId); if (node.pos === 0) return []; const arr = this.toArrayNode(node.leftId); if (!node.deleted) { const formats: Record<string, any> = {}; const it = node.attributes.entries(); let result = it.next(); while (!result.done) { formats[result.value[0] as string] = result.value[1]; result = it.next(); } arr.push({ insert: node.content, attributes: formats, }); } return arr; } private toIdArrayNode(nodeId: string): string[] { const node = this.op(nodeId); if (node.pos === Number.MAX_VALUE) return [this.END]; const array = this.toIdArrayNode(node.rightId); if (!node.deleted) { array.unshift(nodeId); } return array; } toIdArray(): string[] { const arr = this.toIdArrayNode(this.START); return arr; } op(id: string): YataOp<T> { const yataOp = this.getById(id); if (!yataOp) { throw new Error(`There is no Yata operation with id ${id}`); } return yataOp; } get START(): string { return this.start; } set START(s: string) { this.start = s; } get END(): string { return this.end; } set END(e: string) { this.end = e; } toArray(): { insert: T; attributes: Record<string, any> }[] { return this.toArrayNode(this.op(this.END).leftId); } getIdAtIdx(idx: number): string { return this.toIdArray()[idx + 1]; } insertByIdx( replicaID: string, idx: number, content: T, attributeObj?: Record<string, any> ): void { let idLeftOfCursor = this.getIdAtIdx(idx - 1); // TODO: Optimize idx to id conversion with a binary tree (rbtree) console.log("idx:", idx); console.log("idLeftOfCursor:", idLeftOfCursor); this.insert( replicaID, idLeftOfCursor, this.op(idLeftOfCursor).rightId, content, Object.fromEntries([...this.op(idLeftOfCursor).attributes.entries()])!, attributeObj ); // if (attributeObj) { // this.changeAttributes(uid, attributeObj); // } } deleteByIdx(idx: number, len: number): void { const id1 = this.getIdAtIdx(idx); const id2 = this.getIdAtIdx(idx + len); let id = id1; while (id !== id2) { if (!this.op(id).deleted) { this.delete(id); } id = this.op(id).rightId; } } changeAttributeByIdx( idx: number, len: number, attributes: Record<string, any> ): void { const id1 = this.getIdAtIdx(idx); const id2 = this.getIdAtIdx(idx + len); let id = id1; while (id !== id2) { if (!this.op(id).deleted) { this.changeAttributes(id, attributes); } id = this.op(id).rightId; } } getIdxOfId(id: string): number { if (id === this.START) return -1; const prev = this.getIdxOfId(this.op(id).leftId); if (this.op(id).deleted) return prev; return 1 + prev; } toOpArray(): YataOp<T>[] { const getOpFn = (id: string) => this.op(id); return this.toIdArray().map(getOpFn); } protected saveSemidirectProductRev(): Uint8Array { // Note we also include deleted ids. const idArray: string[] = []; let op = this.START; while (true) { idArray.push(op); if (op === this.END) break; else op = this.getById(op)!.rightId; } const saveData = YataSave.create({ idArray, }); return YataSave.encode(saveData).finish(); } protected loadSemidirectProductRev(saveData: collabs.Optional<Uint8Array>) { if (!saveData.isPresent) return; // Set leftId, rightId's based on saved order. const message = YataSave.decode(saveData.get()); for (let i = 0; i < message.idArray.length - 1; i++) { const left = message.idArray[i]; const right = message.idArray[i + 1]; this.getById(left)!.rightId = right; this.getById(right)!.leftId = left; } } }
the_stack
namespace $ { export function $mol_build_start( this: $, paths : string[], ) { var build = $mol_build.relative( '.' ) if( paths.length > 0 ) { try { paths.forEach( ( path : string )=> { path = build.root().resolve( path ).path() return build.bundleAll( { path } ) } ) process.exit(0) } catch( error: any ) { this.$mol_log3_fail({ place: '$mol_build_start' , message: error.message, trace: error.stack, }) process.exit(1) } } else { Promise.resolve().then( ()=> build.server().start() ) } } setTimeout( ()=> $mol_wire_async( $mol_ambient({}) ).$mol_build_start( process.argv.slice( 2 ) ) ) export class $mol_build extends $mol_object { @ $mol_mem_key static root( path : string ) { return this.make({ root : ()=> $mol_file.absolute( path ) , }) } static relative( path : string ) { return $mol_build.root( $mol_file.relative( path ).path() ) } @ $mol_mem server() { return $mol_build_server.make({ build : $mol_const( this ) , }) } root() { return $mol_file.relative( '.' ) } @ $mol_mem_key metaTreeTranspile( path : string ) { const file = $mol_file.absolute( path ) const name = file.name() const tree = $mol_tree.fromString( file.text() , file.path() ) let content = '' for( const step of tree.select( 'build' , '' ).sub ) { const res = this.$.$mol_exec( file.parent().path() , step.value ).stdout.toString().trim() if( step.type ) content += `let ${ step.type } = ${ JSON.stringify( res ) }` } if( !content ) return [] const script = file.parent().resolve( `-meta.tree/${ name }.ts` ) script.text( content ) return [ script ] } @ $mol_mem_key viewTreeTranspile( path : string ) { const file = $mol_file.absolute( path ) const name = file.name() const script = file.parent().resolve( `-view.tree/${ name }.ts` ) const sourceMap = file.parent().resolve( `-view.tree/${ name }.map` ) const locale = file.parent().resolve( `-view.tree/${ name }.locale=en.json` ) const text = file.text() const tree = this.$.$mol_tree2_from_string( text , file.path() ) const res = this.$.$mol_view_tree2_ts_compile( tree ) script.text( res.script ) // sourceMap.text( res.map ) locale.text( JSON.stringify( res.locales , null , '\t' ) ) return [ script , locale ] } @ $mol_mem_key cssTranspile( path : string ) { const file = $mol_file.absolute( path ) const name = file.name() const script = file.parent().resolve( `-css/${ name }.ts` ) const id = file.relate( this.root() ) const styles = file.text() const code = 'namespace $ { $'+`mol_style_attach( ${ JSON.stringify( id ) },\n ${ JSON.stringify( styles ) }\n) }` script.text( code ) return [ script ] } @ $mol_mem_key mods( { path , exclude } : { path : string , exclude? : string[] } ) { const parent = $mol_file.absolute( path ) const mods : $mol_file[] = [] parent.sub().forEach( child => { const name = child.name() if( !/^[a-z0-9]/i.test( name ) ) return false if( exclude && RegExp( '[.=](' + exclude.join( '|' ) + ')[.]' , 'i' ).test( name ) ) return false // if (! child.exists()) return false if( /(meta\.tree)$/.test( name ) ) { mods.push( ... this.metaTreeTranspile( child.path() ) ) } else if( /(view\.tree)$/.test( name ) ) { mods.push( ... this.viewTreeTranspile( child.path() ) ) } else if( /(\.css)$/.test( name ) ) { mods.push( ... this.cssTranspile( child.path() ) ) } mods.push( child ) return true } ) //mods.sort( ( a , b )=> a.name().length - b.name().length ) return mods } // @ $mol_mem_key // modsRecursive( { path , exclude } : { path : string , exclude? : string[] } ) : $mol_file[] { // var mod = $mol_file.absolute( path ) // switch( mod.type() ) { // case 'file' : // return [ mod ] // case 'dir' : // var mods = [ mod ] // for( var m of this.mods( { path , exclude } ) ) { // if( m.type() !== 'dir' ) continue // for( var dep of this.modsRecursive( { path : m.path() , exclude } ) ) { // if( mods.indexOf( dep ) !== -1 ) continue // mods.push( dep ) // } // } // return mods // default : // throw new Error( `Unsupported type "${mod.type()}" of "${mod.relate()}"` ) // } // } @ $mol_mem_key sources( { path , exclude } : { path : string , exclude? : string[] } ) : $mol_file[] { const mod = $mol_file.absolute( path ) if ( ! mod.exists() ) return [] switch( mod.type() ) { case 'file' : return [ mod ] case 'dir' : return this.mods( { path , exclude } ).filter( mod => mod.type() === 'file' ) default: return [] } } @ $mol_mem_key sourcesSorted( { path , exclude } : { path : string , exclude? : string[] } ) : $mol_file[] { const mod = $mol_file.absolute( path ) const graph = new $mol_graph< string , { priority : number } >() const sources = this.sources( { path , exclude } ) for( let src of sources ) { graph.nodes.add( src.relate( this.root() ) ) } for( let src of sources ) { let deps = this.srcDeps( src.path() ) for( let p in deps ) { var names : string[] if( p[ 0 ] === '/' ) { names = p.substring( 1 ).split( '/' ) } else if( p[ 0 ] === '.' ) { names = mod.resolve( p ).relate( this.root() ).split( '/' ) } else { names = [ 'node_modules' , ... p.split( '/' ) ] } let files = [ this.root() ] for( let name of names ) { let nextFiles : $mol_file[] = [] for( let file of files ) { let validName = new RegExp( `^(${file.name()})?${name}(?![a-z0-9])` , 'i' ) for( let child of this.mods( { path : file.path() , exclude } ) ) { if( !child.name().match( validName ) ) continue nextFiles.push( child ) } } if( nextFiles.length === 0 ) break files = nextFiles } for( let file of files ) { if( file === this.root() ) continue const from = src.relate( this.root() ) if( !graph.nodes.has( from ) ) continue const to = file.relate( this.root() ) if( !graph.nodes.has( to ) ) continue graph.link( from , to , { priority : deps[ p ] } ) } } } graph.acyclic( edge => edge.priority ) let next = [ ... graph.sorted ].map( name => this.root().resolve( name ) ) return next } @ $mol_mem_key sourcesAll( { path , exclude } : { path : string , exclude? : string[] } ) : $mol_file[] { const sortedPaths = this.graph( { path , exclude } ).sorted const sources = new Set< $mol_file >() sortedPaths.forEach( path => { const mod = this.root().resolve( path ) this.sourcesSorted( { path : mod.path() , exclude } ).forEach( src => { sources.add( src ) } ) } ) return [ ... sources ] } @ $mol_mem tsOptions() { const rawOptions = JSON.parse( this.root().resolve( 'tsconfig.json' ).text() + '').compilerOptions const res = $node.typescript.convertCompilerOptionsFromJson( rawOptions , "." , 'tsconfig.json' ) if( res.errors.length ) throw res.errors return res.options } @ $mol_mem_key tsSource( { path , target } : { path : string , target : number } ) { const content = $mol_file.absolute( path ).text() return $node.typescript.createSourceFile( path , content , target ) } @ $mol_mem_key tsPaths( { path , exclude , bundle } : { path : string , bundle : string , exclude : string[] } ) { const sources = this.sourcesAll( { path , exclude } ).filter( src => /tsx?$/.test( src.ext() ) ) if( sources.length && bundle === 'node' ) { const types = [] as string[] for( let dep of this.nodeDeps({ path , exclude }) ) { types.push( '\t' + JSON.stringify( dep ) + ' : typeof import( ' + JSON.stringify( dep ) + ' )' ) } const node_types = $mol_file.absolute( path ).resolve( `-node/deps.d.ts` ) node_types.text( 'interface $node {\n ' + types.join( '\n' ) + '\n}' ) sources.push( node_types ) } return sources.map( src => src.path() ) } @ $mol_mem_key tsHost( { path , exclude , bundle } : { path : string , bundle : string , exclude : string[] } ) { const host = $node.typescript.createCompilerHost( this.tsOptions() ) host.fileExists = ( path )=> $mol_file.relative( path ).exists() host.readFile = ( path )=> $mol_file.relative( path ).text() host.writeFile = ( path , text )=> $mol_file.relative( path ).text( text, 'virt' ) return host } @ $mol_mem_key tsTranspiler( { path , exclude , bundle } : { path : string , bundle : string , exclude : string[] } ) { return $node.typescript.createProgram( this.tsPaths({ path , exclude , bundle }) , this.tsOptions() , this.tsHost({ path , exclude , bundle }) , ) } @ $mol_mem_key tsTranspile( { path , exclude , bundle } : { path : string , bundle : string , exclude : string[] } ) { const res = this.tsTranspiler({ path , exclude , bundle }).emit() return res } @ $mol_mem_key tsService( { path , exclude , bundle } : { path : string , bundle : string , exclude : string[] } ) { const paths = this.tsPaths({ path , exclude , bundle }) if( !paths.length ) return null const watchers = new Map< string , ( path : string , kind : number )=> void >() let run = ()=> {} var host = $node.typescript.createWatchCompilerHost( paths , { ... this.tsOptions(), emitDeclarationOnly : true, }, { ... $node.typescript.sys , writeFile : (path , data )=> { $mol_file.relative( path ).text( data, 'virt' ) }, setTimeout : ( cb : any )=> { run = cb } , watchFile : (path:string, cb:(path:string,kind:number)=>any )=> { watchers.set( path , cb ) return { close(){ } } }, }, $node.typescript.createSemanticDiagnosticsBuilderProgram, ( diagnostic )=> { if( diagnostic.file ) { const error = new Error( $node.typescript.formatDiagnostic( diagnostic , { getCurrentDirectory : ()=> this.root().path() , getCanonicalFileName : ( path : string )=> path.toLowerCase() , getNewLine : ()=> '\n' , }) ) this.js_error( diagnostic.file.getSourceFile().fileName , error ) } else { this.$.$mol_log3_fail({ place : `${this}.tsService()` , message: String( diagnostic.messageText ) , }) } } , () => {} , ) const service = $node.typescript.createWatchProgram( host ) const versions = {} as Record< string , number > return { recheck: ()=> { for( const path of paths ) { const version = $node.fs.statSync( path ).mtime.valueOf() if( versions[ path ] && versions[ path ] !== version ) { this.js_error( path, null ) const watcher = watchers.get( path ) if( watcher ) watcher( path , 2 ) } versions[ path ] = version } run() }, destructor : ()=> service.close() } } @ $mol_mem_key js_error( path : string , next = null as null | Error ) { this.js_content( path ) return next } @ $mol_mem_key js_content( path : string ) { const src = $mol_file.absolute( path ) if( /\.tsx?$/.test( src.name() ) ) { const res = $node.typescript.transpileModule( src.text() , { compilerOptions : this.tsOptions() } ) if( res.diagnostics?.length ) { return $mol_fail( new Error( $node.typescript.formatDiagnostic( res.diagnostics[0] , { getCurrentDirectory : ()=> this.root().path() , getCanonicalFileName : ( path : string )=> path.toLowerCase() , getNewLine : ()=> '\n' , }) ) ) } const map = JSON.parse( res.sourceMapText! ) as $mol_sourcemap_raw map.file = src.relate() map.sources = [ src.relate() ] return { text : res.outputText.replace( /^\/\/#\ssourceMappingURL=[^\n]*/mg , '//' + src.relate() )+'\n', map : map, } } else { const srcMap = src.parent().resolve( src.name() + '.map' ); return { text : src.text().replace( /^\/\/#\ssourceMappingURL=/mg , '//' )+'\n', map : srcMap.exists() ? JSON.parse( srcMap.text() ) as $mol_sourcemap_raw : undefined } } } @ $mol_mem_key sourcesJS( { path , exclude } : { path : string , exclude : string[] } ) : $mol_file[] { var sources = this.sourcesAll( { path , exclude } ) const types = { 'svg' : 'image/svg+xml' , 'png' : 'image/png' , 'jpg' : 'image/jpeg' , 'jpeg' : 'image/jpeg' , 'gif' : 'image/gif' , 'webp' : 'image/webp' , 'bin' : 'application/octet-stream' , } // this.tsTranspile({ path , exclude , bundle : 'web' }) sources = sources.map( src => { const ext = src.ext().replace( /^.*\./ , '' ) if( types[ ext ] ) { const script = src.parent().resolve( `-bin/${ src.name() }.js` ) const payload = $mol_base64_encode( src.buffer() ) const path = src.relate( this.root() ) const uri = `data:${ types[ext] };base64,${ payload }` script.text( `var $node = $node || {} ; $node[ ${ JSON.stringify( '/' + path ) } ] = ${ JSON.stringify( uri ) }\n` ) return script } // if( /^tsx?$/.test( ext ) ) { // return src.parent().resolve( src.name().replace( /\.tsx?$/ , '.js' ) ) // } if( /^[jt]sx?$/.test( ext ) ) { // if( 'js' === ext ) { return src } } ).filter( Boolean ) as $mol_file[] return sources } @ $mol_mem_key sourcesDTS( { path , exclude } : { path : string , exclude? : string[] } ) : $mol_file[] { let sources = this.sourcesAll( { path , exclude } ) sources = sources.filter( src => /(tsx?)$/.test( src.ext() ) ) sources = sources.map( src => src.parent().resolve( src.name().replace( /(\.d)?\.tsx?$/ , '.d.ts' ) ) ) return sources } @ $mol_mem_key sourcesCSS( { path , exclude } : { path : string , exclude? : string[] } ) : $mol_file[] { return this.sourcesAll( { path , exclude } ).filter( src => /(css)$/.test( src.ext() ) ) } static dependors : { [ index : string ] : undefined | ( ( source : $mol_file )=> { [ index : string ] : number } ) } = {} @ $mol_mem_key srcDeps( path : string ) { const src = $mol_file.absolute( path ) let ext = src.ext() if( !ext ) return {} let dependencies while( !dependencies ) { dependencies = $mol_build.dependors[ ext ] if( dependencies ) break var extShort = ext.replace( /^[^.]*\./ , '' ) if( ext === extShort ) break ext = extShort } return dependencies ? dependencies( src ) : {} } @ $mol_mem_key modDeps( { path , exclude } : { path : string , exclude? : string[] } ) { const mod = $mol_file.absolute( path ) const depends : { [ index : string ] : number } = mod === this.root() ? {} : { '..' : Number.MIN_SAFE_INTEGER } for( var src of this.sources( { path , exclude } ) ) { $mol_build_depsMerge( depends , this.srcDeps( src.path() ) ) } return depends } @ $mol_mem_key dependencies( { path , exclude } : { path : string , exclude? : string[] } ) { var mod = $mol_file.absolute( path ) if ( ! mod.exists() ) return {} switch( mod.type() ) { case 'file' : return this.srcDeps( path ) case 'dir' : return this.modDeps( { path , exclude } ) default : return {} } } @ $mol_mem_key modEnsure( path : string ) { var mod = $mol_file.absolute( path ) if( mod === this.root() ) return false var parent = mod.parent() this.modEnsure( parent.path() ) var mapping = this.modMeta( parent.path() ) if( mod.exists() ) { try { if( mod.type() !== 'dir' ) return false const git_dir = mod.resolve( '.git' ) if( git_dir.exists() ) return false for( let repo of mapping.select( 'pack' , mod.name() , 'git' ).sub ) { this.$.$mol_exec( mod.path() , 'git' , 'init' ) const res = this.$.$mol_exec( mod.path() , 'git' , 'remote' , 'show' , repo.value ) const matched = res.stdout.toString().match( /HEAD branch: (.*?)\n/ ) const head_branch_name = res instanceof Error || matched === null || !matched[1] ? 'master' : matched[1] this.$.$mol_exec( mod.path() , 'git' , 'remote' , 'add' , '--track' , head_branch_name! , 'origin' , repo.value ) this.$.$mol_exec( mod.path() , 'git' , 'pull' ) mod.reset() for ( const sub of mod.sub() ) { sub.reset() } return true } } catch( error: any ) { this.$.$mol_log3_fail({ place: `${this}.modEnsure()` , path , message: error.message , }) } return false } for( let repo of mapping.select( 'pack' , mod.name() , 'git' ).sub ) { this.$.$mol_exec( this.root().path() , 'git' , 'clone' , repo.value , mod.path() ) mod.reset() return true } if( parent === this.root() ) { throw new Error( `Root package "${ mod.relate( this.root() ) }" not found` ) } if( parent.name() === 'node_modules' || ( parent === this.root().resolve( 'node' ) )&&( mod.name() !== 'node' ) ) { $node[ mod.name() ] // force autoinstall through npm } return false } @ $mol_mem_key modMeta( path : string ) { const decls = [] as $mol_tree[] const pack = $mol_file.absolute( path ) for( const file of pack.sub() ) { if( !/\.meta\.tree$/.test( file.name() ) ) continue decls.push( ... $mol_tree.fromString( file.text() , file.path() ).sub ) } return new $mol_tree({ sub : decls }) } @ $mol_mem_key graph( { path , exclude } : { path : string , exclude? : string[] } ) { let graph = new $mol_graph< string , { priority : number } >() let added : { [ path : string ] : boolean } = {} var addMod = ( mod : $mol_file )=> { if( added[ mod.path() ] ) return added[ mod.path() ] = true graph.nodes.add( mod.relate( this.root() ) ) const checkDep = ( p : string )=> { const isFile = /\.\w+$/.test( p ) var dep = ( p[ 0 ] === '/' ) ? this.root().resolve( p + ( isFile ? '' : '/' + p.replace( /.*\// , '' ) ) ) : ( p[ 0 ] === '.' ) ? mod.resolve( p ) : this.root().resolve( 'node_modules' ).resolve( './' + p ) try { this.modEnsure( dep.path() ) } catch( error: any ) { error.message = `${ error.message }\nDependency "${ dep.relate( this.root() ) }" from "${ mod.relate( this.root() ) }" ` $mol_fail_hidden(error) } while( !dep.exists() ) dep = dep.parent() if( dep.type() === 'dir' && dep.name() !== 'index' ) { let index = dep.resolve( 'index.js' ) if( index.exists() ) dep = index } //if( dep.type() === 'file' ) dep = dep.parent() if( mod === dep ) return const from = mod.relate( this.root() ) const to = dep.relate( this.root() ) const edge = graph.edges_out.get( from )?.get( to ) if( !edge || ( deps[ p ] > edge.priority ) ) { graph.link( from , to , { priority : deps[ p ] } ) } addMod( dep ) } let deps = this.dependencies( { path : mod.path() , exclude } ) for( let p in deps ) { checkDep( p ) } } this.modEnsure( path ) addMod( $mol_file.absolute( path ) ) graph.acyclic( edge => edge.priority ) return graph } @ $mol_action bundleAllWeb( { path } : { path : string } ) { this.bundle({ path , bundle : 'web.deps.json' }) this.bundle({ path , bundle : 'web.css' }) this.bundle({ path , bundle : 'web.js' }) this.bundle({ path , bundle : 'web.test.js' }) this.bundle({ path , bundle : 'web.test.html' }) this.bundle({ path , bundle : 'web.view.tree' }) this.bundle({ path , bundle : 'web.locale=en.json' }) return null } @ $mol_action bundleAllWebAudit( { path } : { path : string } ) { this.bundle({ path , bundle : 'web.audit.js' }) this.bundle({ path , bundle : 'web.d.ts' }) } @ $mol_action bundleAllNode( { path } : { path : string } ) { this.bundle({ path , bundle : 'node.deps.json' }) this.bundle({ path , bundle : 'node.js' }) this.bundle({ path , bundle : 'node.test.js' }) this.bundle({ path , bundle : 'node.view.tree' }) this.bundle({ path , bundle : 'node.locale=en.json' }) return null } @ $mol_action bundleAllNodeAudit( { path } : { path : string } ) { this.bundle({ path , bundle : 'node.audit.js' }) this.bundle({ path , bundle : 'node.d.ts' }) } @ $mol_action bundleAll( { path } : { path : string } ) { this.bundle({ path , bundle : 'index.html' }) this.bundle({ path , bundle : 'test.html' }) this.bundleAllWeb({ path }) this.bundleAllWebAudit({ path }) this.bundleAllNode({ path }) this.bundleAllNodeAudit({ path }) this.bundle({ path , bundle : 'package.json' }) this.bundle({ path , bundle : 'readme.md' }) this.bundleFiles( { path , exclude : [ 'node' ] } ) this.bundleCordova( { path , exclude : [ 'node' ] } ) return null } @ $mol_mem_key bundle( { path , bundle = '' } : { path : string , bundle? : string } ) { bundle = bundle && bundle.replace( /\.map$/ , '' ) var envsDef = [ 'web' , 'node' ] var envs = bundle ? [] as string[] : envsDef.slice() var stages = [ 'test' , 'dev' ] var moduleTargets = ['', 'esm'] if( bundle ) { var [ bundle , tags , type , locale ] = /^(.*?)(?:\.(audit\.js|test\.js|test\.html|js|css|deps\.json|locale=(\w+)\.json))?$/.exec( bundle )! tags.split( '.' ).forEach( tag => { if( envsDef.indexOf( tag ) !== -1 ) envs = [ tag ] } ) } var res : $mol_file[] = [] envs.forEach( env => { var exclude = envsDef.filter( e => e !== env ).concat( stages ) if( !type || type === 'deps.json' ) { res = res.concat( this.bundleDepsJSON( { path , exclude , bundle : env } ) ) } if( !type || type === 'css' ) { res = res.concat( this.bundleCSS( { path , exclude , bundle : env } ) ) } if( !type || type === 'js' ) { moduleTargets.forEach( moduleTarget => { res = res.concat( this.bundleJS( { path , exclude , bundle : env, moduleTarget } ) ) } ) } if( !type || type === 'test.js' ) { res = res.concat( this.bundleTestJS( { path , exclude , bundle : env } ) ) } if( !type || type === 'audit.js' ) { res = res.concat( this.bundleAuditJS( { path , exclude , bundle : env } ) ) } if( !type || type === 'd.ts' ) { res = res.concat( this.bundleDTS( { path , exclude , bundle : env } ) ) } if( !type || type === 'view.tree' ) { res = res.concat( this.bundleViewTree( { path , exclude , bundle : env } ) ) } if( !type || /^locale=(\w+).json$/.test( type ) ) { res = res.concat( this.bundleLocale( { path , exclude , bundle : env } ) ) } } ) if( !bundle || bundle === 'package.json' ) { res = res.concat( this.bundlePackageJSON( { path , exclude : [ 'web', 'test' ] } ) ) } if( !bundle || bundle === 'readme.md' ) { res = res.concat( this.bundleReadmeMd( { path , exclude : [ 'web' ] } ) ) } if( !bundle || bundle === 'index.html' ) { res = res.concat( this.bundleIndexHtml( { path } ) ) } if( !bundle || bundle === 'test.html' ) { res = res.concat( this.bundleTestHtml( { path } ) ) } if( !bundle || /\//.test( bundle ) ) { res = res.concat( this.bundleFiles( { path , exclude : [ 'node' ] } ) ) } return res } logBundle( target : $mol_file , duration : number ) { const path = target.relate( this.root() ) this.$.$mol_log3_done({ place: this , duration: `${duration}ms` , message: `Built` , path , }) } @ $mol_mem_key bundleJS( { path , exclude , bundle , moduleTarget } : { path : string , exclude : string[] , bundle : string, moduleTarget? : string } ) : $mol_file[] { const start = Date.now() var pack = $mol_file.absolute( path ) var mt = moduleTarget ? `.${moduleTarget}` : '' var target = pack.resolve( `-/${bundle}${mt}.js` ) var targetMap = pack.resolve( `-/${bundle}${mt}.js.map` ) var sources = this.sourcesJS( { path , exclude } ) if( sources.length === 0 ) return [] var concater = new $mol_sourcemap_builder( target.name(), ';') concater.add( '"use strict"' ) if( bundle === 'node' ) { concater.add( 'var exports = void 0' ) } else { concater.add( 'function require'+'( path ){ return $node[ path ] }' ) } const errors = [] as Error[] sources.forEach( ( src )=> { if( bundle === 'node' ) { if( /node_modules\//.test( src.relate( this.root() ) ) ) { return } } try { const content = this.js_content( src.path() ) const isCommonJs = /typeof +exports|module\.exports|\bexports\.\w+\s*=/.test( content.text ) if( isCommonJs ) { concater.add( `\nvar $node = $node || {}\nvoid function( module ) { var exports = module.${''}exports = this; function require( id ) { return $node[ id.replace( /^.\\// , "` + src.parent().relate( this.root().resolve( 'node_modules' ) ) + `/" ) ] }; \n`, '-' ) } concater.add( content.text , src.relate( target.parent() ) , content.map ) if( isCommonJs ) { const idFull = src.relate( this.root().resolve( 'node_modules' ) ) const idShort = idFull.replace( /\/index\.js$/ , '' ).replace( /\.js$/ , '' ) concater.add( `\n$${''}node[ "${ idShort }" ] = $${''}node[ "${ idFull }" ] = module.${''}exports }.call( {} , {} )\n`, '-' ) } } catch( error: any ) { errors.push( error ) } } ) if( moduleTarget === 'esm' ) { concater.add( 'export default $', '-' ) } target.text( concater.content + '\n//# sourceMappingURL=' + targetMap.relate( target.parent() )+'\n' ) targetMap.text( concater.toString() ) this.logBundle( target , Date.now() - start ) if( errors.length ) $mol_fail_hidden( new $mol_error_mix( `Build fail ${path}`, ...errors ) ) return [ target , targetMap ] } @ $mol_mem_key bundleAuditJS( { path , exclude , bundle } : { path : string , exclude : string[] , bundle : string } ) : $mol_file[] { const start = Date.now() var pack = $mol_file.absolute( path ) var target = pack.resolve( `-/${bundle}.audit.js` ) var exclude_ext = exclude.filter( ex => ex !== 'test' && ex !== 'dev' ) this.tsService({ path , exclude : exclude_ext , bundle })?.recheck() const errors = [] as Error[] const paths = this.tsPaths({ path , exclude: exclude_ext , bundle }) for( const path of paths ) { const src = this.$.$mol_file.absolute( path ) src.text() // recheck on file change const error = this.js_error( path ) if( !error ) continue errors.push( error ) } this.logBundle( target , Date.now() - start ) if( errors.length ) { $mol_fail_hidden( new $mol_error_mix( `Build fail ${path}`, ... errors ) ) } target.text( 'console.info("Audit passed")' ) return [ target ] } @ $mol_mem_key bundleTestJS( { path , exclude , bundle } : { path : string , exclude : string[] , bundle : string } ) : $mol_file[] { const start = Date.now() var pack = $mol_file.absolute( path ) var root = this.root() var target = pack.resolve( `-/${bundle}.test.js` ) var targetMap = pack.resolve( `-/${bundle}.test.js.map` ) var concater = new $mol_sourcemap_builder( target.name(), ';') concater.add( '"use strict"' ) var exclude_ext = exclude.filter( ex => ex !== 'test' && ex !== 'dev' ) var sources = this.sourcesJS( { path , exclude : exclude_ext } ) var sourcesNoTest = new Set( this.sourcesJS( { path , exclude } ) ) var sourcesTest = sources.filter( src => !sourcesNoTest.has( src ) ) if( bundle === 'node' ) { sourcesTest = [ ... sourcesNoTest , ... sourcesTest ] } else { concater.add( 'function require'+'( path ){ return $node[ path ] }' ) } if( sources.length === 0 ) return [] const errors = [] as Error[] sourcesTest.forEach( ( src )=> { if( bundle === 'node' ) { if( /node_modules\//.test( src.relate( root ) ) ) { return } } try { const content = this.js_content( src.path() ) concater.add( content.text, src.relate( target.parent() ), content.map) } catch( error: any ) { errors.push( error ) } } ) target.text( concater.content + '\n//# sourceMappingURL=' + targetMap.relate( target.parent() )+'\n' ) targetMap.text( concater.toString() ) this.logBundle( target , Date.now() - start ) if( errors.length ) $mol_fail_hidden( new $mol_error_mix( `Build fail ${path}`, ...errors ) ) if( bundle === 'node' ) { this.$.$mol_exec( this.root().path() , 'node' , '--trace-uncaught', target.path() ) } return [ target , targetMap ] } @ $mol_mem_key bundleTestHtml( { path } : { path : string } ) : $mol_file[] { const start = Date.now() const pack = $mol_file.absolute( path ) const source = pack.resolve( 'index.html' ) const target = pack.resolve( `-/test.html` ) let content = source.exists() ? source.text() : `<!doctype html><meta charset="utf-8" /><body><script src="web.js" charset="utf-8"></script>` content = content.replace( /(<\/body>|$)/ , ` <script src="/mol/build/client/client.js" charset="utf-8"></script> <script> addEventListener( 'load', ()=> { const test = document.createElement( 'script' ) test.src = 'web.test.js' const audit = document.createElement( 'script' ) audit.src = 'web.audit.js' test.onload = ()=> document.head.appendChild( audit ) document.head.appendChild( test ) } ) </script> $1`, ) target.text( content ) this.logBundle( target , Date.now() - start ) return [ target ] } @ $mol_mem_key bundleDTS( { path , exclude , bundle } : { path : string , exclude? : string[] , bundle : string } ) : $mol_file[] { const start = Date.now() var pack = $mol_file.absolute( path ) var target = pack.resolve( `-/${bundle}.d.ts` ) var sources = this.sourcesDTS( { path , exclude } ) if( sources.length === 0 ) return [] var concater = new $mol_sourcemap_builder( target.name() ) sources.forEach( function( src ) { if( ! src.exists() || ! src.text() ) return concater.add( src.text(), src.relate( target.parent() ) ) } ) target.text( concater.content + '\nexport = $;' ) this.logBundle( target , Date.now() - start ) return [ target ] } @ $mol_mem_key bundleViewTree( { path , exclude , bundle } : { path : string , exclude? : string[] , bundle : string } ) : $mol_file[] { const start = Date.now() var pack = $mol_file.absolute( path ) var target = pack.resolve( `-/${bundle}.view.tree` ) var sources = this.sourcesAll({ path , exclude }) .filter( src => /view.tree$/.test( src.ext() ) ) if( sources.length === 0 ) return [] target.text( sources.map( src => src.text() ).join( '\n' ) ) this.logBundle( target , Date.now() - start ) return [ target ] } @ $mol_mem_key nodeDeps( { path , exclude } : { path : string , exclude : string[] } ) : string[] { var res = new Set<string>() var sources = this.sourcesAll( { path , exclude } ) for( let src of sources ) { let deps = this.srcDeps( src.path() ) for( let dep in deps ) { if( !/^\/node(?:_modules)?\//.test( dep ) ) continue let mod = dep.replace( /^\/node(?:_modules)?\// , '' ).replace( /\/.*/g , '' ) res.add( mod ) } } return [ ... res ] } @ $mol_mem_key bundleReadmeMd( { path , exclude } : { path : string , exclude : string[] } ) : $mol_file[] { const start = Date.now() const root = this.root() const pack = $mol_file.absolute( path ) let mod = pack let source while( true ) { source = mod.resolve( 'README.md' ) if( source.exists() ) break source = mod.resolve( 'readme.md' ) if( source.exists() ) break if( mod === root ) break mod = mod.parent() } const target = pack.resolve( '-/README.md' ) target.text( source?.text() ?? path ) this.logBundle( target , Date.now() - start ) return [ target ] } @ $mol_mem_key bundlePackageJSON( { path , exclude } : { path : string , exclude : string[] } ) : $mol_file[] { const start = Date.now() var pack = $mol_file.absolute( path ) const source = pack.resolve( `package.json` ) const target = pack.resolve( `-/package.json` ) let name = pack.relate( this.root() ).replace( /\//g , '_' ) let json = { name , version : '0.0.0' , main : 'node.js' , module : 'node.esm.js', browser : 'web.js', types : 'web.d.ts', keywords: [] as string[], dependencies : {} as { [ key : string ] : string } } if( source.exists() ) { Object.assign( json , JSON.parse( source.text() ) ) } let version = json.version.split('.').map( Number ) name = json.name || name try { const published = ( [] as string[] ).concat( JSON.parse( this.$.$mol_exec( '' , 'npm' , 'view' , name , 'versions', '--json' ).stdout.toString() ) ).slice(-1)[0].split('.').map( Number ) if( published[0] > version[0] ) { version = published } else if( published[0] === version[0] && published[1] > version[1] ) { version[1] = published[1] } if(!( published[2] <= version[2] )) { version[2] = published[2] } } catch {} ++ version[2] json.version = version.join( '.' ) json.dependencies = {} for( let dep of this.nodeDeps({ path , exclude }) ) { if( require('module').builtinModules.includes(dep) ) continue json.dependencies[ dep ] = `*` } json.keywords = [ ... this.graph( { path , exclude } ).nodes ] .filter( Boolean ) .filter( path => !/[.-]/.test( path ) ) .map( path => '$' + path.replaceAll( '/', '_' ) ) target.text( JSON.stringify( json , null , ' ' ) ) this.logBundle( target , Date.now() - start ) return [ target ] } @ $mol_mem_key bundleIndexHtml( { path , exclude } : { path : string , exclude? : string[] } ) : $mol_file[] { const pack = $mol_file.absolute( path ) const targets : $mol_file[] = [] const start = Date.now() const html = pack.resolve( 'index.html' ) if ( html.exists() ) { const html_target = pack.resolve( '-/index.html' ) html_target.text( html.text() ) targets.push( html_target ) this.logBundle( html_target , Date.now() - start ) } return targets } @ $mol_mem_key bundleFiles( { path , exclude } : { path : string , exclude? : string[] } ) : $mol_file[] { const root = this.root() const pack = $mol_file.absolute( path ) var sources = this.sourcesAll( { path , exclude } ) .filter( src => /meta.tree$/.test( src.ext() ) ) const targets : $mol_file[] = [] sources.forEach( source => { const tree = $mol_tree.fromString( source.text() , source.path() ) tree.select( 'deploy' ).sub.forEach( deploy => { const start = Date.now() const file = root.resolve( deploy.value.replace( /^\// , '' ) ) if ( ! file.exists() ) return const target = pack.resolve( `-/${ file.relate( root ) }` ) target.buffer( file.buffer() ) targets.push( target ) this.logBundle( target , Date.now() - start ) } ) } ) return targets } @ $mol_mem_key bundleCordova( { path , exclude } : { path : string , exclude? : string[] } ) : $mol_file[] { const start = Date.now() const pack = $mol_file.absolute( path ) const cordova = pack.resolve( '-cordova' ) const config = pack.resolve( 'config.xml' ) if( !config.exists() ) return [] const config_target = cordova.resolve( 'config.xml' ) config_target.text( config.text() ) const html = pack.resolve( 'index.html' ) const targets = [ config_target ] if( html.exists() ) { const html_target = cordova.resolve( 'www/index.html' ) html_target.text( html.text() ) targets.push(html_target) } const sources = pack.resolve( '-' ).find().filter( src => src.type() === 'file' ) for (const source of sources) { const target = cordova.resolve( `www/${ source.relate( pack ) }` ) target.text( source.text() ) targets.push(target) } this.logBundle( cordova , Date.now() - start ) return targets } @ $mol_mem_key bundleCSS( { path , exclude , bundle } : { path : string , exclude? : string[] , bundle : string } ) : $mol_file[] { if( bundle === 'node' ) return [] const start = Date.now() var pack = $mol_file.absolute( path ) var sources = [] as $mol_file[] // this.sourcesCSS( { path , exclude } ) var target = pack.resolve( `-/${bundle}.css` ) var targetMap = pack.resolve( `-/${bundle}.css.map` ) // var root : any = null //$node['postcss'].root({}) // sources.forEach( // src => { // var root2 = $node['postcss'].parse( src.content() , { from : src.path() } ) // root = root ? root.append( root2 ) : root2 // } // ) // var processor = $node['postcss']([ // $node[ 'postcss-custom-properties' ]({ // preserve : true , // }) , // $node[ 'postcss-color-function' ]() , // ]) // var result = processor.process( root , { to : target.relate() , map : { inline : false } } ) const result = { css : '/* CSS compiles into js bundle now! */', map : '/* CSS compiles into js bundle now! */', } target.text( result.css ) targetMap.text( JSON.stringify( result.map , null , '\t' ) ) this.logBundle( target , Date.now() - start ) return [ target , targetMap ] } @ $mol_mem_key bundleLocale( { path , exclude , bundle } : { path : string , exclude? : string[] , bundle : string } ) : $mol_file[] { const pack = $mol_file.absolute( path ) const sources = this.sourcesAll( { path , exclude } ).filter( src => /(locale=(\w+)\.json)$/.test( src.name() ) ) if( !sources.length ) return [] const locales = {} as { [ key : string ] : { [ key : string ] : string } } sources.forEach( src => { const [ ext , lang ] = /locale=(\w+)\.json$/.exec( src.name() )! if( !locales[ lang ] ) locales[ lang ] = {} const loc = JSON.parse( src.text() ) for( let key in loc ) { locales[ lang ][ key ] = loc[ key ] } } ) const targets = Object.keys( locales ).map( lang => { const start = Date.now() const target = pack.resolve( `-/${bundle}.locale=${ lang }.json` ) const locale = locales[ lang ] if( lang !== 'en' && locales['en'] ) { for( let key in locale ) { if( key in locales[ 'en' ] ) continue delete locale[ key ] this.$.$mol_log3_warn({ place: `${this}.buildLocale()`, message: `Excess locale key`, hint: 'May be you forgot to remove this key?', lang, key, }) } } const locale_sorted = {} for( let key of Object.keys( locale ).sort() ) { locale_sorted[ key ] = locale[ key ] } target.text( JSON.stringify( locale_sorted , null , '\t' ) ) this.logBundle( target , Date.now() - start ) return target } ) return targets } @ $mol_mem_key bundleDepsJSON( { path , exclude , bundle } : { path : string , exclude? : string[] , bundle : string } ) : $mol_file[] { const start = Date.now() const pack = $mol_file.absolute( path ) const list = this.sourcesAll( { path , exclude } ) if( !list.length ) return [] const origs = list.filter( src => !/\/-/.test( src.path() ) ) const sloc = {} as Record< string , number > for( const src of origs ) { const ext = src.name().replace( /^.*\./ , '' ) const count = src.text().trim().split( /[\n\r]\s*/ ).length sloc[ ext ] = ( sloc[ ext ] || 0 ) + count } const graph = this.graph( { path , exclude } ) const deps = {} as Record<string, Record<string, number>> for( let dep of graph.nodes ) { deps[ dep ] = this.dependencies( { path : this.root().resolve( dep ).path() , exclude } ) } const deps_in = {} as Record< string , Record< string , number > > for( const [ dep , pair ] of graph.edges_in ) { if( !deps_in[ dep ] ) { deps_in[ dep ] = {} } for( const [ mod , edge ] of pair ) { deps_in[ dep ][ mod ] = edge.priority } } const deps_out = {} as Record< string , Record< string , number > > for( const [ mod , pair ] of graph.edges_out ) { if( !deps_out[ mod ] ) { deps_out[ mod ] = {} } for( const [ dep , edge ] of pair ) { deps_out[ mod ][ dep ] = edge.priority } } const data = { files : list.map( src => src.relate( this.root() ) ) , mods : graph.sorted , deps_in , deps_out , sloc , deps } as const const target = pack.resolve( `-/${bundle}.deps.json` ) target.text( JSON.stringify( data ) ) this.logBundle( target , Date.now() - start ) return [ target ] } } function $mol_build_depsMerge( target : { [ index : string ] : number } , source : { [ index : string ] : number } ) : { [ index : string ] : number } { for( var path in source ) { if( target[ path ] >= source[ path ] ) continue target[ path ] = source[ path ] } return target } $mol_build.dependors[ 'js' ] = source => { var depends : { [ index : string ] : number } = {} var lines = String( source.text() ) .replace( /\/\*[^]*?\*\//g , '' ) // drop block comments .replace( /\/\/.*$/gm , '' ) // drop inline comments .split( '\n' ) lines.forEach( function( line ) { var indent = /^([\s\t]*)/.exec( line )! var priority = -indent[ 0 ].replace( /\t/g , ' ' ).length / 4 line.replace( /require\(\s*['"](.*?)['"]\s*\)/ig , ( str , path )=> { path = path.replace( /(\/[^\/.]+)$/ , '$1.js' ).replace( /\/$/, '/index.js' ) if( path[0] === '.' ) path = '../' + path $mol_build_depsMerge( depends , { [ path ] : priority } ) return str } ) } ) return depends } $mol_build.dependors[ 'ts' ] = $mol_build.dependors[ 'tsx' ] = $mol_build.dependors[ 'jam.js' ] = source => { var depends : { [ index : string ] : number } = {} var lines = String( source.text() ) .replace( /\/\*(?!\*)[\s\S]*?\*\//g , '' ) // drop block comments except doc-comments .replace( /\/\/.*$/gm , '' ) // drop inline comments .split( '\n' ) lines.forEach( function( line ) { var indent = /^([\s\t]*)/.exec( line )! var priority = -indent[ 0 ].replace( /\t/g , ' ' ).length / 4 line.replace( /\$([a-z0-9]{2,})(?:((?:[._A-Z0-9][a-z0-9]+)+)|\[\s*['"]([^'"]+?)['"]\s*\])?/g , ( str , pack , path , name )=> { if( path ) path = '/' + pack + path.replace( /(?=[A-Z])/g , '_' ).toLowerCase().replace( /[_.\[\]'"]+/g , '/' ) if( name ) name = '/' + pack + '/' + name pack = '/' + pack $mol_build_depsMerge( depends , { [ path || name || pack ] : priority } ) return str } ) line.replace( /require\(\s*['"](.*?)['"]\s*\)/ig , ( str , path )=> { $mol_build_depsMerge( depends , { [ path ] : priority } ) return str } ) } ) return depends } $mol_build.dependors[ 'view.ts' ] = source => { var treeName = './' + source.name().replace( /ts$/ , 'tree' ) var depends : { [ index : string ] : number } = { [ treeName ] : 0 } $mol_build_depsMerge( depends , $mol_build.dependors[ 'ts' ]!( source ) ) return depends } $mol_build.dependors[ 'node.ts' ] = $mol_build.dependors[ 'web.ts' ] = source => { var common = './' + source.name().replace( /\.(node|web)\.ts$/ , '.ts' ) var depends : { [ index : string ] : number } = { [ common ] : 0 } $mol_build_depsMerge( depends , $mol_build.dependors[ 'ts' ]!( source ) ) return depends } $mol_build.dependors[ 'view.css' ] = source => { var treeName = './' + source.name().replace( /css$/ , 'tree' ) var depends : { [ index : string ] : number } = { [ treeName ] : 0 } $mol_build_depsMerge( depends , $mol_build.dependors[ 'css' ]!( source ) ) return depends } $mol_build.dependors[ 'css' ] = source => { var depends : { [ index : string ] : number } = { '/mol/style/attach': 0, } var lines = String( source.text() ) .replace( /\/\*[^]*?\*\//g , '' ) // drop block comments .replace( /\/\/.*$/gm , '' ) // drop inline comments .split( '\n' ) lines.forEach( function( line ) { var indent = /^([\s\t]*)/.exec( line )! var priority = -indent[ 0 ].replace( /\t/g , ' ' ).length / 4 line.replace( /(?:--|[\[\.#])([a-z][a-z0-9]+(?:[-_][a-z0-9]+)+)/ig , ( str , name )=> { $mol_build_depsMerge( depends , { [ '/' + name.replace( /[._-]/g , '/' ) ] : priority } ) return str } ) } ) return depends } $mol_build.dependors[ 'meta.tree' ] = source => { const depends : { [ index : string ] : number } = {} const tree = $mol_tree.fromString( source.text() , source.path() ) tree.select( 'require' ).sub.forEach( leaf => { depends[ leaf.value ] = 0 } ) tree.select( 'include' ).sub.forEach( leaf => { depends[ leaf.value ] = -9000 } ) return depends } $mol_build.dependors[ 'view.tree' ] = source => { return { [`/${ source.parent().relate() }/-view.tree/${ source.name() }.ts`]: 0, } } }
the_stack
import type { CSpellSettingsWithSourceTrace, DictionaryDefinition, DictionaryDefinitionCustom, FileSource, Glob, GlobDef, Pattern, RegExpPatternDefinition, } from '@cspell/cspell-types'; import { AutoLoadCache, createAutoLoadCache, createLazyValue, LazyValue } from 'common-utils/autoLoad.js'; import { setIfDefined } from 'common-utils/index.js'; import { log } from 'common-utils/log.js'; import { toUri } from 'common-utils/uriHelper.js'; import { findRepoRoot, GitIgnore } from 'cspell-gitignore'; import { GlobMatcher, GlobMatchOptions, GlobMatchRule, GlobPatternNormalized } from 'cspell-glob'; import { calcOverrideSettings, clearCachedFiles, ExcludeFilesGlobMap, ExclusionHelper, getSources, mergeSettings, readSettingsFiles as cspellReadSettingsFiles, searchForConfig, } from 'cspell-lib'; import * as fs from 'fs-extra'; import { genSequence, Sequence } from 'gensequence'; import * as os from 'os'; import * as path from 'path'; import { Connection, WorkspaceFolder } from 'vscode-languageserver/node'; import { URI as Uri, Utils as UriUtils } from 'vscode-uri'; import { VSCodeSettingsCspell } from '../api'; import { CSpellUserSettings } from '../config/cspellConfig'; import { extensionId } from '../constants'; import { uniqueFilter } from '../utils'; import { getConfiguration, getWorkspaceFolders, TextDocumentUri } from './vscode.config'; import { createWorkspaceNamesResolver, resolveSettings } from './WorkspacePathResolver'; // The settings interface describe the server relevant settings part export interface SettingsCspell extends VSCodeSettingsCspell {} const cSpellSection: keyof SettingsCspell = extensionId; type FsPath = string; export interface SettingsVSCode { search?: { exclude?: ExcludeFilesGlobMap; }; } interface VsCodeSettings { [key: string]: any; } interface ExtSettings { uri: string; vscodeSettings: SettingsCspell; settings: CSpellUserSettings; excludeGlobMatcher: GlobMatcher; includeGlobMatcher: GlobMatcher; } type PromiseType<T extends Promise<any>> = T extends Promise<infer R> ? R : never; type GitignoreResultP = ReturnType<GitIgnore['isIgnoredEx']>; type GitignoreResultInfo = PromiseType<GitignoreResultP>; export interface ExcludeIncludeIgnoreInfo { include: boolean; exclude: boolean; ignored: boolean | undefined; gitignoreInfo: GitignoreResultInfo | undefined; } const defaultExclude: Glob[] = [ '**/*.rendered', '__pycache__/**', // ignore cache files. cspell:ignore pycache ]; const defaultAllowedSchemes = ['gist', 'file', 'sftp', 'untitled', 'vscode-notebook-cell']; const schemeBlockList = ['git', 'output', 'debug', 'vscode']; const defaultRootUri = Uri.file('').toString(); const _defaultSettings: CSpellUserSettings = Object.freeze({}); const _schemaMapToFile = { 'vscode-notebook-cell': true, } as const; const schemeMapToFile: Record<string, true> = Object.freeze(_schemaMapToFile); const defaultCheckOnlyEnabledFileTypes = true; interface Clearable { clear: () => any; } export class DocumentSettings { // Cache per folder settings private cachedValues: Clearable[] = []; private readonly fetchSettingsForUri = this.createCache((key: string) => this._fetchSettingsForUri(key)); private readonly fetchVSCodeConfiguration = this.createCache((key: string) => this._fetchVSCodeConfiguration(key)); private readonly fetchRepoRootForDir = this.createCache((dir: FsPath) => findRepoRoot(dir)); private readonly _folders = this.createLazy(() => this.fetchFolders()); readonly configsToImport = new Set<string>(); private readonly importedSettings = this.createLazy(() => this._importSettings()); private _version = 0; private gitIgnore = new GitIgnore(); constructor(readonly connection: Connection, readonly defaultSettings: CSpellUserSettings = _defaultSettings) {} async getSettings(document: TextDocumentUri): Promise<CSpellUserSettings> { return this.getUriSettings(document.uri); } getUriSettings(uri: string): Promise<CSpellUserSettings> { return this.fetchUriSettings(uri); } async calcIncludeExclude(uri: Uri): Promise<ExcludeIncludeIgnoreInfo> { const settings = await this.fetchSettingsForUri(uri.toString()); const ie = calcIncludeExclude(settings, uri); const ignoredEx = await this._isGitIgnoredEx(settings, uri); return { ...ie, ignored: ignoredEx?.matched, gitignoreInfo: ignoredEx, }; } async isExcluded(uri: string): Promise<boolean> { const settings = await this.fetchSettingsForUri(uri); return isExcluded(settings, Uri.parse(uri)); } /** * If `useGitIgnore` is true, checks to see if a uri matches a `.gitignore` file glob. * @param uri - file uri * @returns `useGitignore` && the file matches a `.gitignore` file glob. */ async isGitIgnored(uri: Uri): Promise<boolean | undefined> { const extSettings = await this.fetchUriSettingsEx(uri.toString()); return this._isGitIgnored(extSettings, uri); } /** * If `useGitIgnore` is true, checks to see if a uri matches a `.gitignore` file glob. * @param uri - file uri * @returns * - `undefined` if `useGitignore` is falsy. -- meaning we do not know. * - `true` if it is ignored * - `false` otherwise */ private async _isGitIgnored(extSettings: ExtSettings, uri: Uri): Promise<boolean | undefined> { if (!extSettings.settings.useGitignore) return undefined; return await this.gitIgnore.isIgnored(uri.fsPath); } /** * If `useGitIgnore` is true, checks to see if a uri matches a `.gitignore` file glob. * @param uri - file uri * @returns * - `undefined` if `useGitignore` is falsy. -- meaning we do not know. * - `true` if it is ignored * - `false` otherwise */ private async _isGitIgnoredEx(extSettings: ExtSettings, uri: Uri): Promise<GitignoreResultInfo | undefined> { if (!extSettings.settings.useGitignore) return undefined; const root = await this.fetchRepoRootForFile(uri); if (root) { this.gitIgnore.addRoots([root]); } return await this.gitIgnore.isIgnoredEx(uri.fsPath); } async calcExcludedBy(uri: string): Promise<ExcludedByMatch[]> { const extSettings = await this.fetchUriSettingsEx(uri); return calcExcludedBy(uri, extSettings); } resetSettings(): void { log('resetSettings'); clearCachedFiles(); this.cachedValues.forEach((cache) => cache.clear()); this._version += 1; this.gitIgnore = new GitIgnore(); } get folders(): Promise<WorkspaceFolder[]> { return this._folders(); } private _importSettings() { log('importSettings'); const importPaths = [...this.configsToImport].sort(); return readSettingsFiles(importPaths); } get version(): number { return this._version; } registerConfigurationFile(path: string): void { log('registerConfigurationFile:', path); this.configsToImport.add(path); this.importedSettings.clear(); this.resetSettings(); } private async fetchUriSettings(uri: string): Promise<CSpellUserSettings> { const exSettings = await this.fetchUriSettingsEx(uri); return exSettings.settings; } private fetchUriSettingsEx(uri: string): Promise<ExtSettings> { return this.fetchSettingsForUri(uri); } private async findMatchingFolder(docUri: string, defaultTo: WorkspaceFolder): Promise<WorkspaceFolder>; private async findMatchingFolder(docUri: string, defaultTo?: WorkspaceFolder | undefined): Promise<WorkspaceFolder | undefined>; private async findMatchingFolder(docUri: string, defaultTo: WorkspaceFolder | undefined): Promise<WorkspaceFolder | undefined> { return (await this.matchingFoldersForUri(docUri))[0] || defaultTo; } private rootForUri(docUri: string | undefined) { return Uri.parse(docUri || defaultRootUri).with({ path: '' }); } private rootFolderForUri(docUri: string | undefined) { const root = this.rootForUri(docUri); return { uri: root.toString(), name: 'root' }; } private async fetchFolders() { return (await getWorkspaceFolders(this.connection)) || []; } private async _fetchVSCodeConfiguration(uri: string) { const [cSpell, search] = ( await getConfiguration(this.connection, [{ scopeUri: uri || undefined, section: cSpellSection }, { section: 'search' }]) ).map((v) => v || {}) as [CSpellUserSettings, VsCodeSettings]; return { cSpell, search }; } private async fetchRepoRootForFile(uriFile: string | Uri) { const u = toUri(uriFile); const uriDir = UriUtils.dirname(u); return this.fetchRepoRootForDir(uriDir.fsPath); } public async findCSpellConfigurationFilesForUri(docUri: string | Uri): Promise<Uri[]> { const uri = typeof docUri === 'string' ? Uri.parse(docUri) : docUri; const docUriAsString = uri.toString(); const settings = await this.fetchSettingsForUri(docUriAsString); return this.extractCSpellConfigurationFiles(settings.settings); } /** * Extract cspell configuration files used as sources to the finalized settings. * @param settings - finalized settings * @returns config file uri's. */ readonly extractCSpellConfigurationFiles = extractCSpellConfigurationFiles; /** * Extract file based cspell configurations used to create the finalized settings. * @param settings - finalized settings * @returns array of Settings */ readonly extractCSpellFileConfigurations = extractCSpellFileConfigurations; readonly extractTargetDictionaries = extractTargetDictionaries; private async fetchSettingsFromVSCode(uri?: string): Promise<CSpellUserSettings> { const { cSpell, search } = await this.fetchVSCodeConfiguration(uri || ''); const { exclude = {} } = search; const { ignorePaths = [] } = cSpell; const cSpellConfigSettings: CSpellUserSettings = { ...cSpell, id: 'VSCode-Config', ignorePaths: ignorePaths.concat(ExclusionHelper.extractGlobsFromExcludeFilesGlobMap(exclude)), }; return cSpellConfigSettings; } private async _fetchSettingsForUri(docUri: string): Promise<ExtSettings> { log(`fetchFolderSettings: URI ${docUri}`); const uri = Uri.parse(docUri); if (uri.scheme in schemeMapToFile) { return this.fetchSettingsForUri(mapToFileUri(uri).toString()); } const fsPath = path.normalize(uri.fsPath); const cSpellConfigSettingsRel = await this.fetchSettingsFromVSCode(docUri); const cSpellConfigSettings = await this.resolveWorkspacePaths(cSpellConfigSettingsRel, docUri); const settings = await searchForConfig(fsPath); const rootFolder = this.rootFolderForUri(docUri); const folders = await this.folders; const folder = await this.findMatchingFolder(docUri, rootFolder); const cSpellFolderSettings = resolveConfigImports(cSpellConfigSettings, folder.uri); const globRootFolder = folder !== rootFolder ? folder : folders[0] || folder; const settingsToMerge: CSpellUserSettings[] = []; if (this.defaultSettings !== _defaultSettings) { settingsToMerge.push(this.defaultSettings); } settingsToMerge.push(this.importedSettings()); settingsToMerge.push(cSpellFolderSettings); if (settings) { settingsToMerge.push(settings); } const mergedSettings = mergeSettings(settingsToMerge[0], ...settingsToMerge.slice(1)); const enabledFiletypes = extractEnableFiletypes(mergedSettings); const spellSettings = applyEnableFiletypes(enabledFiletypes, mergedSettings); const fileSettings = calcOverrideSettings(spellSettings, fsPath); const { ignorePaths = [], files = [] } = fileSettings; const globRoot = Uri.parse(globRootFolder.uri).fsPath; if (!files.length && cSpellConfigSettings.spellCheckOnlyWorkspaceFiles !== false) { // Add file globs that will match the entire workspace. folders.forEach((folder) => files.push({ glob: '**', root: Uri.parse(folder.uri).fsPath })); fileSettings.enableGlobDot = fileSettings.enableGlobDot ?? true; } fileSettings.files = files; const globs = ignorePaths.concat(defaultExclude); const excludeGlobMatcher = new GlobMatcher(globs, globRoot); const includeOptions: GlobMatchOptions = { root: globRoot, mode: 'include' }; setIfDefined(includeOptions, 'dot', fileSettings.enableGlobDot); const includeGlobMatcher = new GlobMatcher(files, includeOptions); const ext: ExtSettings = { uri: docUri, vscodeSettings: { cSpell: cSpellConfigSettings }, settings: fileSettings, excludeGlobMatcher, includeGlobMatcher, }; return ext; } private async resolveWorkspacePaths(settings: CSpellUserSettings, docUri: string): Promise<CSpellUserSettings> { const folders = await this.folders; const folder = (await this.findMatchingFolder(docUri)) || folders[0] || this.rootFolderForUri(docUri); const resolver = createWorkspaceNamesResolver(folder, folders, settings.workspaceRootPath); return resolveSettings(settings, resolver); } public async matchingFoldersForUri(docUri: string): Promise<WorkspaceFolder[]> { const folders = await this.folders; return _matchingFoldersForUri(folders, docUri); } private createCache<K, T>(loader: (key: K) => T): AutoLoadCache<K, T> { const cache = createAutoLoadCache(loader); this.cachedValues.push(cache); return cache; } private createLazy<T>(loader: () => T): LazyValue<T> { const lazy = createLazyValue(loader); this.cachedValues.push(lazy); return lazy; } } function resolveConfigImports(config: CSpellUserSettings, folderUri: string): CSpellUserSettings { log('resolveConfigImports:', folderUri); const uriFsPath = path.normalize(Uri.parse(folderUri).fsPath); const imports = typeof config.import === 'string' ? [config.import] : config.import || []; const importAbsPath = imports.map((file) => resolvePath(uriFsPath, file)); log(`resolvingConfigImports: [\n${imports.join('\n')}]`); log(`resolvingConfigImports ABS: [\n${importAbsPath.join('\n')}]`); const { import: _import, ...result } = importAbsPath.length ? mergeSettings(readSettingsFiles([...importAbsPath]), config) : config; return result; } function readSettingsFiles(paths: string[]) { // log('readSettingsFiles:', paths); const existingPaths = paths.filter((filename) => exists(filename)); log('readSettingsFiles:', existingPaths); return existingPaths.length ? cspellReadSettingsFiles(existingPaths) : {}; } function exists(file: string): boolean { try { const s = fs.statSync(file); return s.isFile(); } catch (e) {} return false; } function resolvePath(...parts: string[]): string { const normalizedParts = parts.map((part) => (part[0] === '~' ? os.homedir() + part.slice(1) : part)); return path.resolve(...normalizedParts); } export function isUriAllowed(uri: string, schemes?: string[]): boolean { schemes = schemes || defaultAllowedSchemes; return doesUriMatchAnyScheme(uri, schemes); } export function isUriBlocked(uri: string, schemes: string[] = schemeBlockList): boolean { return doesUriMatchAnyScheme(uri, schemes); } export function doesUriMatchAnyScheme(uri: string, schemes: string[]): boolean { const schema = Uri.parse(uri).scheme; return schemes.findIndex((v) => v === schema) >= 0; } function extractEnableFiletypes(...settings: CSpellUserSettings[]): string[] { return settings.map(({ enableFiletypes = [] }) => enableFiletypes).reduce((acc, next) => acc.concat(next), []); } function applyEnableFiletypes(enableFiletypes: string[], settings: CSpellUserSettings): CSpellUserSettings { const mapOfEnabledFileTypes = calcMapOfEnabledFileTypes(enableFiletypes, settings); const enabledLanguageIds = [...mapOfEnabledFileTypes.entries()].filter(([_, enabled]) => enabled).map(([lang]) => lang); const { enableFiletypes: _, enabledLanguageIds: __, ...rest } = settings; return { enabledLanguageIds, mapOfEnabledFileTypes, ...rest }; } function normalizeEnableFiletypes(enableFiletypes: string[]): string[] { const ids = enableFiletypes .map((id) => id.replace(/!/g, '~')) // Use ~ for better sorting .sort() .map((id) => id.replace(/~/g, '!')) // Restore the ! .map((id) => id.replace(/^(!!)+/, '')); // Remove extra !! pairs return ids; } function calcMapOfEnabledFileTypes( enableFiletypes: string[], settings: CSpellUserSettings ): Required<CSpellUserSettings>['mapOfEnabledFileTypes'] { const { enabledLanguageIds = [] } = settings; const enabled = new Map<string, boolean>(); normalizeEnableFiletypes(enabledLanguageIds.concat(enableFiletypes)).forEach((lang) => { if (lang[0] === '!') { enabled.set(lang.slice(1), false); } else { enabled.set(lang, true); } }); return enabled; } export function isLanguageEnabled(languageId: string, settings: CSpellUserSettings): boolean { const mapOfEnabledFileTypes = settings.mapOfEnabledFileTypes || calcMapOfEnabledFileTypes(settings.enableFiletypes || [], settings); const enabled = mapOfEnabledFileTypes.get(languageId); const starEnabled = mapOfEnabledFileTypes.get('*'); const checkOnly = settings.checkOnlyEnabledFileTypes ?? defaultCheckOnlyEnabledFileTypes; return checkOnly && starEnabled !== true ? !!enabled : enabled !== false; } function _matchingFoldersForUri(folders: WorkspaceFolder[], docUri: string): WorkspaceFolder[] { return folders.filter(({ uri }) => docUri.startsWith(uri)).sort((a, b) => b.uri.length - a.uri.length); } function filterFnConfigFilesToMatchInheritedPath(dir: Uri): (uri: Uri) => boolean { const inheritPath = dir.toString(); return (cfgUri) => { const uriConfDir = UriUtils.dirname(cfgUri); if (inheritPath.startsWith(uriConfDir.toString())) { return true; } return UriUtils.basename(uriConfDir) === '.vscode' && inheritPath.startsWith(UriUtils.dirname(uriConfDir).toString()); }; } function filterConfigFilesToMatchInheritedPathOfFile(configFiles: Uri[], file: Uri): Uri[] { const fnFilter = filterFnConfigFilesToMatchInheritedPath(UriUtils.dirname(file)); return configFiles.filter(fnFilter); } const correctRegExMap = new Map([ ['/"""(.*?\\n?)+?"""/g', '/(""")[^\\1]*?\\1/g'], ["/'''(.*?\\n?)+?'''/g", "/(''')[^\\1]*?\\1/g"], ]); function fixRegEx(pat: Pattern): Pattern { if (typeof pat != 'string') { return pat; } return correctRegExMap.get(pat) || pat; } function fixRegPattern(pat: Pattern | Pattern[]): Pattern | Pattern[] { if (Array.isArray(pat)) { return pat.map(fixRegEx); } return fixRegEx(pat); } function fixPattern(pat: RegExpPatternDefinition): RegExpPatternDefinition { const pattern = fixRegPattern(pat.pattern); if (pattern === pat.pattern) { return pat; } return { ...pat, pattern }; } export function correctBadSettings(settings: CSpellUserSettings): CSpellUserSettings { const newSettings = { ...settings }; // Fix patterns newSettings.patterns = newSettings?.patterns?.map(fixPattern); newSettings.ignoreRegExpList = newSettings?.ignoreRegExpList?.map(fixRegEx); newSettings.includeRegExpList = newSettings?.includeRegExpList?.map(fixRegEx); return newSettings; } export function stringifyPatterns(settings: CSpellUserSettings): CSpellUserSettings; export function stringifyPatterns(settings: undefined): undefined; export function stringifyPatterns(settings: CSpellUserSettings | undefined): CSpellUserSettings | undefined; export function stringifyPatterns(settings: CSpellUserSettings | undefined): CSpellUserSettings | undefined { if (!settings) return settings; const patterns = settings.patterns?.map((pat) => ({ ...pat, pattern: pat.pattern.toString() })); return { ...settings, patterns }; } export const debugExports = { fixRegEx: fixRegPattern, fixPattern, resolvePath, filterConfigFilesToMatchInheritedPathOfFile, }; export interface ExcludedByMatch { settings: CSpellSettingsWithSourceTrace; glob: Glob; } function calcExcludedBy(uri: string, extSettings: ExtSettings): ExcludedByMatch[] { const filename = path.normalize(Uri.parse(uri).fsPath); const matchResult = extSettings.excludeGlobMatcher.matchEx(filename); if (matchResult.matched === false) { return []; } const glob = extractGlobDef(matchResult); function isExcluded(ex: ExcludedByMatch): boolean { return areGlobsEqual(glob, ex.glob); } function keep(cfg: CSpellSettingsWithSourceTrace): boolean { return !cfg.source?.sources?.length; } const ex: Sequence<ExcludedByMatch> = genSequence(getSources(extSettings.settings)) // keep only leaf sources .filter(keep) .filter(uniqueFilter()) .concatMap((settings) => settings.ignorePaths?.map((glob) => ({ glob, settings })) || []); const matches: ExcludedByMatch[] = ex.filter(isExcluded).toArray(); return matches; } function extractGlobDef(match: GlobMatchRule): GlobDef { return { glob: (<GlobPatternNormalized>match.pattern).rawGlob || match.pattern.glob || match.glob, root: (<GlobPatternNormalized>match.pattern).rawRoot || match.pattern.root || match.root, }; } function areGlobsEqual(globA: Glob, globB: Glob): boolean { globA = toGlobDef(globA); globB = toGlobDef(globB); return globA.glob === globB.glob && globA.root === globB.root; } function toGlobDef(g: Glob): GlobDef { return typeof g === 'string' ? { glob: g } : g; } export interface CSpellSettingsWithFileSource extends CSpellSettingsWithSourceTrace { source: FileSource; } function isCSpellSettingsWithFileSource(s: CSpellUserSettings | CSpellSettingsWithFileSource): s is CSpellSettingsWithFileSource { return !!(<CSpellSettingsWithSourceTrace>s).source?.filename; } /** * Extract cspell configuration files used as sources to the finalized settings. * @param settings - finalized settings * @returns config file uri's. */ function extractCSpellConfigurationFiles(settings: CSpellUserSettings): Uri[] { const configs = extractCSpellFileConfigurations(settings); return configs.map(({ source }) => Uri.file(source.filename)); } const regExIsOwnedByCspell = /@cspell\b/; const regExIsOwnedByExtension = /\bstreetsidesoftware\.code-spell-checker\b/; /** * Extract file based cspell configurations used to create the finalized settings. * @param settings - finalized settings * @returns array of Settings */ export function extractCSpellFileConfigurations(settings: CSpellUserSettings): CSpellSettingsWithFileSource[] { const sources = getSources(settings); const configs = sources .filter(isCSpellSettingsWithFileSource) .filter(({ source }) => !regExIsOwnedByCspell.test(source.filename)) .filter(({ source }) => !regExIsOwnedByExtension.test(source.filename)) .reverse(); return configs; } /** * * @param settings - finalized settings * @returns */ export function extractTargetDictionaries(settings: CSpellUserSettings): DictionaryDefinitionCustom[] { const { dictionaries = [], dictionaryDefinitions = [] } = settings; const defs = new Map(dictionaryDefinitions.map((d) => [d.name, d])); const activeDicts = dictionaries.map((name) => defs.get(name)).filter(isDefined); const regIsTextFile = /\.txt$/; const targetDicts = activeDicts .filter(isDictionaryDefinitionCustom) .filter((d) => regIsTextFile.test(d.path) && d.addWords) .filter((d) => !regExIsOwnedByCspell.test(d.path)) .filter((d) => !regExIsOwnedByExtension.test(d.path)); return targetDicts; } function isDictionaryDefinitionCustom(d: DictionaryDefinition): d is DictionaryDefinitionCustom { return d.file === undefined && !!d.path && (<DictionaryDefinitionCustom>d).addWords; } function isDefined<T>(t: T | undefined): t is T { return t !== undefined && t !== null; } export function calcIncludeExclude(settings: ExtSettings, uri: Uri): { include: boolean; exclude: boolean } { return { include: isIncluded(settings, uri), exclude: isExcluded(settings, uri), }; } export function isIncluded(settings: ExtSettings, uri: Uri): boolean { const files = settings.settings.files; return !files?.length || settings.includeGlobMatcher.match(uri.fsPath); } export function isExcluded(settings: ExtSettings, uri: Uri): boolean { return settings.excludeGlobMatcher.match(uri.fsPath); } function mapToFileUri(uri: Uri): Uri { return uri.with({ scheme: 'file', query: '', fragment: '', }); } export const __testing__ = { extractTargetDictionaries, extractEnableFiletypes, normalizeEnableFiletypes, applyEnableFiletypes, };
the_stack
import * as React from 'react'; import BusyButton from '../atoms/BusyButton'; import Button from '@material-ui/core/Button'; import Buttons from '../lib/Buttons'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import Input from '../atoms/Input'; import InputAdornment from '@material-ui/core/InputAdornment'; import NewRunParameters from '../components/NewRunParameters'; import Radio from '@material-ui/core/Radio'; import ResourceSelector from './ResourceSelector'; import RunUtils from '../lib/RunUtils'; import { TextFieldProps } from '@material-ui/core/TextField'; import Trigger from '../components/Trigger'; import { ApiExperiment, ApiExperimentStorageState } from '../apis/experiment'; import { ApiPipeline, ApiParameter, ApiPipelineVersion } from '../apis/pipeline'; import { ApiRun, ApiResourceReference, ApiRelationship, ApiResourceType, ApiRunDetail, ApiPipelineRuntime, } from '../apis/run'; import { ApiTrigger, ApiJob } from '../apis/job'; import { Apis, PipelineSortKeys, PipelineVersionSortKeys, ExperimentSortKeys } from '../lib/Apis'; import { Link } from 'react-router-dom'; import { Page, PageProps } from './Page'; import { RoutePage, RouteParams, QUERY_PARAMS } from '../components/Router'; import { ToolbarProps } from '../components/Toolbar'; import { URLParser } from '../lib/URLParser'; import { Workflow } from '../../../frontend/third_party/argo-ui/argo_template'; import { classes, stylesheet } from 'typestyle'; import { commonCss, padding, color } from '../Css'; import { logger, errorToMessage } from '../lib/Utils'; import UploadPipelineDialog, { ImportMethod } from '../components/UploadPipelineDialog'; import { CustomRendererProps } from '../components/CustomTable'; import { Description } from '../components/Description'; import { NamespaceContext } from '../lib/KubeflowClient'; import { NameWithTooltip } from '../components/CustomTableNameColumn'; import { PredicateOp, ApiFilter } from '../apis/filter'; import { HelpButton } from 'src/atoms/HelpButton'; import { ExternalLink } from 'src/atoms/ExternalLink'; interface NewRunState { description: string; errorMessage: string; experiment?: ApiExperiment; experimentName: string; serviceAccount: string; experimentSelectorOpen: boolean; isBeingStarted: boolean; isClone: boolean; isFirstRunInExperiment: boolean; isRecurringRun: boolean; maxConcurrentRuns?: string; catchup: boolean; parameters: ApiParameter[]; pipeline?: ApiPipeline; pipelineVersion?: ApiPipelineVersion; // This represents a pipeline from a run that is being cloned, or if a user is creating a run from // a pipeline that was not uploaded to the system (as in the case of runs created from notebooks). workflowFromRun?: Workflow; // TODO: this is only here to properly display the name in the text field. // There is definitely a way to do this that doesn't necessitate this being in state. // Note: this cannot be undefined/optional or the label animation for the input field will not // work properly. pipelineName: string; pipelineVersionName: string; pipelineSelectorOpen: boolean; pipelineVersionSelectorOpen: boolean; runName: string; trigger?: ApiTrigger; unconfirmedSelectedExperiment?: ApiExperiment; unconfirmedSelectedPipeline?: ApiPipeline; unconfirmedSelectedPipelineVersion?: ApiPipelineVersion; useWorkflowFromRun: boolean; uploadDialogOpen: boolean; usePipelineFromRunLabel: string; } const css = stylesheet({ nonEditableInput: { color: color.secondaryText, }, selectorDialog: { // If screen is small, use calc(100% - 120px). If screen is big, use 1200px. maxWidth: 1200, // override default maxWidth to expand this dialog further minWidth: 680, width: 'calc(100% - 120px)', }, }); const descriptionCustomRenderer: React.FC<CustomRendererProps<string>> = props => { return <Description description={props.value || ''} forceInline={true} />; }; export class NewRun extends Page<{ namespace?: string }, NewRunState> { public state: NewRunState = { catchup: true, description: '', errorMessage: '', experimentName: '', serviceAccount: '', experimentSelectorOpen: false, isBeingStarted: false, isClone: false, isFirstRunInExperiment: false, isRecurringRun: false, parameters: [], pipelineName: '', pipelineSelectorOpen: false, pipelineVersionName: '', pipelineVersionSelectorOpen: false, runName: '', uploadDialogOpen: false, usePipelineFromRunLabel: 'Using pipeline from cloned run', useWorkflowFromRun: false, }; private pipelineSelectorColumns = [ { customRenderer: NameWithTooltip, flex: 1, label: 'Pipeline name', sortKey: PipelineSortKeys.NAME, }, { label: 'Description', flex: 2, customRenderer: descriptionCustomRenderer }, { label: 'Uploaded on', flex: 1, sortKey: PipelineSortKeys.CREATED_AT }, ]; private pipelineVersionSelectorColumns = [ { customRenderer: NameWithTooltip, flex: 2, label: 'Version name', sortKey: PipelineVersionSortKeys.NAME, }, // TODO(jingzhang36): version doesn't have description field; remove it and // fix the rendering. { label: 'Description', flex: 1, customRenderer: descriptionCustomRenderer }, { label: 'Uploaded on', flex: 1, sortKey: PipelineVersionSortKeys.CREATED_AT }, ]; private experimentSelectorColumns = [ { customRenderer: NameWithTooltip, flex: 1, label: 'Experiment name', sortKey: ExperimentSortKeys.NAME, }, { label: 'Description', flex: 2 }, { label: 'Created at', flex: 1, sortKey: ExperimentSortKeys.CREATED_AT }, ]; public getInitialToolbarState(): ToolbarProps { return { actions: {}, breadcrumbs: [{ displayName: 'Experiments', href: RoutePage.EXPERIMENTS }], pageTitle: 'Start a new run', }; } public render(): JSX.Element { const { workflowFromRun, description, errorMessage, experimentName, serviceAccount, experimentSelectorOpen, isClone, isFirstRunInExperiment, isRecurringRun, parameters, pipelineName, pipelineVersionName, pipelineSelectorOpen, pipelineVersionSelectorOpen, runName, unconfirmedSelectedExperiment, unconfirmedSelectedPipeline, unconfirmedSelectedPipelineVersion, usePipelineFromRunLabel, useWorkflowFromRun, } = this.state; const urlParser = new URLParser(this.props); const originalRunId = urlParser.get(QUERY_PARAMS.cloneFromRun) || urlParser.get(QUERY_PARAMS.fromRunId); const pipelineDetailsUrl = originalRunId ? RoutePage.PIPELINE_DETAILS.replace( ':' + RouteParams.pipelineId + '/version/:' + RouteParams.pipelineVersionId + '?', '', ) + urlParser.build({ [QUERY_PARAMS.fromRunId]: originalRunId }) : ''; const buttons = new Buttons(this.props, this.refresh.bind(this)); return ( <div className={classes(commonCss.page, padding(20, 'lr'))}> <div className={commonCss.scrollContainer}> <div className={commonCss.header}>Run details</div> {/* Pipeline selection */} {workflowFromRun && ( <div> <div> <span>{usePipelineFromRunLabel}</span> </div> <div className={classes(padding(10, 't'))}> {originalRunId && ( <Link className={classes(commonCss.link)} to={pipelineDetailsUrl}> [View pipeline] </Link> )} </div> </div> )} {!useWorkflowFromRun && ( <Input value={pipelineName} required={true} label='Pipeline' disabled={true} variant='outlined' InputProps={{ classes: { disabled: css.nonEditableInput }, endAdornment: ( <InputAdornment position='end'> <Button color='secondary' id='choosePipelineBtn' onClick={() => this.setStateSafe({ pipelineSelectorOpen: true })} style={{ padding: '3px 5px', margin: 0 }} > Choose </Button> </InputAdornment> ), readOnly: true, }} /> )} {!useWorkflowFromRun && ( <Input value={pipelineVersionName} required={true} label='Pipeline Version' disabled={true} variant='outlined' InputProps={{ classes: { disabled: css.nonEditableInput }, endAdornment: ( <InputAdornment position='end'> <Button color='secondary' id='choosePipelineVersionBtn' onClick={() => this.setStateSafe({ pipelineVersionSelectorOpen: true })} style={{ padding: '3px 5px', margin: 0 }} > Choose </Button> </InputAdornment> ), readOnly: true, }} /> )} {/* Pipeline selector dialog */} <Dialog open={pipelineSelectorOpen} classes={{ paper: css.selectorDialog }} onClose={() => this._pipelineSelectorClosed(false)} PaperProps={{ id: 'pipelineSelectorDialog' }} > <DialogContent> <ResourceSelector {...this.props} title='Choose a pipeline' filterLabel='Filter pipelines' listApi={async (...args) => { const response = await Apis.pipelineServiceApi.listPipelines(...args); return { nextPageToken: response.next_page_token || '', resources: response.pipelines || [], }; }} columns={this.pipelineSelectorColumns} emptyMessage='No pipelines found. Upload a pipeline and then try again.' initialSortColumn={PipelineSortKeys.CREATED_AT} selectionChanged={(selectedPipeline: ApiPipeline) => this.setStateSafe({ unconfirmedSelectedPipeline: selectedPipeline }) } toolbarActionMap={buttons .upload(() => this.setStateSafe({ pipelineSelectorOpen: false, uploadDialogOpen: true }), ) .getToolbarActionMap()} /> </DialogContent> <DialogActions> <Button id='cancelPipelineSelectionBtn' onClick={() => this._pipelineSelectorClosed(false)} color='secondary' > Cancel </Button> <Button id='usePipelineBtn' onClick={() => this._pipelineSelectorClosed(true)} color='secondary' disabled={!unconfirmedSelectedPipeline} > Use this pipeline </Button> </DialogActions> </Dialog> {/* Pipeline version selector dialog */} <Dialog open={pipelineVersionSelectorOpen} classes={{ paper: css.selectorDialog }} onClose={() => this._pipelineVersionSelectorClosed(false)} PaperProps={{ id: 'pipelineVersionSelectorDialog' }} > <DialogContent> <ResourceSelector {...this.props} title='Choose a pipeline version' filterLabel='Filter pipeline versions' listApi={async (...args) => { const response = await Apis.pipelineServiceApi.listPipelineVersions( 'PIPELINE', this.state.pipeline ? this.state.pipeline!.id! : '', args[1] /* page size */, args[0] /* page token*/, args[2] /* sort by */, args[3] /* filter */, ); return { nextPageToken: response.next_page_token || '', resources: response.versions || [], }; }} columns={this.pipelineVersionSelectorColumns} emptyMessage='No pipeline versions found. Select or upload a pipeline then try again.' initialSortColumn={PipelineVersionSortKeys.CREATED_AT} selectionChanged={(selectedPipelineVersion: ApiPipelineVersion) => this.setStateSafe({ unconfirmedSelectedPipelineVersion: selectedPipelineVersion }) } toolbarActionMap={buttons .upload(() => this.setStateSafe({ pipelineVersionSelectorOpen: false, uploadDialogOpen: true, }), ) .getToolbarActionMap()} /> </DialogContent> <DialogActions> <Button id='cancelPipelineVersionSelectionBtn' onClick={() => this._pipelineVersionSelectorClosed(false)} color='secondary' > Cancel </Button> <Button id='usePipelineVersionBtn' onClick={() => this._pipelineVersionSelectorClosed(true)} color='secondary' disabled={!unconfirmedSelectedPipelineVersion} > Use this pipeline version </Button> </DialogActions> </Dialog> <UploadPipelineDialog open={this.state.uploadDialogOpen} onClose={this._uploadDialogClosed.bind(this)} /> {/* Experiment selector dialog */} <Dialog open={experimentSelectorOpen} classes={{ paper: css.selectorDialog }} onClose={() => this._experimentSelectorClosed(false)} PaperProps={{ id: 'experimentSelectorDialog' }} > <DialogContent> <ResourceSelector {...this.props} title='Choose an experiment' filterLabel='Filter experiments' listApi={async ( page_token?: string, page_size?: number, sort_by?: string, filter?: string, ) => { // A new run can only be created in an unarchived experiment. // Therefore, when listing experiments here for selection, we // only list unarchived experiments. const new_filter = JSON.parse( decodeURIComponent(filter || '{"predicates": []}'), ) as ApiFilter; new_filter.predicates = (new_filter.predicates || []).concat([ { key: 'storage_state', op: PredicateOp.NOTEQUALS, string_value: ApiExperimentStorageState.ARCHIVED.toString(), }, ]); const response = await Apis.experimentServiceApi.listExperiment( page_token, page_size, sort_by, encodeURIComponent(JSON.stringify(new_filter)), this.props.namespace ? 'NAMESPACE' : undefined, this.props.namespace, ); return { nextPageToken: response.next_page_token || '', resources: response.experiments || [], }; }} columns={this.experimentSelectorColumns} emptyMessage='No experiments found. Create an experiment and then try again.' initialSortColumn={ExperimentSortKeys.CREATED_AT} selectionChanged={(selectedExperiment: ApiExperiment) => this.setStateSafe({ unconfirmedSelectedExperiment: selectedExperiment }) } /> </DialogContent> <DialogActions> <Button id='cancelExperimentSelectionBtn' onClick={() => this._experimentSelectorClosed(false)} color='secondary' > Cancel </Button> <Button id='useExperimentBtn' onClick={() => this._experimentSelectorClosed(true)} color='secondary' disabled={!unconfirmedSelectedExperiment} > Use this experiment </Button> </DialogActions> </Dialog> {/* Run metadata inputs */} <Input label={isRecurringRun ? 'Recurring run config name' : 'Run name'} required={true} onChange={this.handleChange('runName')} autoFocus={true} value={runName} variant='outlined' /> <Input label='Description (optional)' multiline={true} onChange={this.handleChange('description')} value={description} variant='outlined' /> {/* Experiment selection */} <div>This run will be associated with the following experiment</div> <Input value={experimentName} required={true} label='Experiment' disabled={true} variant='outlined' InputProps={{ classes: { disabled: css.nonEditableInput }, endAdornment: ( <InputAdornment position='end'> <Button color='secondary' id='chooseExperimentBtn' onClick={() => this.setStateSafe({ experimentSelectorOpen: true })} style={{ padding: '3px 5px', margin: 0 }} > Choose </Button> </InputAdornment> ), readOnly: true, }} /> <div> This run will use the following Kubernetes service account.{' '} <HelpButton helpText={ <div> Note, the service account needs{' '} <ExternalLink href='https://argoproj.github.io/argo-workflows/workflow-rbac/'> minimum permissions required by argo workflows </ExternalLink>{' '} and extra permissions the specific task requires. </div> } /> </div> <Input value={serviceAccount} onChange={this.handleChange('serviceAccount')} label='Service Account (Optional)' variant='outlined' /> {/* One-off/Recurring Run Type */} <div className={commonCss.header}>Run Type</div> {isClone && <span>{isRecurringRun ? 'Recurring' : 'One-off'}</span>} {!isClone && ( <React.Fragment> <FormControlLabel id='oneOffToggle' label='One-off' control={<Radio color='primary' />} onChange={() => this._updateRecurringRunState(false)} checked={!isRecurringRun} /> <FormControlLabel id='recurringToggle' label='Recurring' control={<Radio color='primary' />} onChange={() => this._updateRecurringRunState(true)} checked={isRecurringRun} /> </React.Fragment> )} {/* Recurring run controls */} {isRecurringRun && ( <React.Fragment> <div className={commonCss.header}>Run trigger</div> <div>Choose a method by which new runs will be triggered</div> <Trigger initialProps={{ trigger: this.state.trigger, maxConcurrentRuns: this.state.maxConcurrentRuns, catchup: this.state.catchup, }} onChange={({ trigger, maxConcurrentRuns, catchup }) => this.setStateSafe( { catchup, maxConcurrentRuns, trigger, }, this._validate.bind(this), ) } /> </React.Fragment> )} {/* Run parameters form */} <NewRunParameters initialParams={parameters} titleMessage={this._runParametersMessage()} handleParamChange={this._handleParamChange.bind(this)} /> {/* Create/Cancel buttons */} <div className={classes(commonCss.flex, padding(20, 'tb'))}> <BusyButton id='startNewRunBtn' disabled={!!errorMessage} busy={this.state.isBeingStarted} className={commonCss.buttonAction} title='Start' onClick={this._start.bind(this)} /> <Button id='exitNewRunPageBtn' onClick={() => { this.props.history.push( !!this.state.experiment ? RoutePage.EXPERIMENT_DETAILS.replace( ':' + RouteParams.experimentId, this.state.experiment.id!, ) : RoutePage.RUNS, ); }} > {isFirstRunInExperiment ? 'Skip this step' : 'Cancel'} </Button> <div className={classes(padding(20, 'r'))} style={{ color: 'red' }}> {errorMessage} </div> {this._areParametersMissing() && ( <div id='missing-parameters-message' style={{ color: 'orange' }}> Some parameters are missing values </div> )} </div> </div> </div> ); } public async refresh(): Promise<void> { return this.load(); } public async componentDidMount(): Promise<void> { return this.load(); } public async load(): Promise<void> { this.clearBanner(); const urlParser = new URLParser(this.props); let experimentId: string | null = urlParser.get(QUERY_PARAMS.experimentId); // Get clone run id from querystring if any const originalRunId = urlParser.get(QUERY_PARAMS.cloneFromRun); const originalRecurringRunId = urlParser.get(QUERY_PARAMS.cloneFromRecurringRun); // If we are not cloning from an existing run, we may have an embedded pipeline from a run from // a notebook. This is a somewhat hidden path that can be reached via the following steps: // 1. Create a pipeline and run it from a notebook // 2. Click [View Pipeline Version] for this run from one of the list pages // (Now you will be viewing a pipeline details page for a pipeline version that hasn't been uploaded) // 3. Click Create run const embeddedRunId = urlParser.get(QUERY_PARAMS.fromRunId); if (originalRunId) { // If we are cloning a run, fetch the original try { const originalRun = await Apis.runServiceApi.getRun(originalRunId); await this._prepareFormFromClone(originalRun.run, originalRun.pipeline_runtime); // If the querystring did not contain an experiment ID, try to get one from the run. if (!experimentId) { experimentId = RunUtils.getFirstExperimentReferenceId(originalRun.run); } } catch (err) { await this.showPageError(`Error: failed to retrieve original run: ${originalRunId}.`, err); logger.error(`Failed to retrieve original run: ${originalRunId}`, err); } } else if (originalRecurringRunId) { // If we are cloning a recurring run, fetch the original try { const originalJob = await Apis.jobServiceApi.getJob(originalRecurringRunId); await this._prepareFormFromClone(originalJob); this.setStateSafe({ trigger: originalJob.trigger, maxConcurrentRuns: originalJob.max_concurrency, catchup: !originalJob.no_catchup, }); if (!experimentId) { experimentId = RunUtils.getFirstExperimentReferenceId(originalJob); } } catch (err) { await this.showPageError( `Error: failed to retrieve original recurring run: ${originalRunId}.`, err, ); logger.error(`Failed to retrieve original recurring run: ${originalRunId}`, err); } } else if (embeddedRunId) { // If we create run from a workflow manifest that is acquried from an existing run. this._prepareFormFromEmbeddedPipeline(embeddedRunId); } else { // If we create a run from an existing pipeline version. // Get pipeline and pipeline version id from querystring if any const possiblePipelineId = urlParser.get(QUERY_PARAMS.pipelineId); if (possiblePipelineId) { try { const pipeline = await Apis.pipelineServiceApi.getPipeline(possiblePipelineId); this.setStateSafe({ parameters: pipeline.parameters || [], pipeline, pipelineName: (pipeline && pipeline.name) || '', }); const possiblePipelineVersionId = urlParser.get(QUERY_PARAMS.pipelineVersionId) || (pipeline.default_version && pipeline.default_version.id); if (possiblePipelineVersionId) { try { const pipelineVersion = await Apis.pipelineServiceApi.getPipelineVersion( possiblePipelineVersionId, ); this.setStateSafe({ parameters: pipelineVersion.parameters || [], pipelineVersion, pipelineVersionName: (pipelineVersion && pipelineVersion.name) || '', runName: this._getRunNameFromPipelineVersion( (pipelineVersion && pipelineVersion.name) || '', ), }); } catch (err) { urlParser.clear(QUERY_PARAMS.pipelineVersionId); await this.showPageError( `Error: failed to retrieve pipeline version: ${possiblePipelineVersionId}.`, err, ); logger.error( `Failed to retrieve pipeline version: ${possiblePipelineVersionId}`, err, ); } } else { this.setStateSafe({ runName: this._getRunNameFromPipelineVersion((pipeline && pipeline.name) || ''), }); } } catch (err) { urlParser.clear(QUERY_PARAMS.pipelineId); await this.showPageError( `Error: failed to retrieve pipeline: ${possiblePipelineId}.`, err, ); logger.error(`Failed to retrieve pipeline: ${possiblePipelineId}`, err); } } } let experiment: ApiExperiment | undefined; let experimentName = ''; const breadcrumbs = [{ displayName: 'Experiments', href: RoutePage.EXPERIMENTS }]; if (experimentId) { try { experiment = await Apis.experimentServiceApi.getExperiment(experimentId); experimentName = experiment.name || ''; breadcrumbs.push({ displayName: experimentName!, href: RoutePage.EXPERIMENT_DETAILS.replace(':' + RouteParams.experimentId, experimentId), }); } catch (err) { await this.showPageError( `Error: failed to retrieve associated experiment: ${experimentId}.`, err, ); logger.error(`Failed to retrieve associated experiment: ${experimentId}`, err); } } const isRecurringRun = urlParser.get(QUERY_PARAMS.isRecurring) === '1'; const titleVerb = originalRunId ? 'Clone' : 'Start'; const pageTitle = isRecurringRun ? `${titleVerb} a recurring run` : `${titleVerb} a run`; this.props.updateToolbar({ actions: this.props.toolbarProps.actions, breadcrumbs, pageTitle }); this.setStateSafe({ experiment, experimentName, isFirstRunInExperiment: urlParser.get(QUERY_PARAMS.firstRunInExperiment) === '1', isRecurringRun, }); this._validate(); } public handleChange = (name: string) => (event: any) => { const value = (event.target as TextFieldProps).value; this.setStateSafe({ [name]: value } as any, () => { this._validate(); }); }; protected async _experimentSelectorClosed(confirmed: boolean): Promise<void> { let { experiment } = this.state; if (confirmed && this.state.unconfirmedSelectedExperiment) { experiment = this.state.unconfirmedSelectedExperiment; } this.setStateSafe({ experiment, experimentName: (experiment && experiment.name) || '', experimentSelectorOpen: false, }); } protected async _pipelineSelectorClosed(confirmed: boolean): Promise<void> { let { parameters, pipeline, pipelineVersion } = this.state; if (confirmed && this.state.unconfirmedSelectedPipeline) { pipeline = this.state.unconfirmedSelectedPipeline; // Get the default version of selected pipeline to auto-fill the version // input field. if (pipeline.default_version) { pipelineVersion = await Apis.pipelineServiceApi.getPipelineVersion( pipeline.default_version.id!, ); parameters = pipelineVersion.parameters || []; } } this.setStateSafe( { parameters, pipeline, pipelineName: (pipeline && pipeline.name) || '', pipelineSelectorOpen: false, pipelineVersion, pipelineVersionName: (pipelineVersion && pipelineVersion.name) || '', }, () => this._validate(), ); } protected async _pipelineVersionSelectorClosed(confirmed: boolean): Promise<void> { let { parameters, pipelineVersion } = this.state; if (confirmed && this.state.unconfirmedSelectedPipelineVersion) { pipelineVersion = this.state.unconfirmedSelectedPipelineVersion; parameters = pipelineVersion.parameters || []; } this.setStateSafe( { parameters, pipelineVersion, pipelineVersionName: (pipelineVersion && pipelineVersion.name) || '', pipelineVersionSelectorOpen: false, }, () => this._validate(), ); } protected _updateRecurringRunState(isRecurringRun: boolean): void { this.props.updateToolbar({ pageTitle: isRecurringRun ? 'Start a recurring run' : 'Start a new run', }); this.setStateSafe({ isRecurringRun }); } protected _handleParamChange(index: number, value: string): void { const { parameters } = this.state; parameters[index].value = value; this.setStateSafe({ parameters }); } private async _uploadDialogClosed( confirmed: boolean, name: string, file: File | null, url: string, method: ImportMethod, description?: string, ): Promise<boolean> { if ( !confirmed || (method === ImportMethod.LOCAL && !file) || (method === ImportMethod.URL && !url) ) { this.setStateSafe({ pipelineSelectorOpen: true, uploadDialogOpen: false }); return false; } try { const uploadedPipeline = method === ImportMethod.LOCAL ? await Apis.uploadPipeline(name, description || '', file!) : await Apis.pipelineServiceApi.createPipeline({ name, url: { pipeline_url: url } }); this.setStateSafe( { pipeline: uploadedPipeline, pipelineName: (uploadedPipeline && uploadedPipeline.name) || '', pipelineSelectorOpen: false, uploadDialogOpen: false, }, () => this._validate(), ); return true; } catch (err) { const errorMessage = await errorToMessage(err); this.showErrorDialog('Failed to upload pipeline', errorMessage); return false; } } private async _prepareFormFromEmbeddedPipeline(embeddedRunId: string): Promise<void> { let embeddedPipelineSpec: string | null; let runWithEmbeddedPipeline: ApiRunDetail; try { runWithEmbeddedPipeline = await Apis.runServiceApi.getRun(embeddedRunId); embeddedPipelineSpec = RunUtils.getWorkflowManifest(runWithEmbeddedPipeline.run); } catch (err) { await this.showPageError( `Error: failed to retrieve the specified run: ${embeddedRunId}.`, err, ); logger.error(`Failed to retrieve the specified run: ${embeddedRunId}`, err); return; } if (!embeddedPipelineSpec) { await this.showPageError( `Error: somehow the run provided in the query params: ${embeddedRunId} had no embedded pipeline.`, ); return; } try { const workflow: Workflow = JSON.parse(embeddedPipelineSpec); const parameters = RunUtils.getParametersFromRun(runWithEmbeddedPipeline); this.setStateSafe({ parameters, usePipelineFromRunLabel: 'Using pipeline from previous page.', useWorkflowFromRun: true, workflowFromRun: workflow, }); } catch (err) { await this.showPageError( `Error: failed to parse the embedded pipeline's spec: ${embeddedPipelineSpec}.`, err, ); logger.error(`Failed to parse the embedded pipeline's spec from run: ${embeddedRunId}`, err); return; } this._validate(); } private async _prepareFormFromClone( originalRun?: ApiRun | ApiJob, runtime?: ApiPipelineRuntime, ): Promise<void> { if (!originalRun) { logger.error('Could not get cloned run details'); return; } let pipeline: ApiPipeline | undefined; let pipelineVersion: ApiPipelineVersion | undefined; let workflowFromRun: Workflow | undefined; let useWorkflowFromRun = false; let usePipelineFromRunLabel = ''; let name = ''; let pipelineVersionName = ''; const serviceAccount = originalRun.service_account || ''; // Case 1: a legacy run refers to a pipeline without specifying version. const referencePipelineId = RunUtils.getPipelineId(originalRun); // Case 2: a run refers to a pipeline version. const referencePipelineVersionId = RunUtils.getPipelineVersionId(originalRun); // Case 3: a run whose pipeline (version) has not been uploaded, such as runs started from // the CLI or notebooks const embeddedPipelineSpec = RunUtils.getWorkflowManifest(originalRun); if (referencePipelineVersionId) { try { // TODO(jingzhang36): optimize this part to make only one api call. pipelineVersion = await Apis.pipelineServiceApi.getPipelineVersion( referencePipelineVersionId, ); pipelineVersionName = pipelineVersion && pipelineVersion.name ? pipelineVersion.name : ''; pipeline = await Apis.pipelineServiceApi.getPipeline( RunUtils.getPipelineIdFromApiPipelineVersion(pipelineVersion)!, ); name = pipeline.name || ''; } catch (err) { await this.showPageError( 'Error: failed to find a pipeline version corresponding to that of the original run:' + ` ${originalRun.id}.`, err, ); return; } } else if (referencePipelineId) { try { pipeline = await Apis.pipelineServiceApi.getPipeline(referencePipelineId); name = pipeline.name || ''; } catch (err) { await this.showPageError( 'Error: failed to find a pipeline corresponding to that of the original run:' + ` ${originalRun.id}.`, err, ); return; } } else if (embeddedPipelineSpec) { try { workflowFromRun = JSON.parse(embeddedPipelineSpec); name = workflowFromRun!.metadata.name || ''; } catch (err) { await this.showPageError("Error: failed to read the clone run's pipeline definition.", err); return; } useWorkflowFromRun = true; usePipelineFromRunLabel = 'Using pipeline from cloned run'; } else { await this.showPageError("Could not find the cloned run's pipeline definition."); return; } if (!originalRun.pipeline_spec || !originalRun.pipeline_spec.workflow_manifest) { await this.showPageError(`Error: run ${originalRun.id} had no workflow manifest`); return; } const parameters = runtime ? await RunUtils.getParametersFromRuntime(runtime) // cloned from run : originalRun.pipeline_spec.parameters || []; // cloned from recurring run this.setStateSafe({ isClone: true, parameters, pipeline, pipelineName: name, pipelineVersion, pipelineVersionName, runName: this._getCloneName(originalRun.name!), usePipelineFromRunLabel, useWorkflowFromRun, workflowFromRun, serviceAccount, }); this._validate(); } private _runParametersMessage(): string { if (this.state.pipeline || this.state.workflowFromRun) { if (this.state.parameters.length) { return 'Specify parameters required by the pipeline'; } else { return 'This pipeline has no parameters'; } } return 'Parameters will appear after you select a pipeline'; } private _start(): void { if (!this.state.pipelineVersion && !this.state.workflowFromRun) { this.showErrorDialog('Run creation failed', 'Cannot start run without pipeline version'); logger.error('Cannot start run without pipeline version'); return; } const references: ApiResourceReference[] = []; if (this.state.experiment) { references.push({ key: { id: this.state.experiment.id, type: ApiResourceType.EXPERIMENT, }, relationship: ApiRelationship.OWNER, }); } if (this.state.pipelineVersion) { references.push({ key: { id: this.state.pipelineVersion!.id, type: ApiResourceType.PIPELINEVERSION, }, relationship: ApiRelationship.CREATOR, }); } let newRun: ApiRun | ApiJob = { description: this.state.description, name: this.state.runName, pipeline_spec: { parameters: (this.state.parameters || []).map(p => { p.value = (p.value || '').trim(); return p; }), workflow_manifest: this.state.useWorkflowFromRun ? JSON.stringify(this.state.workflowFromRun) : undefined, }, resource_references: references, service_account: this.state.serviceAccount, }; if (this.state.isRecurringRun) { newRun = Object.assign(newRun, { enabled: true, max_concurrency: this.state.maxConcurrentRuns || '1', no_catchup: !this.state.catchup, trigger: this.state.trigger, }); } this.setStateSafe({ isBeingStarted: true }, async () => { // TODO: there was previously a bug here where the await wasn't being applied to the API // calls, so a run creation could fail, and the success path would still be taken. We need // tests for this and other similar situations. try { this.state.isRecurringRun ? await Apis.jobServiceApi.createJob(newRun) : await Apis.runServiceApi.createRun(newRun); } catch (err) { const errorMessage = await errorToMessage(err); this.showErrorDialog('Run creation failed', errorMessage); logger.error('Error creating Run:', err); return; } finally { this.setStateSafe({ isBeingStarted: false }); } if (this.state.experiment) { this.props.history.push( RoutePage.EXPERIMENT_DETAILS.replace( ':' + RouteParams.experimentId, this.state.experiment.id!, ), ); } else { this.props.history.push(RoutePage.RUNS); } this.props.updateSnackbar({ message: `Successfully started new Run: ${newRun.name}`, open: true, }); }); } private _getCloneName(oldName: string): string { const numberRegex = /Clone(?: \(([0-9]*)\))? of (.*)/; const match = oldName.match(numberRegex); if (!match) { // No match, add Clone prefix return 'Clone of ' + oldName; } else { const cloneNumber = match[1] ? +match[1] : 1; return `Clone (${cloneNumber + 1}) of ${match[2]}`; } } private _generateRandomString(length: number): string { let d = 0; function randomChar(): string { const r = Math.trunc((d + Math.random() * 16) % 16); d = Math.floor(d / 16); return r.toString(16); } let str = ''; for (let i = 0; i < length; ++i) { str += randomChar(); } return str; } private _getRunNameFromPipelineVersion(pipelineVersionName: string): string { return 'Run of ' + pipelineVersionName + ' (' + this._generateRandomString(5) + ')'; } private _validate(): void { // Validate state const { pipelineVersion, workflowFromRun, maxConcurrentRuns, runName, trigger } = this.state; try { if (!pipelineVersion && !workflowFromRun) { throw new Error('A pipeline version must be selected'); } if (!runName) { throw new Error('Run name is required'); } const hasTrigger = trigger && (!!trigger.cron_schedule || !!trigger.periodic_schedule); if (hasTrigger) { const startDate = !!trigger!.cron_schedule ? trigger!.cron_schedule!.start_time : trigger!.periodic_schedule!.start_time; const endDate = !!trigger!.cron_schedule ? trigger!.cron_schedule!.end_time : trigger!.periodic_schedule!.end_time; if (startDate && endDate && startDate > endDate) { throw new Error('End date/time cannot be earlier than start date/time'); } const validMaxConcurrentRuns = (input: string) => !isNaN(Number.parseInt(input, 10)) && +input > 0; if (maxConcurrentRuns !== undefined && !validMaxConcurrentRuns(maxConcurrentRuns)) { throw new Error('For triggered runs, maximum concurrent runs must be a positive number'); } } this.setStateSafe({ errorMessage: '' }); } catch (err) { this.setStateSafe({ errorMessage: err.message }); } } private _areParametersMissing(): boolean { const { parameters } = this.state; return parameters.some(parameter => !parameter.value); } } const EnhancedNewRun: React.FC<PageProps> = props => { const namespace = React.useContext(NamespaceContext); return <NewRun {...props} namespace={namespace} />; }; export default EnhancedNewRun;
the_stack
'use strict' import Dataset from '../../rdf/dataset' import { rdf } from '../../utils' import { Algebra } from 'sparqljs' import { partition } from 'lodash' /** * Create a triple pattern that matches all RDF triples in a graph * @private * @return A triple pattern that matches all RDF triples in a graph */ function allPattern (): Algebra.TripleObject { return { subject: '?s', predicate: '?p', object: '?o' } } /** * Create a BGP that matches all RDF triples in a graph * @private * @return A BGP that matches all RDF triples in a graph */ function allBGP (): Algebra.BGPNode { return { type: 'bgp', triples: [allPattern()] } } /** * Build a SPARQL GROUP that selects all RDF triples from the Default Graph or a Named Graph * @private * @param source - Source graph * @param dataset - RDF dataset used to select the source * @param isSilent - True if errors should not be reported * @param [isWhere=false] - True if the GROUP should belong to a WHERE clause * @return The SPARQL GROUP clasue */ function buildGroupClause (source: Algebra.UpdateGraphTarget, dataset: Dataset, isSilent: boolean): Algebra.BGPNode | Algebra.UpdateGraphNode { if (source.default) { return allBGP() } else { // a SILENT modifier prevents errors when using an unknown graph if (!(dataset.hasNamedGraph(source.name!)) && !isSilent) { throw new Error(`Unknown Source Graph in ADD query ${source.name}`) } return { type: 'graph', name: source.name!, triples: [allPattern()] } } } /** * Build a SPARQL WHERE that selects all RDF triples from the Default Graph or a Named Graph * @private * @param source - Source graph * @param dataset - RDF dataset used to select the source * @param isSilent - True if errors should not be reported * @param [isWhere=false] - True if the GROUP should belong to a WHERE clause * @return The SPARQL GROUP clasue */ function buildWhereClause (source: Algebra.UpdateGraphTarget, dataset: Dataset, isSilent: boolean): Algebra.BGPNode | Algebra.GraphNode { if (source.default) { return allBGP() } else { // a SILENT modifier prevents errors when using an unknown graph if (!(dataset.hasNamedGraph(source.name!)) && !isSilent) { throw new Error(`Unknown Source Graph in ADD query ${source.name}`) } const bgp: Algebra.BGPNode = { type: 'bgp', triples: [allPattern()] } return { type: 'graph', name: source.name!, patterns: [bgp] } } } /** * Rewrite an ADD query into a INSERT query * @see https://www.w3.org/TR/2013/REC-sparql11-update-20130321/#add * @param addQuery - Parsed ADD query * @param dataset - related RDF dataset * @return Rewritten ADD query */ export function rewriteAdd (addQuery: Algebra.UpdateCopyMoveNode, dataset: Dataset): Algebra.UpdateQueryNode { return { updateType: 'insertdelete', silent: addQuery.silent, insert: [buildGroupClause(addQuery.destination, dataset, addQuery.silent)], where: [buildWhereClause(addQuery.source, dataset, addQuery.silent)] } } /** * Rewrite a COPY query into a CLEAR + INSERT/DELETE query * @see https://www.w3.org/TR/2013/REC-sparql11-update-20130321/#copy * @param copyQuery - Parsed COPY query * @param dataset - related RDF dataset * @return Rewritten COPY query, i.e., a sequence [CLEAR query, INSERT query] */ export function rewriteCopy (copyQuery: Algebra.UpdateCopyMoveNode, dataset: Dataset): [Algebra.UpdateClearNode, Algebra.UpdateQueryNode] { // first, build a CLEAR query to empty the destination const clear: Algebra.UpdateClearNode = { type: 'clear', silent: copyQuery.silent, graph: { type: 'graph' } } if (copyQuery.destination.default) { clear.graph.default = true } else { clear.graph.type = copyQuery.destination.type clear.graph.name = copyQuery.destination.name } // then, build an INSERT query to copy the data const update = rewriteAdd(copyQuery, dataset) return [clear, update] } /** * Rewrite a MOVE query into a CLEAR + INSERT/DELETE + CLEAR query * @see https://www.w3.org/TR/2013/REC-sparql11-update-20130321/#move * @param moveQuery - Parsed MOVE query * @param dataset - related RDF dataset * @return Rewritten MOVE query, i.e., a sequence [CLEAR query, INSERT query, CLEAR query] */ export function rewriteMove (moveQuery: Algebra.UpdateCopyMoveNode, dataset: Dataset): [Algebra.UpdateClearNode, Algebra.UpdateQueryNode, Algebra.UpdateClearNode] { // first, build a classic COPY query const [ clearBefore, update ] = rewriteCopy(moveQuery, dataset) // then, append a CLEAR query to clear the source graph const clearAfter: Algebra.UpdateClearNode = { type: 'clear', silent: moveQuery.silent, graph: { type: 'graph' } } if (moveQuery.source.default) { clearAfter.graph.default = true } else { clearAfter.graph.type = moveQuery.source.type clearAfter.graph.name = moveQuery.source.name } return [clearBefore, update, clearAfter] } /** * Extract property paths triples and classic triples from a set of RDF triples. * It also performs a first rewriting of some property paths. * @param bgp - Set of RDF triples * @return A tuple [classic triples, triples with property paths, set of variables added during rewriting] */ export function extractPropertyPaths (bgp: Algebra.BGPNode): [Algebra.TripleObject[], Algebra.PathTripleObject[], string[]] { const parts = partition(bgp.triples, triple => typeof(triple.predicate) === 'string') let classicTriples: Algebra.TripleObject[] = parts[0] as Algebra.TripleObject[] let pathTriples: Algebra.PathTripleObject[] = parts[1] as Algebra.PathTripleObject[] let variables: string[] = [] // TODO: change bgp evaluation's behavior for ask queries when subject and object are given /*if (pathTriples.length > 0) { // review property paths and rewrite those equivalent to a regular BGP const paths: Algebra.PathTripleObject[] = [] // first rewriting phase pathTriples.forEach((triple, tIndex) => { const t = triple as Algebra.PathTripleObject // 1) unpack sequence paths into a set of RDF triples if (t.predicate.pathType === '/') { t.predicate.items.forEach((pred, seqIndex) => { const joinVar = `?seq_${tIndex}_join_${seqIndex}` const nextJoinVar = `?seq_${tIndex}_join_${seqIndex + 1}` variables.push(joinVar) // non-property paths triples are fed to the BGP executor if (typeof(pred) === 'string') { classicTriples.push({ subject: (seqIndex == 0) ? triple.subject : joinVar, predicate: pred, object: (seqIndex == t.predicate.items.length - 1) ? triple.object : nextJoinVar }) } else { paths.push({ subject: (seqIndex == 0) ? triple.subject : joinVar, predicate: pred, object: (seqIndex == t.predicate.items.length - 1) ? triple.object : nextJoinVar }) } }) } else { paths.push(t) } }) pathTriples = paths }*/ return [classicTriples, pathTriples, variables] } /** * Rewriting utilities for Full Text Search queries */ export namespace fts { /** * A Full Text Search query */ export interface FullTextSearchQuery { /** The pattern queried by the full text search */ pattern: Algebra.TripleObject, /** The SPARQL varibale on which the full text search is performed */ variable: string, /** The magic triples sued to configured the full text search query */ magicTriples: Algebra.TripleObject[] } /** * The results of extracting full text search queries from a BGP */ export interface ExtractionResults { /** The set of full text search queries extracted from the BGP */ queries: FullTextSearchQuery[], /** Regular triple patterns, i.e., those who should be evaluated as a regular BGP */ classicPatterns: Algebra.TripleObject[] } /** * Extract all full text search queries from a BGP, using magic triples to identify them. * A magic triple is an IRI prefixed by 'https://callidon.github.io/sparql-engine/search#' (ses:search, ses:rank, ses:minRank, etc). * @param bgp - BGP to analyze * @return The extraction results */ export function extractFullTextSearchQueries (bgp: Algebra.TripleObject[]): ExtractionResults { const queries: FullTextSearchQuery[] = [] const classicPatterns: Algebra.TripleObject[] = [] // find, validate and group all magic triples per query variable const patterns: Algebra.TripleObject[] = [] const magicGroups = new Map<string, Algebra.TripleObject[]>() const prefix = rdf.SES('') bgp.forEach(triple => { // A magic triple is an IRI prefixed by 'https://callidon.github.io/sparql-engine/search#' if (rdf.isIRI(triple.predicate) && triple.predicate.startsWith(prefix)) { // assert that the magic triple's subject is a variable if (!rdf.isVariable(triple.subject)) { throw new SyntaxError(`Invalid Full Text Search query: the subject of the magic triple ${triple} must a valid URI/IRI.`) } if (!magicGroups.has(triple.subject)) { magicGroups.set(triple.subject, [ triple ]) } else { magicGroups.get(triple.subject)!.push(triple) } } else { patterns.push(triple) } }) // find all triple pattern whose object is the subject of some magic triples patterns.forEach(pattern => { if (magicGroups.has(pattern.subject)) { queries.push({ pattern, variable: pattern.subject, magicTriples: magicGroups.get(pattern.subject)! }) } else if (magicGroups.has(pattern.object)) { queries.push({ pattern, variable: pattern.object, magicTriples: magicGroups.get(pattern.object)! }) } else { classicPatterns.push(pattern) } }) return { queries, classicPatterns } } }
the_stack
import * as path from 'path'; import * as fs from 'fs'; import { workspace, window, commands, QuickPickItem, ExtensionContext, StatusBarAlignment, TextEditor,ThemeColor, Disposable, TextDocumentSaveReason, Uri } from 'vscode'; import { LanguageClient, LanguageClientOptions, SettingMonitor, ServerOptions, TextEdit, RequestType, TextDocumentIdentifier, ResponseError, InitializeError, State as ClientState, NotificationType, TransportKind, ProposedProtocol } from 'vscode-languageclient'; import { exec } from 'child_process'; import * as open from 'open'; interface AllFixesParams { readonly textDocument: TextDocumentIdentifier; readonly isOnSave: boolean; } interface AllFixesResult { readonly documentVersion: number; readonly edits: TextEdit[]; readonly ruleId?: string; } namespace AllFixesRequest { export const type = new RequestType<AllFixesParams, AllFixesResult, void, void>('textDocument/tslint/allFixes'); } interface NoTSLintLibraryParams { readonly source: TextDocumentIdentifier; } interface NoTSLintLibraryResult { } namespace NoTSLintLibraryRequest { export const type = new RequestType<NoTSLintLibraryParams, NoTSLintLibraryResult, void, void>('tslint/noLibrary'); } enum Status { ok = 1, warn = 2, error = 3 } interface StatusParams { state: Status; } namespace StatusNotification { export const type = new NotificationType<StatusParams, void>('tslint/status'); } let willSaveTextDocument: Disposable | undefined; let configurationChangedListener: Disposable; export function activate(context: ExtensionContext) { let statusBarItem = window.createStatusBarItem(StatusBarAlignment.Right, 0); let tslintStatus: Status = Status.ok; let serverRunning: boolean = false; statusBarItem.text = 'TSLint'; statusBarItem.command = 'tslint.showOutputChannel'; let errorColor = new ThemeColor('tslint.error'); let warningColor = new ThemeColor('tslint.warning'); console.log('Congratulations, the extension is working!'); function showStatusBarItem(show: boolean): void { if (show) { statusBarItem.show(); } else { statusBarItem.hide(); } } function updateStatus(status: Status) { switch (status) { case Status.ok: statusBarItem.color = undefined; break; case Status.warn: statusBarItem.color = warningColor; break; case Status.error: statusBarItem.color = errorColor; // darkred doesn't work break; } if (tslintStatus !== Status.ok && status === Status.ok) { // an error got addressed fix, write to the output that the status is OK client.info('vscode-tslint: Status is OK'); } tslintStatus = status; udpateStatusBarVisibility(window.activeTextEditor); } function isTypeScriptDocument(languageId) { return languageId === 'typescript' || languageId === 'typescriptreact' || languageId === 'vue'; } function isJavaScriptDocument(languageId) { return languageId === 'javascript' || languageId === 'javascriptreact'; } function isEnableForJavaScriptDocument(languageId) { let isJsEnable = workspace.getConfiguration('tslint').get('jsEnable', true); if (isJsEnable && isJavaScriptDocument(languageId)) { return true; } return false; } function udpateStatusBarVisibility(editor: TextEditor | undefined): void { switch (tslintStatus) { case Status.ok: statusBarItem.text = 'TSLint'; break; case Status.warn: statusBarItem.text = 'TSLint: Warning'; break; case Status.error: statusBarItem.text = 'TSLint: Error'; break; } let enabled = workspace.getConfiguration('tslint')['enable']; if (!editor || !enabled) { showStatusBarItem(false); return; } showStatusBarItem( serverRunning && ( tslintStatus !== Status.ok || ((isTypeScriptDocument(editor.document.languageId) || isEnableForJavaScriptDocument(editor.document.languageId))) ) ); } window.onDidChangeActiveTextEditor(udpateStatusBarVisibility); udpateStatusBarVisibility(window.activeTextEditor); // We need to go one level up since an extension compile the js code into // the output folder. let serverModulePath = path.join(__dirname, '..', 'server', 'server.js'); // break on start options //let debugOptions = { execArgv: ["--nolazy", "--debug=6010", "--debug-brk"] }; let debugOptions = { execArgv: ["--nolazy", "--inspect=6010"], cwd: process.cwd() }; let runOptions = {cwd: process.cwd()}; let serverOptions: ServerOptions = { run: { module: serverModulePath, transport: TransportKind.ipc, options: runOptions }, debug: { module: serverModulePath, transport: TransportKind.ipc, options: debugOptions } }; let clientOptions: LanguageClientOptions = { documentSelector: ['typescript', 'typescriptreact', 'vue', 'javascript', 'javascriptreact'], synchronize: { configurationSection: 'tslint', fileEvents: workspace.createFileSystemWatcher('**/tslint.json') }, diagnosticCollectionName: 'tslint', initializationFailedHandler: (error) => { client.error('Server initialization failed.', error); client.outputChannel.show(true); return false; }, }; let client = new LanguageClient('tslint', serverOptions, clientOptions); client.registerFeatures(ProposedProtocol(client)); const running = 'Linter is running.'; const stopped = 'Linter has stopped.'; client.onDidChangeState((event) => { if (event.newState === ClientState.Running) { client.info(running); statusBarItem.tooltip = running; serverRunning = true; } else { client.info(stopped); statusBarItem.tooltip = stopped; serverRunning = false; } udpateStatusBarVisibility(window.activeTextEditor); }); client.onReady().then(() => { client.onNotification(StatusNotification.type, (params) => { updateStatus(params.state); }); client.onRequest(NoTSLintLibraryRequest.type, (params) => { let uri: Uri = Uri.parse(params.source.uri); if (workspace.rootPath) { client.info([ '', `Failed to load the TSLint library for the document ${uri.fsPath}`, '', 'To use TSLint in this workspace please install tslint using \'npm install tslint\' or globally using \'npm install -g tslint\'.', 'TSLint has a peer dependency on `typescript`, make sure that `typescript` is installed as well.', 'You need to reopen the workspace after installing tslint.', ].join('\n')); } else { client.info([ `Failed to load the TSLint library for the document ${uri.fsPath}`, 'To use TSLint for single file install tslint globally using \'npm install -g tslint\'.', 'TSLint has a peer dependency on `typescript`, make sure that `typescript` is installed as well.', 'You need to reopen VS Code after installing tslint.', ].join('\n')); } updateStatus(Status.warn); return {}; }); }); function applyTextEdits(uri: string, documentVersion: number, edits: TextEdit[]) { let textEditor = window.activeTextEditor; if (textEditor && textEditor.document.uri.toString() === uri) { if (textEditor.document.version !== documentVersion) { window.showInformationMessage(`TSLint fixes are outdated and can't be applied to the document.`); } textEditor.edit(mutator => { for (let edit of edits) { mutator.replace(client.protocol2CodeConverter.asRange(edit.range), edit.newText); } }).then((success) => { if (!success) { window.showErrorMessage('Failed to apply TSLint fixes to the document. Please consider opening an issue with steps to reproduce.'); } }); } } function applyDisableRuleEdit(uri: string, documentVersion: number, edits: TextEdit[]) { let textEditor = window.activeTextEditor; if (textEditor && textEditor.document.uri.toString() === uri) { if (textEditor.document.version !== documentVersion) { window.showInformationMessage(`TSLint fixes are outdated and can't be applied to the document.`); } // prefix disable comment with same indent as line with the diagnostic let edit = edits[0]; let ruleLine = textEditor.document.lineAt(edit.range.start.line); let prefixIndex = ruleLine.firstNonWhitespaceCharacterIndex; let prefix = ruleLine.text.substr(0, prefixIndex); edit.newText = prefix + edit.newText; applyTextEdits(uri, documentVersion, edits); } } function showRuleDocumentation(uri: string, documentVersion: number, edits: TextEdit[], ruleId: string) { const tslintDocBaseURL = "https://palantir.github.io/tslint/rules"; if (!ruleId) { return; } open(tslintDocBaseURL+'/'+ruleId); } function fixAllProblems() { // server is not running so there can be no problems to fix if (!serverRunning) { return; } let textEditor = window.activeTextEditor; if (!textEditor) { return; } let uri: string = textEditor.document.uri.toString(); client.sendRequest(AllFixesRequest.type, { textDocument: { uri } }).then((result) => { if (result) { applyTextEdits(uri, result.documentVersion, result.edits); } }, (error) => { window.showErrorMessage('Failed to apply TSLint fixes to the document. Please consider opening an issue with steps to reproduce.'); }); } async function createDefaultConfiguration() { let folders = workspace.workspaceFolders; if (!folders) { window.showErrorMessage('A TSLint configuration file can only be generated if VS Code is opened on a folder.'); return; } let folderPicks = folders.map(each => { return {label: each.name, description: each.uri.fsPath}; }); let selection; if (folderPicks.length === 1) { selection = folderPicks[0]; } else { selection = await window.showQuickPick(folderPicks, {placeHolder: 'Select the target folder for the tslint.json'}); } if(!selection) { return; } let tslintConfigFile = path.join(selection.description, 'tslint.json'); if (fs.existsSync(tslintConfigFile)) { window.showInformationMessage('A TSLint configuration file already exists.'); let document = await workspace.openTextDocument(tslintConfigFile); window.showTextDocument(document); } else { const cmd = 'tslint --init'; const p = exec(cmd, { cwd: selection.description, env: process.env }); p.on('exit', async (code: number, signal: string) => { if (code === 0) { let document = await workspace.openTextDocument(tslintConfigFile); window.showTextDocument(document); } }); } } function configurationChanged() { let config = workspace.getConfiguration('tslint'); let autoFix = config.get('autoFixOnSave', false); if (autoFix && !willSaveTextDocument) { willSaveTextDocument = workspace.onWillSaveTextDocument((event) => { let document = event.document; // only auto fix when the document was manually saved by the user if (!(isTypeScriptDocument(document.languageId) || isEnableForJavaScriptDocument(document.languageId)) || event.reason !== TextDocumentSaveReason.Manual) { return; } const version = document.version; event.waitUntil( client.sendRequest(AllFixesRequest.type, { textDocument: { uri: document.uri.toString() }, isOnSave: true }).then((result) => { if (result && version === result.documentVersion) { return client.protocol2CodeConverter.asTextEdits(result.edits); } else { return []; } }) ); }); } else if (!autoFix && willSaveTextDocument) { willSaveTextDocument.dispose(); willSaveTextDocument = undefined; } udpateStatusBarVisibility(window.activeTextEditor); } configurationChangedListener = workspace.onDidChangeConfiguration(configurationChanged); configurationChanged(); context.subscriptions.push( client.start(), configurationChangedListener, // internal commands commands.registerCommand('_tslint.applySingleFix', applyTextEdits), commands.registerCommand('_tslint.applySameFixes', applyTextEdits), commands.registerCommand('_tslint.applyAllFixes', applyTextEdits), commands.registerCommand('_tslint.applyDisableRule', applyDisableRuleEdit), commands.registerCommand('_tslint.showRuleDocumentation', showRuleDocumentation), // user commands commands.registerCommand('tslint.fixAllProblems', fixAllProblems), commands.registerCommand('tslint.createConfig', createDefaultConfiguration), commands.registerCommand('tslint.showOutputChannel', () => { client.outputChannel.show(); }), statusBarItem ); } export function deactivate() { if (willSaveTextDocument) { willSaveTextDocument.dispose(); willSaveTextDocument = undefined; } }
the_stack
import appModule from 'app-module-path'; import * as globby from 'globby'; import * as fs from '../fs'; import * as inquirer from '../inquirer'; import { PackageJson } from '../fs'; jest.mock('flex-plugins-utils-logger/dist/lib/inquirer'); jest.mock('globby'); jest.mock('app-module-path'); describe('fs', () => { const flexPluginScripts = 'flex-plugin-scripts'; const flexPluginWebpack = 'flex-plugin-webpack'; const flexPluginScriptsPath = `/path/to/${flexPluginScripts}`; const flexPluginWebpackPath = `/path/to/${flexPluginWebpack}`; const pluginName = 'plugin-test'; const fileContent = '{"version":1}'; const filePath = 'path1/path2'; const appPackage: fs.AppPackageJson = { version: '1', name: pluginName, dependencies: { [flexPluginScripts]: '1', 'flex-plugin': '2', }, devDependencies: {}, }; beforeEach(() => { jest.resetAllMocks(); jest.resetModules(); jest.restoreAllMocks(); }); describe('readPackageJson', () => { it('should read package.json', () => { const readFileSync = jest.spyOn(fs.default, 'readFileSync').mockReturnValue(fileContent); const pkg = fs.readPackageJson('filePath'); expect(pkg).toEqual({ version: 1 }); expect(readFileSync).toHaveBeenCalledTimes(1); expect(readFileSync).toHaveBeenCalledWith('filePath', 'utf8'); readFileSync.mockRestore(); }); }); describe('getSileSizeInBytes', () => { it('should get file size', () => { // @ts-ignore const statSync = jest.spyOn(fs.default, 'statSync').mockReturnValue({ size: 123 }); const size = fs.getSileSizeInBytes('path', 'to', 'file.js'); expect(size).toEqual(123); expect(statSync).toHaveBeenCalledTimes(1); expect(statSync).toHaveBeenCalledWith(expect.toMatchPath('path/to/file.js')); }); }); describe('getFileSizeInMB', () => { it('should get file size', () => { // @ts-ignore const statSync = jest.spyOn(fs.default, 'statSync').mockReturnValue({ size: 1024 * 1024 * 2 }); const size = fs.getFileSizeInMB('path', 'to', 'file.js'); expect(size).toEqual(2); expect(statSync).toHaveBeenCalledTimes(1); expect(statSync).toHaveBeenCalledWith(expect.toMatchPath('path/to/file.js')); }); }); describe('readJsonFile', () => { it('should read package.json', () => { const readFileSync = jest.spyOn(fs.default, 'readFileSync').mockReturnValue(fileContent); const pkg = fs.readJsonFile('file', 'path'); expect(pkg).toEqual({ version: 1 }); expect(readFileSync).toHaveBeenCalledTimes(1); expect(readFileSync).toHaveBeenCalledWith(expect.toMatchPath('file/path'), 'utf8'); readFileSync.mockRestore(); }); }); describe('readAppPackageJson', () => { it('should read app package', () => { const readPackageJson = jest.spyOn(fs, 'readPackageJson').mockReturnValue(appPackage); const getPackageJsonPath = jest.spyOn(fs, 'getPackageJsonPath').mockReturnValue('path'); const pkg = fs.readAppPackageJson(); expect(pkg).toEqual(appPackage); expect(readPackageJson).toHaveBeenCalledTimes(1); expect(readPackageJson).toHaveBeenCalledWith(expect.toMatchPath('path')); expect(getPackageJsonPath).toHaveBeenCalledTimes(1); readPackageJson.mockRestore(); getPackageJsonPath.mockRestore(); }); }); describe('getPackageJsonPath', () => { it('should return the right path', () => { const cwd = jest.spyOn(fs, 'getCwd').mockImplementation(() => 'test'); const path = fs.getPackageJsonPath(); expect(cwd).toHaveBeenCalledTimes(1); expect(path).toMatchPath('test/package.json'); cwd.mockRestore(); }); it('should read custom path', () => { const readFileSync = jest.spyOn(fs.default, 'readFileSync').mockImplementation(() => fileContent); const pkg = fs.readPackageJson('another-path'); expect(pkg).toEqual({ version: 1 }); expect(readFileSync).toHaveBeenCalledTimes(1); expect(readFileSync).toHaveBeenCalledWith(expect.toMatchPath('another-path'), 'utf8'); readFileSync.mockRestore(); }); }); describe('checkFilesExist', () => { it('loop through all files', () => { // @ts-ignore const existsSync = jest.spyOn(fs.default, 'existsSync').mockImplementation(() => { /* no-op */ }); fs.checkFilesExist('file1', 'file2'); expect(existsSync).toHaveBeenCalledTimes(2); existsSync.mockRestore(); }); }); describe('writeFile', () => { it('should join paths', () => { const writeFileSync = jest.spyOn(fs.default, 'writeFileSync').mockImplementation(() => { /* no-op */ }); fs.writeFile('the-str', 'path1', 'path2'); expect(writeFileSync).toHaveBeenCalledTimes(1); expect(writeFileSync).toHaveBeenCalledWith(expect.toMatchPath(filePath), 'the-str'); }); }); describe('writeJSONFile', () => { it('should write JSON file', () => { const writeFile = jest.spyOn(fs, 'writeFile').mockImplementation(() => { /* no-op */ }); fs.writeJSONFile({ key1: 'value1' }, 'path1', 'path2'); // Leave this formatted like this! This is a formatted JSON string test const str = `{ \"key1\": \"value1\" }`; expect(writeFile).toHaveBeenCalledTimes(1); expect(writeFile).toHaveBeenCalledWith(str, 'path1', 'path2'); }); }); describe('removeFile', () => { it('should remove file', () => { const unlinkSync = jest.spyOn(fs.default, 'unlinkSync').mockImplementation(() => { /* no-op */ }); fs.removeFile('path1', 'path2'); expect(unlinkSync).toHaveBeenCalledTimes(1); expect(unlinkSync).toHaveBeenCalledWith(expect.toMatchPath(filePath)); }); }); describe('copyFile', () => { it('should copy file', () => { const copyFileSync = jest.spyOn(fs.default, 'copyFileSync').mockImplementation(() => { /* no-op */ }); fs.copyFile(['path1', 'path2'], ['path3', 'path4']); expect(copyFileSync).toHaveBeenCalledTimes(1); expect(copyFileSync).toHaveBeenCalledWith(expect.toMatchPath(filePath), expect.toMatchPath('path3/path4')); }); }); describe('checkAFileExists', () => { it('should check a file', () => { const existsSync = jest.spyOn(fs.default, 'existsSync').mockReturnValue(true); expect(fs.checkAFileExists('path1', 'path2')).toEqual(true); expect(existsSync).toHaveBeenCalledTimes(1); expect(existsSync).toHaveBeenCalledWith(expect.toMatchPath(filePath)); }); }); describe('updateAppVersion', () => { it('should update version', () => { const pkgBefore = { ...appPackage }; const pkgAfter: fs.PackageJson = { ...pkgBefore, version: '2' }; // @ts-ignore const writeFileSync = jest.spyOn(fs.default, 'writeFileSync').mockImplementation(() => { /* no-op */ }); // @ts-ignore const getPackageJsonPath = jest.spyOn(fs, 'getPackageJsonPath').mockReturnValue('package.json'); const readPackageJson = jest.spyOn(fs, 'readPackageJson').mockReturnValue(pkgBefore); fs.updateAppVersion('2'); expect(writeFileSync).toHaveBeenCalledTimes(1); expect(writeFileSync).toHaveBeenCalledWith(expect.toMatchPath('package.json'), JSON.stringify(pkgAfter, null, 2)); writeFileSync.mockRestore(); getPackageJsonPath.mockRestore(); readPackageJson.mockRestore(); }); }); describe('findUp', () => { const findUpDir = '/path1/path2/path3'; const fileName = 'foo'; it('should find on one up', () => { const path = '/path1/path2/path3/foo'; // @ts-ignore const existsSync = jest .spyOn(fs.default, 'existsSync') .mockImplementation((p) => p === global.utils.normalizePath(path)); fs.findUp(findUpDir, fileName); expect(existsSync).toHaveBeenCalledTimes(1); existsSync.mockRestore(); }); it('should find on two up', () => { const path = '/path1/path2/foo'; // @ts-ignore const existsSync = jest .spyOn(fs.default, 'existsSync') .mockImplementation((p) => p === global.utils.normalizePath(path)); fs.findUp(findUpDir, fileName); expect(existsSync).toHaveBeenCalledTimes(2); existsSync.mockRestore(); }); it('should fail if it reaches root directory', (done) => { // @ts-ignore const existsSync = jest.spyOn(fs.default, 'existsSync').mockImplementation(() => false); try { fs.findUp(findUpDir, fileName); } catch (e) { done(); } existsSync.mockRestore(); }); }); describe('resolveCwd', () => { it('should call resolveRelative', () => { const resolveRelative = jest.spyOn(fs, 'resolveRelative').mockReturnValue('foo'); expect(fs.resolveCwd('some-path')).toEqual('foo'); expect(resolveRelative).toHaveBeenCalledTimes(1); expect(resolveRelative).toHaveBeenCalledWith(expect.any(String), expect.toMatchPath('some-path')); resolveRelative.mockRestore(); }); }); describe('resolveRelative', () => { it('should return dir if no paths passed', () => { expect(fs.resolveRelative('the-dir')).toMatchPath('the-dir'); }); it('should build path with single item and no extension', () => { expect(fs.resolveRelative('the-dir', 'the-sub')).toMatchPath('the-dir/the-sub'); }); it('should build path with single item that is extension', () => { expect(fs.resolveRelative('the-file', '.extension')).toMatchPath('the-file.extension'); }); it('should build path with two items and no extension', () => { expect(fs.resolveRelative('foo', 'bar', 'baz')).toMatchPath('foo/bar/baz'); }); it('should build path with two items and an extension', () => { expect(fs.resolveRelative('foo', 'bar', '.baz')).toMatchPath('foo/bar.baz'); }); it('should build path with multiple items and no extension', () => { expect(fs.resolveRelative('foo', 'bar', 'baz', 'test', 'it')).toMatchPath('foo/bar/baz/test/it'); }); it('should build path with multiple items and an extension', () => { expect(fs.resolveRelative('foo', 'bar', 'baz', 'test', '.it')).toMatchPath('foo/bar/baz/test.it'); }); }); describe('findGlobsIn', () => { it('should call globby', () => { const dirs = ['path1', 'path2']; const sync = jest.spyOn(globby, 'sync').mockReturnValue(dirs); const patterns = ['pattern1', 'pattern2']; const result = fs.findGlobsIn('the-dir', ...patterns); expect(result).toEqual(dirs); expect(sync).toHaveBeenCalledTimes(1); expect(sync).toHaveBeenCalledWith(patterns, { cwd: 'the-dir' }); }); }); describe('checkPluginConfigurationExists', () => { const pluginsJsonPath = 'test-dir-plugins'; const name = pluginName; const dir = 'test-dir'; const anotherDir = 'another-dir'; const cliPath = { dir, flexDir: 'test-dir-flex', pluginsJsonPath, }; let checkFilesExist = jest.spyOn(fs, 'checkFilesExist'); let mkdirpSync = jest.spyOn(fs, 'mkdirpSync'); let writeFileSync = jest.spyOn(fs.default, 'writeFileSync'); let readJsonFile = jest.spyOn(fs, 'readJsonFile'); let confirm = jest.spyOn(inquirer, 'confirm'); let getCliPaths = jest.spyOn(fs, 'getCliPaths'); beforeEach(() => { checkFilesExist = jest.spyOn(fs, 'checkFilesExist'); mkdirpSync = jest.spyOn(fs, 'mkdirpSync'); writeFileSync = jest.spyOn(fs.default, 'writeFileSync'); readJsonFile = jest.spyOn(fs, 'readJsonFile'); confirm = jest.spyOn(inquirer, 'confirm'); getCliPaths = jest.spyOn(fs, 'getCliPaths'); mkdirpSync.mockReturnThis(); writeFileSync.mockReturnThis(); readJsonFile.mockReturnValue({ plugins: [] }); // @ts-ignore getCliPaths.mockReturnValue(cliPath); }); it('make directories if not found', async () => { checkFilesExist.mockReturnValue(false); await fs.checkPluginConfigurationExists(name, dir); expect(checkFilesExist).toHaveBeenCalledTimes(1); expect(checkFilesExist).toHaveBeenCalledWith(pluginsJsonPath); expect(mkdirpSync).toHaveBeenCalledTimes(1); expect(mkdirpSync).toHaveBeenCalledWith('test-dir-flex'); }); it('do nothing if directories are found', async () => { checkFilesExist.mockReturnValue(true); const result = await fs.checkPluginConfigurationExists(name, dir); expect(checkFilesExist).toHaveBeenCalledTimes(1); expect(checkFilesExist).toHaveBeenCalledWith(pluginsJsonPath); expect(mkdirpSync).not.toHaveBeenCalled(); expect(result).toEqual(true); }); it('should add the plugin to plugins.json if not found', async () => { checkFilesExist.mockReturnValue(true); readJsonFile.mockReturnValue({ plugins: [] }); writeFileSync.mockReturnThis(); const result = await fs.checkPluginConfigurationExists(name, dir); expect(checkFilesExist).toHaveBeenCalledTimes(1); expect(readJsonFile).toHaveBeenCalledTimes(1); expect(writeFileSync).toHaveBeenCalledTimes(1); expect(writeFileSync).toHaveBeenCalledWith( pluginsJsonPath, JSON.stringify({ plugins: [{ name: pluginName, dir }] }, null, 2), ); expect(result).toEqual(true); }); it('do nothing if plugin has same directory as an existing one', async () => { checkFilesExist.mockReturnValue(true); readJsonFile.mockReturnValue({ plugins: [{ name: pluginName, dir }] }); writeFileSync.mockReturnThis(); const result = await fs.checkPluginConfigurationExists(name, dir); expect(checkFilesExist).toHaveBeenCalledTimes(1); expect(readJsonFile).toHaveBeenCalledTimes(1); expect(writeFileSync).not.toHaveBeenCalled(); expect(result).toEqual(false); }); it('change file path if user confirms', async () => { checkFilesExist.mockReturnValue(true); readJsonFile.mockReturnValue({ plugins: [{ name: pluginName, dir: anotherDir }] }); writeFileSync.mockReturnThis(); confirm.mockResolvedValue(true); const result = await fs.checkPluginConfigurationExists(name, dir); expect(checkFilesExist).toHaveBeenCalledTimes(1); expect(readJsonFile).toHaveBeenCalledTimes(1); // expect(confirm).toHaveBeenCalledTimes(1); expect(readJsonFile).toHaveBeenCalledTimes(1); expect(writeFileSync).toHaveBeenCalledTimes(1); expect(writeFileSync).toHaveBeenCalledWith( pluginsJsonPath, JSON.stringify({ plugins: [{ name: pluginName, dir }] }, null, 2), ); expect(result).toEqual(true); }); it('do not change file path, user did not confirm', async () => { checkFilesExist.mockReturnValue(true); readJsonFile.mockReturnValue({ plugins: [{ name: pluginName, dir: anotherDir }] }); writeFileSync.mockReturnThis(); confirm.mockResolvedValue(false); const result = await fs.checkPluginConfigurationExists(name, dir, true); expect(checkFilesExist).toHaveBeenCalledTimes(1); expect(readJsonFile).toHaveBeenCalledTimes(1); expect(confirm).toHaveBeenCalledTimes(1); expect(writeFileSync).not.toHaveBeenCalled(); expect(result).toEqual(false); }); }); describe('_getFlexPluginScripts', () => { it('should resolve path', () => { const thePath = 'the/path'; const resolveModulePath = jest.spyOn(fs, 'resolveModulePath').mockReturnValue(thePath); fs._getFlexPluginScripts(); expect(resolveModulePath).toHaveBeenCalledTimes(1); expect(resolveModulePath).toHaveBeenCalledWith(flexPluginScripts); }); it('should throw exception if package not found', (done) => { jest.spyOn(fs, 'resolveModulePath').mockReturnValue(false); try { fs._getFlexPluginScripts(); } catch (e) { expect(e.message).toContain(`resolve ${flexPluginScripts}`); done(); } }); }); describe('_getFlexPluginWebpackPath', () => { it('should resolve path', () => { const thePath = 'the/path'; const theModule = 'the/module'; const resolveModulePath = jest.spyOn(fs, 'resolveModulePath').mockReturnValue(thePath); fs._getFlexPluginWebpackPath(theModule); expect(resolveModulePath).toHaveBeenCalledTimes(1); expect(resolveModulePath).toHaveBeenCalledWith(flexPluginWebpack, theModule); }); it('should throw exception if package not found', (done) => { jest.spyOn(fs, 'resolveModulePath').mockReturnValue(false); try { fs._getFlexPluginWebpackPath('path'); } catch (e) { expect(e.message).toContain(`resolve ${flexPluginWebpack}`); done(); } }); }); describe('getPaths', () => { const validPackage = { name: pluginName, version: '1.2.3', dependencies: { [flexPluginScripts]: '1', 'flex-plugin': '2', }, devDependencies: {}, }; it('should give cli paths', () => { const readPackageJson = jest.spyOn(fs, 'readPackageJson').mockReturnValue(validPackage); // cli/ directory expect(fs.getCliPaths().dir).toMatchPathContaining('/.twilio-cli'); expect(fs.getCliPaths().flexDir).toMatchPathContaining('/.twilio-cli/flex'); expect(fs.getCliPaths().pluginsJsonPath).toEqual(expect.stringMatching('plugins.json')); readPackageJson.mockRestore(); }); it('should throw exception if flexPluginScriptPath is not found', (done) => { jest.spyOn(fs, 'resolveModulePath').mockImplementation((pkg) => { if (pkg === flexPluginScripts) { return false; } return pkg; }); try { fs.getPaths(); } catch (e) { expect(e.message).toContain(`resolve ${flexPluginScripts}`); done(); } }); it('should throw exception if flexPluginWebpackPath is not found', (done) => { jest.spyOn(fs, 'resolveModulePath').mockImplementation((pkg) => { if (pkg === flexPluginWebpack) { return false; } return pkg; }); try { fs.getPaths(); } catch (e) { expect(e.message).toContain(`resolve ${flexPluginWebpack}`); done(); } }); it('should give you the paths', () => { const _getFlexPluginScripts = jest.spyOn(fs, '_getFlexPluginScripts').mockReturnValue(flexPluginScriptsPath); const _getFlexPluginWebpackPath = jest .spyOn(fs, '_getFlexPluginWebpackPath') .mockReturnValue(flexPluginWebpackPath); const readPackageJson = jest.spyOn(fs, 'readPackageJson').mockReturnValue(validPackage); const thePaths = fs.getPaths(); expect(_getFlexPluginScripts).toHaveBeenCalledTimes(1); expect(_getFlexPluginWebpackPath).toHaveBeenCalledTimes(1); // build/ directory expect(thePaths.app.buildDir).toEqual(expect.stringMatching('build$')); expect(thePaths.app.bundlePath).toContain('build'); expect(thePaths.app.bundlePath).toContain(validPackage.name); expect(thePaths.app.bundlePath).toEqual(expect.stringMatching('.js$')); expect(thePaths.app.sourceMapPath).toContain('build'); expect(thePaths.app.sourceMapPath).toContain(validPackage.name); expect(thePaths.app.sourceMapPath).toEqual(expect.stringMatching('.js.map$')); // cli/ directory expect(thePaths.cli.dir).toMatchPathContaining('/.twilio-cli'); expect(thePaths.cli.flexDir).toMatchPathContaining('/.twilio-cli/flex'); expect(thePaths.cli.pluginsJsonPath).toEqual(expect.stringMatching('plugins.json')); // src/ directory expect(thePaths.app.srcDir).toEqual(expect.stringMatching('src$')); expect(thePaths.app.entryPath).toContain('src'); expect(thePaths.app.entryPath).toEqual(expect.stringMatching('index$')); // node_modules/ directory expect(thePaths.app.nodeModulesDir).toEqual(expect.stringMatching('node_modules$')); expect(thePaths.app.flexUIDir).toContain('node_modules'); expect(thePaths.app.flexUIDir).toMatchPathContaining('@twilio/flex-ui'); expect(thePaths.app.flexUIPkgPath).toMatchPathContaining('@twilio/flex-ui'); expect(thePaths.app.flexUIPkgPath).toEqual(expect.stringMatching('package.json$')); // scripts expect(thePaths.scripts.devAssetsDir).toMatchPathContaining(flexPluginScriptsPath); // public/ directory expect(thePaths.app.publicDir).toEqual(expect.stringMatching('public$')); expect(thePaths.app.appConfig).toEqual(expect.stringMatching('appConfig.js$')); // env support expect(thePaths.app.envPath).toEqual(expect.stringMatching('.env')); expect(thePaths.app.envExamplePath).toEqual(expect.stringMatching('.env.example')); expect(thePaths.app.envDefaultsPath).toEqual(expect.stringMatching('.env.defaults')); // dependencies expect(thePaths.app.dependencies.react.version).toEqual('1.2.3'); expect(thePaths.app.dependencies.reactDom.version).toEqual('1.2.3'); expect(thePaths.app.dependencies.flexUI.version).toEqual('1.2.3'); // package.json expect(thePaths.app.name).toEqual(pluginName); expect(thePaths.app.version).toEqual('1.2.3'); // typescript expect(thePaths.app.tsConfigPath).toContain('tsconfig.json'); expect(thePaths.app.isTSProject()).toEqual(true); // setup tests expect(thePaths.app.setupTestsPaths).toHaveLength(2); expect(thePaths.app.setupTestsPaths[0]).toContain('setupTests.js'); expect(thePaths.app.setupTestsPaths[0]).not.toContain('src'); expect(thePaths.app.setupTestsPaths[1]).toContain('setupTests.js'); expect(thePaths.app.setupTestsPaths[1]).toContain('src'); // webpack expect(thePaths.webpack.dir).toContain(flexPluginWebpackPath); expect(thePaths.webpack.nodeModulesDir).toMatchPathContaining(flexPluginWebpackPath); expect(thePaths.webpack.nodeModulesDir).toContain('node_modules'); // others expect(thePaths.assetBaseUrlTemplate).toContain('plugin-test/%PLUGIN_VERSION%'); readPackageJson.mockRestore(); }); }); describe('setCoreCwd', () => { it('should set the core cwd', () => { const cwd = '/new/path'; const before = fs.getCoreCwd(); fs.setCoreCwd(cwd); const after = fs.getCoreCwd(); expect(after).toEqual(cwd); expect(before).not.toEqual(after); }); }); describe('setCwd', () => { it('should set the cwd', () => { const cwd = '/new/path'; const before = fs.getCwd(); fs.setCwd(cwd); const after = fs.getCwd(); expect(after).toEqual(cwd); expect(before).not.toEqual(after); }); }); describe('addCWDNodeModule', () => { it('should add path', () => { const addPath = jest.spyOn(appModule, 'addPath').mockReturnThis(); const setCoreCwd = jest.spyOn(fs, 'setCoreCwd').mockReturnThis(); fs.addCWDNodeModule(); expect(setCoreCwd).not.toHaveBeenCalled(); expect(addPath).toHaveBeenCalledTimes(1); expect(addPath).toHaveBeenCalledWith(expect.stringContaining('node_modules')); }); it('should add core-cwd', () => { const cwd = '/new/path'; jest.spyOn(appModule, 'addPath').mockReturnThis(); const setCoreCwd = jest.spyOn(fs, 'setCoreCwd').mockReturnThis(); fs.addCWDNodeModule('--core-cwd', cwd); expect(setCoreCwd).toHaveBeenCalledTimes(1); expect(setCoreCwd).toHaveBeenCalledWith(cwd); }); it('should not add core-cwd if not provided', () => { jest.spyOn(appModule, 'addPath').mockReturnThis(); const setCoreCwd = jest.spyOn(fs, 'setCoreCwd').mockReturnThis(); fs.addCWDNodeModule('--core-cwd'); expect(setCoreCwd).not.toHaveBeenCalled(); }); it('should add cwd', () => { const cwd = '/new/path'; jest.spyOn(appModule, 'addPath').mockReturnThis(); const setCwd = jest.spyOn(fs, 'setCwd').mockReturnThis(); fs.addCWDNodeModule('--cwd', cwd); expect(setCwd).toHaveBeenCalledTimes(1); expect(setCwd).toHaveBeenCalledWith(cwd); }); it('should not add cwd if not provided', () => { jest.spyOn(appModule, 'addPath').mockReturnThis(); const setCwd = jest.spyOn(fs, 'setCwd').mockReturnThis(); fs.addCWDNodeModule('--cwd'); expect(setCwd).not.toHaveBeenCalled(); }); }); describe('resolveModulePath', () => { it('should find path', () => { expect(fs.resolveModulePath('jest')).toContain('jest'); }); it('should not find path', () => { expect(fs.resolveModulePath('random-unknown-package')).toEqual(false); }); }); describe('findGlobs', () => { it('should return all globs', () => { const findGlobsIn = jest.spyOn(fs, 'findGlobsIn').mockReturnValue(['glob']); const getCwd = jest.spyOn(fs, 'getCwd').mockReturnValue('/the/cwd'); const result = fs.findGlobs('pattern1', 'pattern2'); expect(result).toEqual(['glob']); expect(getCwd).toHaveBeenCalledTimes(1); expect(findGlobsIn).toHaveBeenCalledTimes(1); expect(findGlobsIn).toHaveBeenCalledWith(expect.toMatchPathContaining('the/cwd/src'), 'pattern1', 'pattern2'); }); }); describe('isPluginDir', () => { it('should return true if @twilio/flex-ui is in the dependencies', () => { expect( fs.isPluginDir({ version: '1.0.0', name: '', dependencies: { '@twilio/flex-ui': '^1', }, devDependencies: {}, }), ).toBe(true); }); it('should return true if @twilio/flex-ui is in the devDependencies', () => { expect( fs.isPluginDir({ version: '1.0.0', name: '', dependencies: {}, devDependencies: { '@twilio/flex-ui': '^1', }, }), ).toBe(true); }); it('should return true if @twilio/flex-ui is not in dependencies or devDependencies', () => { expect( fs.isPluginDir({ version: '1.0.0', name: '', dependencies: {}, devDependencies: {}, }), ).toBe(false); }); }); describe('packageDependencyVersion', () => { const pkg: PackageJson = { name: 'test', version: '1.2.3', dependencies: {}, devDependencies: {}, }; it('should return version from dependency', () => { const testPkg = { ...pkg, ...{ dependencies: { test: '2.3.4' } } }; expect(fs.packageDependencyVersion(testPkg, 'test')).toEqual('2.3.4'); }); it('should return version from devDeps', () => { const testPkg = { ...pkg, ...{ devDependencies: { test: '3.4.5' } } }; expect(fs.packageDependencyVersion(testPkg, 'test')).toEqual('3.4.5'); }); it('should return version from peerDeps', () => { const testPkg = { ...pkg, ...{ peerDependencies: { test: '4.5.6' } } }; expect(fs.packageDependencyVersion(testPkg, 'test')).toEqual('4.5.6'); }); it('should return null if no package is found', () => { expect(fs.packageDependencyVersion(pkg, 'test')).toBeNull(); }); }); describe('flexUIPackageDependencyVersion', () => { it('should call packageDependencyVersion', () => { const packageDependencyVersion = jest.spyOn(fs, 'packageDependencyVersion'); const flexUIPkgPath = 'path/to/flex-ui'; const pkg = { name: 'test' }; // @ts-ignore jest.spyOn(fs, 'getPaths').mockReturnValue({ app: { flexUIPkgPath } }); const _require = jest.spyOn(fs, '_require').mockReturnValue(pkg); fs.flexUIPackageDependencyVersion('test'); expect(packageDependencyVersion).toHaveBeenCalledTimes(1); expect(packageDependencyVersion).toHaveBeenCalledWith(pkg, 'test'); expect(_require).toHaveBeenCalledWith(flexUIPkgPath); }); }); });
the_stack
import { window, TextEditor, TextDocument, Uri, workspace, WorkspaceEdit, Position, Range, Selection, QuickPickItem, QuickPickOptions, ViewColumn } from 'vscode'; import { readJSON } from 'fs-extra'; import * as path from 'path'; import { sessionDir, sessionDirectoryExists, writeResponse, writeSuccessResponse } from './session'; import { runTextInTerm, restartRTerminal, chooseTerminal } from './rTerminal'; import { config } from './util'; let lastActiveTextEditor: TextEditor; export async function dispatchRStudioAPICall(action: string, args: any, sd: string): Promise<void> { switch (action) { case 'active_editor_context': { await writeResponse(activeEditorContext(), sd); break; } case 'insert_or_modify_text': { await insertOrModifyText(args.query, args.id); await writeSuccessResponse(sd); break; } case 'replace_text_in_current_selection': { await replaceTextInCurrentSelection(args.text, args.id); await writeSuccessResponse(sd); break; } case 'show_dialog': { showDialog(args.message); await writeSuccessResponse(sd); break; } case 'navigate_to_file': { await navigateToFile(args.file, args.line, args.column); await writeSuccessResponse(sd); break; } case 'set_selection_ranges': { await setSelections(args.ranges, args.id); await writeSuccessResponse(sd); break; } case 'document_save': { await documentSave(args.id); await writeSuccessResponse(sd); break; } case 'document_save_all': { await documentSaveAll(); await writeSuccessResponse(sd); break; } case 'get_project_path': { await writeResponse(projectPath(), sd); break; } case 'document_context': { await writeResponse(await documentContext(args.id), sd); break; } case 'document_new': { await documentNew(args.text, args.type, args.position); await writeSuccessResponse(sd); break; } case 'restart_r': { await restartRTerminal(); await writeSuccessResponse(sd); break; } case 'send_to_console': { await sendCodeToRTerminal(args.code, args.execute, args.focus); await writeSuccessResponse(sd); break; } default: console.error(`[dispatchRStudioAPICall] Unsupported action: ${action}`); } } //rstudioapi export function activeEditorContext() { // info returned from RStudio: // list with: // id // path // contents // selection - a list of selections const currentDocument = getLastActiveTextEditor().document; return { id: currentDocument.uri, contents: currentDocument.getText(), path: currentDocument.fileName, selection: getLastActiveTextEditor().selections }; } export async function documentContext(id: string) { const target = findTargetUri(id); const targetDocument = await workspace.openTextDocument(target); console.info(`[documentContext] getting context for: ${target.path}`); return { id: targetDocument.uri }; } export async function insertOrModifyText(query: any[], id: string = null) { const target = findTargetUri(id); const targetDocument = await workspace.openTextDocument(target); console.info(`[insertTextAtPosition] inserting text into: ${target.path}`); const edit = new WorkspaceEdit(); query.forEach((op) => { assertSupportedEditOperation(op.operation); let editLocation: any; const editText = normaliseEditText(op.text, op.location, op.operation, targetDocument); if (op.operation === 'insertText') { editLocation = parsePosition(op.location, targetDocument); console.info(`[insertTextAtPosition] inserting at: ${JSON.stringify(editLocation)}`); console.info(`[insertTextAtPosition] inserting text: ${editText}`); edit.insert(target, editLocation, editText); } else { editLocation = parseRange(op.location, targetDocument); console.info(`[insertTextAtPosition] replacing at: ${JSON.stringify(editLocation)}`); console.info(`[insertTextAtPosition] replacing with text: ${editText}`); edit.replace(target, editLocation, editText); } }); void workspace.applyEdit(edit); } export async function replaceTextInCurrentSelection(text: string, id: string): Promise<void> { const target = findTargetUri(id); console.info(`[replaceTextInCurrentSelection] inserting: ${text} into ${target.path}`); const edit = new WorkspaceEdit(); edit.replace( target, getLastActiveTextEditor().selection, text ); await workspace.applyEdit(edit); } export function showDialog(message: string): void { void window.showInformationMessage(message); } export async function navigateToFile(file: string, line: number, column: number): Promise<void>{ const targetDocument = await workspace.openTextDocument(Uri.file(file)); const editor = await window.showTextDocument(targetDocument); const targetPosition = parsePosition([line, column], targetDocument); editor.selection = new Selection(targetPosition, targetPosition); editor.revealRange(new Range(targetPosition, targetPosition)); } export async function setSelections(ranges: number[][], id: string): Promise<void> { // Setting selections can only be done on TextEditors not TextDocuments, but // it is the latter which are the things actually referred to by `id`. In // VSCode it's not possible to get a list of the open text editors. it is not // window.visibleTextEditors - this is only editors (tabs) with text showing. // The only editors we know about are those that are visible and the last // active (which may not be visible if it was overtaken by a WebViewPanel). // This function looks to see if a text editor for the document id is amongst // those known, and if not, it opens and shows that document, but in a // texteditor 'beside' the current one. // The rationale for this is: // If an addin is trying to set selections in an editor that is not the active // one it is most likely that it was active before the addin ran, but the addin // opened a something that overtook its' focus. The most likely culprit for // this is a shiny app. In the case that the target window is visible // alongside the shiny app, it will be found and used. If it is not visible, // there's a change it may be the last active, if the shiny app over took it. // If it is neither of these things a new one needs to be opened to set // selections and the question is whether open it in the same window as the // shiny app, or the one 'beside'. 'beside' is preferred since it allows shiny // apps that work interactively with an open document to behave more smoothly. // {prefixer} is an example of one of these. const target = findTargetUri(id); const targetDocument = await workspace.openTextDocument(target); const editor = await reuseOrCreateEditor(targetDocument); const selectionObjects = ranges.map(x => { const newRange = parseRange(x, targetDocument); const newSelection = new Selection(newRange.start, newRange.end); return (newSelection); }); editor.selections = selectionObjects; } export async function documentSave(id: string): Promise<void> { const target = findTargetUri(id); const targetDocument = await workspace.openTextDocument(target); await targetDocument.save(); } export async function documentSaveAll(): Promise<void> { await workspace.saveAll(); } export function projectPath(): { path: string; } { if (typeof workspace.workspaceFolders !== 'undefined') { // Is there a root folder open? if (workspace.workspaceFolders.length === 1) { // In single root common case, this will always work. return { path: workspace.workspaceFolders[0].uri.path }; } else if (workspace.workspaceFolders.length > 1) { // In less common multi-root folder case is a bit tricky. If the active // text editor has scheme 'untitled:' (is unsaved), then // workspace.getWorkspaceFolder() won't be able to find its Uri in any // folder and will return undefined. const currentDocument = getLastActiveTextEditor().document; const currentDocFolder = workspace.getWorkspaceFolder(currentDocument.uri); if (typeof currentDocFolder !== 'undefined') { return { path: currentDocFolder.uri.path }; } } } // if we got to here either: // - the workspaceFolders array was undefined (no folder open) // - the activeText editor was an unsaved document, which has undefined workspace folder. // return undefined and handle with a message in R. return { path: undefined }; } export async function documentNew(text: string, type: string, position: number[]): Promise<void> { const documentUri = Uri.parse('untitled:' + path.join(projectPath().path, 'new_document.' + type)); const targetDocument = await workspace.openTextDocument(documentUri); const edit = new WorkspaceEdit(); const docLines = targetDocument.lineCount; edit.replace(documentUri, targetDocument.validateRange(new Range( new Position(0, 0), new Position(docLines + 1, 0) )), text); void workspace.applyEdit(edit).then(async () => { const editor = await window.showTextDocument(targetDocument); editor.selections = [new Selection( parsePosition(position, targetDocument), parsePosition(position, targetDocument) )]; }); } // interface // represents addins in a QuickPick menu interface AddinItem extends QuickPickItem { binding: string; package: string; } let addinQuickPicks: AddinItem[] = undefined; export async function getAddinPickerItems(): Promise<AddinItem[]> { if (typeof addinQuickPicks === 'undefined') { const addins: any[] = await readJSON(path.join(sessionDir, 'addins.json')). then( (result) => result, () => { throw ('Could not find list of installed addins.' + ' options(vsc.rstudioapi = TRUE) must be set in your .Rprofile to use ' + ' RStudio Addins'); } ); const addinItems = addins.map((x) => { return { alwaysShow: false, description: `{${x.package}}`, label: x.name, detail: x.description, picked: false, binding: x.binding, package: x.package, }; }); addinQuickPicks = addinItems; } return addinQuickPicks; } export function purgeAddinPickerItems(): void { addinQuickPicks = undefined; } export async function launchAddinPicker(): Promise<void> { if (!config().get<boolean>('sessionWatcher')) { void window.showErrorMessage('{rstudioapi} emulation requires session watcher to be enabled in extension config.'); return; } if (!sessionDirectoryExists()) { void window.showErrorMessage('No active R terminal session, attach one to use RStudio addins.'); return; } const addinPickerOptions: QuickPickOptions = { matchOnDescription: true, matchOnDetail: true, canPickMany: false, ignoreFocusOut: false, placeHolder: '', onDidSelectItem: undefined }; const addinSelection: AddinItem = await window.showQuickPick<AddinItem>(getAddinPickerItems(), addinPickerOptions); if (!(typeof addinSelection === 'undefined')) { await runTextInTerm(addinSelection.package + ':::' + addinSelection.binding + '()'); } } export async function sendCodeToRTerminal(code: string, execute: boolean, focus: boolean) { if (execute) { console.info(`[sendCodeToRTerminal] sending code: ${code}`); } else { console.info(`[sendCodeToRTerminal] inserting code: ${code}`); } await runTextInTerm(code, execute); if (focus) { const rTerm = await chooseTerminal(); if (rTerm !== undefined) { rTerm.show(); } } } //utils function toVSCCoord(coord: any) { // this is necessary because RStudio will accept negative or infinite values, // replacing them with the min or max or the document. // These must be clamped non-negative integers accepted by VSCode. // For Inf, we set the value to a very large integer, relying on the // parsing functions to revise this down using the validatePosition/Range functions. let coord_value: number; if (coord === 'Inf') { coord_value = 10000000; } else if (coord === '-Inf') { coord_value = 0; } else if (coord <= 0) { coord_value = 0; } else { // coord > 0 coord_value = coord - 1; // positions in the rstudioapi are 1 indexed. } return coord_value; } function parsePosition(rs_position: any[], targetDocument: TextDocument) { if (rs_position.length !== 2) { throw ('an rstudioapi position must be an array of 2 numbers'); } return ( targetDocument.validatePosition( new Position(toVSCCoord(rs_position[0]), toVSCCoord(rs_position[1])) )); } function parseRange(rs_range: any, targetDocument: TextDocument) { if (rs_range.start.length !== 2 || rs_range.end.length !== 2) { throw ('an rstudioapi range must be an object containing two numeric arrays'); } return ( targetDocument.validateRange( new Range( new Position(toVSCCoord(rs_range.start[0]), toVSCCoord(rs_range.start[1])), new Position(toVSCCoord(rs_range.end[0]), toVSCCoord(rs_range.end[1])) ) )); } function assertSupportedEditOperation(operation: string) { if (operation !== 'insertText' && operation !== 'modifyRange') { throw ('Operation: ' + operation + ' not supported by VSCode-R API'); } } function normaliseEditText(text: string, editLocation: any, operation: string, targetDocument: TextDocument) { // in a document with lines, does the line position extend past the existing // lines in the document? rstudioapi adds a newline in this case, so must we. // n_lines is a count, line is 0 indexed position hence + 1 const editStartLine = operation === 'insertText' ? editLocation[0] : editLocation.start[0]; if (editStartLine === 'Inf' || (editStartLine + 1 > targetDocument.lineCount && targetDocument.lineCount > 0)) { return (text + '\n'); } else { return text; } } // window.onActiveTextEditorDidChange handler export function trackLastActiveTextEditor(editor?: TextEditor): void { if (typeof editor !== 'undefined') { lastActiveTextEditor = editor; } } function getLastActiveTextEditor() { return (typeof window.activeTextEditor === 'undefined' ? lastActiveTextEditor : window.activeTextEditor); } function findTargetUri(id: string) { return (id === null ? getLastActiveTextEditor().document.uri : Uri.parse(id)); } async function reuseOrCreateEditor(targetDocument: TextDocument) { // if there's a known text editor for a Uri, use it. if not, open a new one // 'beside' the current one. We know about the last active, and all visible. // Sometimes the last active is not visible in the case it was overtaken by a // WebViewPanel. const KnownEditors: TextEditor[] = []; KnownEditors.push(lastActiveTextEditor); KnownEditors.push(...window.visibleTextEditors); const matchingTextEditors = KnownEditors.filter((editor) => editor.document.uri.toString() === targetDocument.uri.toString()); if (matchingTextEditors.length === 0) { const newEditor = await window.showTextDocument( targetDocument, ViewColumn.Beside ); return (newEditor); } else { return (matchingTextEditors[0]); } }
the_stack
import { jestConsoleContext, jestContext } from '@prisma/sdk' import execa from 'execa' import fs from 'fs-jetpack' import { DbSeed } from '../commands/DbSeed' // TODO: Windows: snapshot tests fail on Windows because of emoji. const describeIf = (condition: boolean) => (condition ? describe : describe.skip) const ctx = jestContext.new().add(jestConsoleContext()).assemble() describeIf(process.platform !== 'win32')('seed', () => { it('seed.js', async () => { ctx.fixture('seed-sqlite-js') const result = DbSeed.new().parse([]) await expect(result).resolves.toMatchInlineSnapshot(` 🌱 The seed command has been executed. `) expect(ctx.mocked['console.info'].mock.calls.join('\n')).toMatchInlineSnapshot( `Running seed command \`node prisma/seed.js\` ...`, ) expect(ctx.mocked['console.log'].mock.calls.join('\n')).toMatchInlineSnapshot(``) expect(ctx.mocked['console.error'].mock.calls.join('\n')).toMatchInlineSnapshot(``) }) it('one broken seed.js file', async () => { const mockExit = jest.spyOn(process, 'exit').mockImplementation() ctx.fixture('seed-sqlite-js') fs.write('prisma/seed.js', 'BROKEN_CODE_SHOULD_ERROR;') const result = DbSeed.new().parse([]) await expect(result).resolves.toMatchInlineSnapshot(``) expect(ctx.mocked['console.info'].mock.calls.join('\n')).toMatchInlineSnapshot( `Running seed command \`node prisma/seed.js\` ...`, ) expect(ctx.mocked['console.error'].mock.calls.join()).toContain('An error occured while running the seed command:') expect(mockExit).toBeCalledWith(1) }) it('seed.ts', async () => { ctx.fixture('seed-sqlite-ts') const result = DbSeed.new().parse([]) await expect(result).resolves.toMatchInlineSnapshot(` 🌱 The seed command has been executed. `) expect(ctx.mocked['console.info'].mock.calls.join('\n')).toMatchInlineSnapshot( `Running seed command \`ts-node prisma/seed.ts\` ...`, ) expect(ctx.mocked['console.error'].mock.calls.join('\n')).toMatchInlineSnapshot(``) }, 10_000) it('seed.ts - ESM', async () => { ctx.fixture('seed-sqlite-ts-esm') // Needs ts-node to be installed await execa.command('npm i') const result = DbSeed.new().parse([]) await expect(result).resolves.toMatchInlineSnapshot(` 🌱 The seed command has been executed. `) expect(ctx.mocked['console.info'].mock.calls.join('\n')).toMatchInlineSnapshot( `Running seed command \`node --loader ts-node/esm prisma/seed.ts\` ...`, ) expect(ctx.mocked['console.error'].mock.calls.join('\n')).toMatchInlineSnapshot(``) // "high" number since npm install can sometimes be slow }, 30_000) it('seed.sh', async () => { ctx.fixture('seed-sqlite-sh') const result = DbSeed.new().parse([]) await expect(result).resolves.toMatchInlineSnapshot(` 🌱 The seed command has been executed. `) expect(ctx.mocked['console.info'].mock.calls.join('\n')).toMatchInlineSnapshot( `Running seed command \`./prisma/seed.sh\` ...`, ) expect(ctx.mocked['console.error'].mock.calls.join('\n')).toMatchInlineSnapshot(``) }) }) describeIf(process.platform !== 'win32')('seed - legacy', () => { it('no seed file', async () => { ctx.fixture('seed-sqlite-legacy') ctx.fs.remove('prisma/seed.js') ctx.fs.remove('prisma/seed.ts') ctx.fs.remove('prisma/seed.sh') try { await DbSeed.new().parse([]) } catch (e) { expect(e).toMatchInlineSnapshot(` To configure seeding in your project you need to add a "prisma.seed" property in your package.json with the command to execute it: 1. Open the package.json of your project 2. Add one of the following examples to your package.json: TypeScript: \`\`\` "prisma": { "seed": "ts-node ./prisma/seed.ts" } \`\`\` If you are using ESM (ECMAScript modules): \`\`\` "prisma": { "seed": "node --loader ts-node/esm ./prisma/seed.ts" } \`\`\` And install the required dependencies by running: npm i -D ts-node typescript @types/node JavaScript: \`\`\` "prisma": { "seed": "node ./prisma/seed.js" } \`\`\` Bash: \`\`\` "prisma": { "seed": "./prisma/seed.sh" } \`\`\` And run \`chmod +x prisma/seed.sh\` to make it executable. More information in our documentation: https://pris.ly/d/seeding `) } expect(ctx.mocked['console.info'].mock.calls.join('\n')).toMatchInlineSnapshot(``) expect(ctx.mocked['console.error'].mock.calls.join('\n')).toMatchInlineSnapshot(``) }) it('more than one seed file', async () => { ctx.fixture('seed-sqlite-legacy') const result = DbSeed.new().parse([]) await expect(result).rejects.toThrowErrorMatchingInlineSnapshot(` To configure seeding in your project you need to add a "prisma.seed" property in your package.json with the command to execute it: 1. Open the package.json of your project 2. Add the following example to it: \`\`\` "prisma": { "seed": "node prisma/seed.js" } \`\`\` More information in our documentation: https://pris.ly/d/seeding `) expect(ctx.mocked['console.info'].mock.calls.join('\n')).toMatchInlineSnapshot(``) expect(ctx.mocked['console.error'].mock.calls.join('\n')).toMatchInlineSnapshot(``) }) it('deprecation of --preview-feature flag', async () => { ctx.fixture('seed-sqlite-js') const result = DbSeed.new().parse(['--preview-feature']) await expect(result).resolves.toMatchInlineSnapshot(` 🌱 The seed command has been executed. `) expect(ctx.mocked['console.info'].mock.calls.join('\n')).toMatchInlineSnapshot( `Running seed command \`node prisma/seed.js\` ...`, ) expect(ctx.mocked['console.warn'].mock.calls.join('\n')).toMatchInlineSnapshot(` prisma:warn Prisma "db seed" was in Preview and is now Generally Available. You can now remove the --preview-feature flag. `) expect(ctx.mocked['console.error'].mock.calls.join('\n')).toMatchInlineSnapshot(``) }) // legacy flag should warn it('using --schema should warn', async () => { ctx.fixture('seed-sqlite-js') const result = DbSeed.new().parse(['--schema=./some-folder/schema.prisma']) await expect(result).resolves.toMatchInlineSnapshot(` 🌱 The seed command has been executed. `) expect(ctx.mocked['console.info'].mock.calls.join('\n')).toMatchInlineSnapshot( `Running seed command \`node prisma/seed.js\` ...`, ) expect(ctx.mocked['console.warn'].mock.calls.join('\n')).toMatchInlineSnapshot( `prisma:warn The "--schema" parameter is not used anymore by "prisma db seed" since version 3.0 and can now be removed.`, ) expect(ctx.mocked['console.error'].mock.calls.join('\n')).toMatchInlineSnapshot(``) }) it('custom --schema from package.json should enrich help setup', async () => { ctx.fixture('seed-sqlite-legacy-schema-from-package-json') const result = DbSeed.new().parse([]) await expect(result).rejects.toMatchInlineSnapshot(` To configure seeding in your project you need to add a "prisma.seed" property in your package.json with the command to execute it: 1. Open the package.json of your project 2. Add the following example to it: \`\`\` "prisma": { "seed": "node custom-folder/seed.js" } \`\`\` More information in our documentation: https://pris.ly/d/seeding `) expect(ctx.mocked['console.info'].mock.calls.join('\n')).toMatchInlineSnapshot(``) expect(ctx.mocked['console.error'].mock.calls.join('\n')).toMatchInlineSnapshot(``) }) it('custom ts-node should warn', async () => { ctx.fixture('seed-sqlite-legacy-custom-ts-node') const result = DbSeed.new().parse([]) await expect(result).rejects.toMatchInlineSnapshot(` To configure seeding in your project you need to add a "prisma.seed" property in your package.json with the command to execute it: 1. Open the package.json of your project 2. Add the following example to it: \`\`\` "prisma": { "seed": "ts-node prisma/seed.ts" } \`\`\` If you are using ESM (ECMAScript modules): \`\`\` "prisma": { "seed": "node --loader ts-node/esm prisma/seed.ts" } \`\`\` 3. Install the required dependencies by running: npm i -D ts-node typescript @types/node More information in our documentation: https://pris.ly/d/seeding `) expect(ctx.mocked['console.info'].mock.calls.join('\n')).toMatchInlineSnapshot(``) expect(ctx.mocked['console.warn'].mock.calls.join('\n')).toMatchInlineSnapshot( `prisma:warn The "ts-node" script in the package.json is not used anymore since version 3.0 and can now be removed.`, ) expect(ctx.mocked['console.error'].mock.calls.join()).toMatchInlineSnapshot(``) }) })
the_stack
import dox from 'dox'; import path from 'path'; import { ObjectTypeComposer, EnumTypeComposer } from 'graphql-compose'; import ElasticApiParser from '../ElasticApiParser'; const apiPartialPath = path.resolve(__dirname, '../__mocks__/apiPartial.js'); describe('ElasticApiParser', () => { let parser: ElasticApiParser; beforeEach(() => { parser = new ElasticApiParser({ elasticApiFilePath: apiPartialPath, }); }); describe('static methods', () => { describe('loadApiFile()', () => { it('should load file with data', () => { expect(ElasticApiParser.loadApiFile(apiPartialPath)).toContain('api.search = ca({'); }); it('should replace invalid markup', () => { expect(ElasticApiParser.loadApiFile(apiPartialPath)).not.toContain( '@param {<<api-param-type-string,`String`>>} params.analyzer - The analyzer to use for the query string' ); expect(ElasticApiParser.loadApiFile(apiPartialPath)).toContain( '@param {String} params.analyzer - The analyzer to use for the query string' ); }); }); describe('findApiVersionFile()', () => { it('should find proper version in elasticsearch 12.x', () => { const { loadApiListFile } = ElasticApiParser; // $FlowFixMe ElasticApiParser.loadApiListFile = () => ` module.exports = { '_default': require('./5_0'), '5.0': require('./5_0'), '2.4': require('./2_4'), '2.1': require('./2_1'), '1.7': require('./1_7'), '0.90': require('./0_90'), '5.x': require('./5_x'), 'master': require('./master') }; `; expect(ElasticApiParser.findApiVersionFile('5.0')).toMatch( 'elasticsearch/src/lib/apis/5_0.js' ); expect(ElasticApiParser.findApiVersionFile('2.4')).toMatch( 'elasticsearch/src/lib/apis/2_4.js' ); expect(ElasticApiParser.findApiVersionFile('1.7')).toMatch( 'elasticsearch/src/lib/apis/1_7.js' ); expect(ElasticApiParser.findApiVersionFile('_default')).toMatch( 'elasticsearch/src/lib/apis/5_0.js' ); // $FlowFixMe ElasticApiParser.loadApiListFile = loadApiListFile; }); it('should find proper version in elasticsearch 13.x', () => { const { loadApiListFile } = ElasticApiParser; // $FlowFixMe ElasticApiParser.loadApiListFile = () => ` module.exports = { get '_default'() { return require('./5_3'); }, get '5.3'() { return require('./5_3'); }, get '5.2'() { return require('./5_2'); }, get '5.1'() { return require('./5_1'); }, get '5.0'() { return require('./5_0'); }, get '2.4'() { return require('./2_4'); }, get '1.7'() { return require('./1_7'); }, get '0.90'() { return require('./0_90'); }, get '5.x'() { return require('./5_x'); }, get 'master'() { return require('./master'); }, }; `; expect(ElasticApiParser.findApiVersionFile('5.0')).toMatch( 'elasticsearch/src/lib/apis/5_0.js' ); expect(ElasticApiParser.findApiVersionFile('2.4')).toMatch( 'elasticsearch/src/lib/apis/2_4.js' ); expect(ElasticApiParser.findApiVersionFile('1.7')).toMatch( 'elasticsearch/src/lib/apis/1_7.js' ); expect(ElasticApiParser.findApiVersionFile('_default')).toMatch( 'elasticsearch/src/lib/apis/5_3.js' ); // $FlowFixMe ElasticApiParser.loadApiListFile = loadApiListFile; }); }); describe('cleanupDescription()', () => { it('should remove `- ` from start and trim', () => { expect(ElasticApiParser.cleanupDescription('- Some param ')).toEqual('Some param'); }); }); describe('cleanupParamName()', () => { it('should remove `params.` from start', () => { expect(ElasticApiParser.cleanupParamName('params.q')).toEqual('q'); }); }); describe('cleanUpSource()', () => { it('should {<<api-param-type-boolean,`Boolean`>>} convert to {Boolean}', () => { expect( ElasticApiParser.cleanUpSource( `@param {<<api-param-type-boolean,\`Boolean\`>>} params.analyzeWildcard` ) ).toEqual(`@param {Boolean} params.analyzeWildcard`); }); it("should api['delete'] convert to api.delete", () => { expect(ElasticApiParser.cleanUpSource(`api.indices.prototype['delete'] = ca({`)).toEqual( `api.indices.prototype.delete = ca({` ); }); }); describe('parseParamsDescription()', () => { it('should return descriptions for fields', () => { const source = ElasticApiParser.cleanUpSource( ` /** * Perform a [updateByQuery](https://www.elastic.co/guide/en/elasticsearch/reference/5.x/docs-update-by-query.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {<<api-param-type-string,\`String\`>>} params.analyzer - The analyzer to use for the query string * @param {<<api-param-type-boolean,\`Boolean\`>>} params.analyzeWildcard - Specify whether wildcard and prefix queries should be analyzed (default: false) * @param {<<api-param-type-number,\`Number\`>>} params.from - Starting offset (default: 0) */ api.updateByQuery = ca({}); ` ); const doxAST = dox.parseComments(source, { raw: true }); expect(ElasticApiParser.parseParamsDescription(doxAST[0])).toMatchObject({ analyzeWildcard: 'Specify whether wildcard and prefix queries should be analyzed (default: false)', analyzer: 'The analyzer to use for the query string', from: 'Starting offset (default: 0)', }); }); }); describe('codeToSettings()', () => { it('should return settings as object from ca({ settings })', () => { expect( ElasticApiParser.codeToSettings( ` api.cat.prototype.allocation = ca({ params: { format: { type: 'string' }, bytes: { type: 'enum', options: ['b', 'k', 'kb'] }, local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/allocation/<%=nodeId%>', req: { nodeId: { type: 'list' }} }, { fmt: '/_cat/allocation' }, { fmt: '/<%=index%>/<%=type%>/_update_by_query', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_update_by_query', req: { index: { type: 'list' } } } ] });` ) ).toMatchObject({ params: { bytes: { options: ['b', 'k', 'kb'], type: 'enum' }, format: { type: 'string' }, h: { type: 'list' }, help: { default: false, type: 'boolean' }, local: { type: 'boolean' }, masterTimeout: { name: 'master_timeout', type: 'time' }, v: { default: false, type: 'boolean' }, }, urls: [ { fmt: '/_cat/allocation/<%=nodeId%>', req: { nodeId: { type: 'list' } }, }, { fmt: '/_cat/allocation' }, { fmt: '/<%=index%>/<%=type%>/_update_by_query', req: { index: { type: 'list' }, type: { type: 'list' }, }, }, { fmt: '/<%=index%>/_update_by_query', req: { index: { type: 'list' } }, }, ], }); }); }); describe('getMethodName()', () => { it('should return string', () => { expect(ElasticApiParser.getMethodName('api.updateByQuery')).toEqual('updateByQuery'); }); it('should return array of string', () => { expect(ElasticApiParser.getMethodName('api.cat.prototype.allocation')).toEqual([ 'cat', 'allocation', ]); }); }); describe('parseSource()', () => { it('should throw error if empty source', () => { expect(() => { ElasticApiParser.parseSource(''); }).toThrowError('Empty source'); expect(() => { ElasticApiParser.parseSource(123 as any); }).toThrowError('should be non-empty string'); }); it('should return ElasticParsedSourceT', () => { expect( ElasticApiParser.parseSource(ElasticApiParser.loadApiFile(apiPartialPath)) ).toMatchSnapshot(); }); }); }); describe('paramTypeToGraphQL()', () => { it('should convert scalar types', () => { expect(parser.paramTypeToGraphQL({ type: 'string' }, 'f1')).toEqual('String'); expect(parser.paramTypeToGraphQL({ type: 'boolean' }, 'f1')).toEqual('Boolean'); expect(parser.paramTypeToGraphQL({ type: 'number' }, 'f1')).toEqual('Float'); expect(parser.paramTypeToGraphQL({ type: 'time' }, 'f1')).toEqual('String'); }); it('should `list` convert to JSON', () => { expect(parser.paramTypeToGraphQL({ type: 'list' }, 'f1')).toEqual('JSON'); }); it('should `enum` convert to String (if empty options)', () => { expect(parser.paramTypeToGraphQL({ type: 'enum' }, 'f1')).toEqual('String'); }); it('should `enum` convert to EnumTypeComposer', () => { const type = parser.paramTypeToGraphQL({ type: 'enum', options: ['AND', 'OR'] }, 'f1'); expect(type).toBeInstanceOf(EnumTypeComposer); }); it('should as fallback type return JSON', () => { expect(parser.paramTypeToGraphQL({ type: 'crazy' }, 'f1')).toEqual('JSON'); }); }); describe('getEnumType()', () => { it('should convert to EnumTypeComposer', () => { const etc = parser.getEnumType('f1', ['AND', 'OR']); expect(etc).toBeInstanceOf(EnumTypeComposer); expect(etc.getField('AND')).toMatchObject({ value: 'AND' }); expect(etc.getField('OR')).toMatchObject({ value: 'OR' }); }); it("should convert '' to empty_string", () => { const etc = parser.getEnumType('f1', ['']); expect(etc).toBeInstanceOf(EnumTypeComposer); expect(etc.getField('empty_string')).toMatchObject({ value: '', }); }); it('should convert `true` to `true_value` (same for `false`)', () => { // This is fix for https://github.com/graphql/graphql-js/pull/812 // Which throw error on `true`, `false` and `null`. // But we allow to use this values, just renaming it. const etc = parser.getEnumType('f1', ['true', true, 'false', false]); expect(etc).toBeInstanceOf(EnumTypeComposer); expect(etc.getField('true_string')).toMatchObject({ value: 'true', }); expect(etc.getField('true_boolean')).toMatchObject({ value: true, }); expect(etc.getField('false_string')).toMatchObject({ value: 'false', }); expect(etc.getField('false_boolean')).toMatchObject({ value: false, }); }); it('should convert 1 to number_1', () => { const etc = parser.getEnumType('f1', [1]); expect(etc).toBeInstanceOf(EnumTypeComposer); expect(etc.getField('number_1')).toMatchObject({ value: 1 }); }); it('should provide name started with ElasticEnum', () => { const etc = parser.getEnumType('f1', ['']); expect(etc.getTypeName()).toMatch(/^ElasticEnum/); }); it('should reuse generated Enums', () => { const type = parser.getEnumType('f1', ['']); const type2 = parser.getEnumType('f1', ['']); const type3 = parser.getEnumType('f2', ['']); expect(type).toBe(type2); expect(type).not.toBe(type3); }); it('should generated different name for Enums', () => { const etc = parser.getEnumType('f1', ['a', 'b']); const etc2 = parser.getEnumType('f1', ['c', 'd']); expect(etc).not.toBe(etc2); expect(etc.getTypeName()).toMatch(/F1$/); expect(etc2.getTypeName()).toMatch(/F1_1$/); }); }); describe('paramToGraphQLArgConfig()', () => { it('should return object with type property', () => { expect(parser.paramToGraphQLArgConfig({ type: 'string' }, 'f1')).toMatchObject({ type: 'String', }); }); it('should return object with defaultValue property', () => { expect( parser.paramToGraphQLArgConfig({ type: 'string', default: 'ABC' }, 'f1') ).toMatchObject({ type: 'String', defaultValue: 'ABC', }); }); it('should set defaultValue="json" for `format` argument', () => { expect(parser.paramToGraphQLArgConfig({ type: 'string' }, 'format')).toMatchObject({ type: 'String', defaultValue: 'json', }); }); it('should ignore non-numeric default for float', () => { expect( parser.paramToGraphQLArgConfig({ type: 'number', default: 'ABC' }, 'someField') ).not.toHaveProperty('defaultValue'); }); it('should accept numeric default for float', () => { expect( parser.paramToGraphQLArgConfig({ type: 'number', default: '4.2' }, 'someField') ).toHaveProperty('defaultValue', 4.2); }); }); describe('settingsToArgMap()', () => { it('should create body arg if POST or PUT method', () => { const args: any = parser.settingsToArgMap({ params: {}, method: 'POST', }); expect(args).toMatchObject({ body: {} }); expect(args.body.type).toEqual('JSON'); }); it('should create required body arg if POST or PUT method', () => { const args: any = parser.settingsToArgMap({ params: {}, method: 'POST', needBody: true, }); expect(args).toMatchObject({ body: {} }); expect(args.body.type).toBe('JSON!'); }); it('should traverse params', () => { expect( parser.settingsToArgMap({ params: { q: { type: 'string', }, format: { type: 'string' }, }, urls: [], }) ).toMatchObject({ format: {}, q: {} }); }); it('should traverse urls[].req params', () => { expect( parser.settingsToArgMap({ params: {}, urls: [ { fmt: '/_cat/allocation/<%=nodeId%>', req: { nodeId: { type: 'list' } }, }, { fmt: '/<%=index%>/_update_by_query', req: { index: { type: 'list', }, }, }, ], }) ).toMatchObject({ nodeId: {}, index: {} }); }); it('should traverse url.req params', () => { expect( parser.settingsToArgMap({ params: {}, url: { fmt: '/_cat/allocation/<%=nodeId%>', req: { nodeId: { type: 'list' } }, }, }) ).toMatchObject({ nodeId: {} }); }); }); describe('reassembleNestedFields()', () => { it('should pass single fields', () => { expect( parser.reassembleNestedFields({ field1: { type: 'String' }, field2: { type: 'String' }, }) ).toMatchObject({ field1: { type: 'String' }, field2: { type: 'String' }, }); }); it('should combine nested field in GraphQLObjectType', () => { const reFields: any = parser.reassembleNestedFields({ 'cat.field1': { type: 'String' }, 'cat.field2': { type: 'String' }, 'index.exists': { type: 'Boolean' }, }); expect(Object.keys(reFields).length).toEqual(2); expect(reFields.cat).toBeDefined(); expect(reFields.cat.type).toBeInstanceOf(ObjectTypeComposer); const tc = reFields.cat.type; expect(tc.getFieldNames()).toEqual(['field1', 'field2']); expect(tc.getFieldTC('field1').getTypeName()).toEqual('String'); expect(tc.getFieldTC('field2').getTypeName()).toEqual('String'); expect(reFields.index).toBeDefined(); expect(reFields.index.type).toBeInstanceOf(ObjectTypeComposer); const tc2 = reFields.index.type; expect(tc2.getFieldNames()).toEqual(['exists']); expect(tc2.getFieldTC('exists').getTypeName()).toEqual('Boolean'); }); }); describe('generateFieldConfig()', () => { it('should throw error if provided empty method name', () => { expect(() => { parser.generateFieldConfig(undefined as any); }).toThrowError('provide Elastic search method'); }); it('should throw error if requested method does not exist', () => { expect(() => { parser.generateFieldConfig('missing.method'); }).toThrowError('does not exists'); }); it('should generate fieldConfig', () => { const partialApiParser = new ElasticApiParser({ elasticApiFilePath: apiPartialPath, }); expect(partialApiParser.generateFieldConfig('search')).toMatchSnapshot(); expect(partialApiParser.generateFieldConfig('cat.allocation')).toMatchSnapshot(); }); }); describe('generateFieldMap()', () => { it('should generate fieldMap', () => { const partialApiParser = new ElasticApiParser({ elasticApiFilePath: apiPartialPath, }); expect(partialApiParser.generateFieldMap()).toMatchSnapshot(); }); }); });
the_stack
import { blockchainTests, constants, expect, verifyEventsFromLogs } from '@0x/contracts-test-utils'; import { AuthorizableRevertErrors } from '@0x/contracts-utils'; import { BigNumber, StakingRevertErrors } from '@0x/utils'; import * as _ from 'lodash'; import { artifacts } from '../artifacts'; import { StakingProxyEvents, TestProxyDestinationContract, TestProxyDestinationEvents, TestStakingProxyUnitContract, } from '../wrappers'; import { constants as stakingConstants } from '../../src/constants'; blockchainTests.resets('StakingProxy unit tests', env => { const testString = 'Hello, World!'; const testRevertString = 'Goodbye, World!'; let accounts: string[]; let owner: string; let authorizedAddress: string; let notAuthorizedAddresses: string[]; let testProxyContract: TestStakingProxyUnitContract; let testContractViaProxy: TestProxyDestinationContract; let testContract: TestProxyDestinationContract; let testContract2: TestProxyDestinationContract; before(async () => { // Create accounts accounts = await env.getAccountAddressesAsync(); [owner, authorizedAddress, ...notAuthorizedAddresses] = accounts; // Deploy contracts testContract = await TestProxyDestinationContract.deployFrom0xArtifactAsync( artifacts.TestProxyDestination, env.provider, env.txDefaults, artifacts, ); testContract2 = await TestProxyDestinationContract.deployFrom0xArtifactAsync( artifacts.TestProxyDestination, env.provider, env.txDefaults, artifacts, ); testProxyContract = await TestStakingProxyUnitContract.deployFrom0xArtifactAsync( artifacts.TestStakingProxyUnit, env.provider, env.txDefaults, artifacts, testContract.address, ); const logDecoderDependencies = _.mapValues(artifacts, v => v.compilerOutput.abi); testContractViaProxy = new TestProxyDestinationContract( testProxyContract.address, env.provider, env.txDefaults, logDecoderDependencies, ); // Add authorized address to Staking Proxy await testProxyContract.addAuthorizedAddress(authorizedAddress).sendTransactionAsync({ from: owner }); }); describe('Fallback function', () => { it('should pass back the return value of the destination contract', async () => { const returnValue = await testContractViaProxy.echo(testString).callAsync(); expect(returnValue).to.equal(testString); }); it('should revert with correct value when destination reverts', async () => { return expect(testContractViaProxy.die().callAsync()).to.revertWith(testRevertString); }); it('should revert if no staking contract is attached', async () => { await testProxyContract.detachStakingContract().awaitTransactionSuccessAsync({ from: authorizedAddress }); const expectedError = new StakingRevertErrors.ProxyDestinationCannotBeNilError(); const tx = testContractViaProxy.echo(testString).callAsync(); return expect(tx).to.revertWith(expectedError); }); }); describe('attachStakingContract', () => { it('should successfully attaching a new staking contract', async () => { // Cache existing staking contract and attach a new one const initStakingContractAddress = await testProxyContract.stakingContract().callAsync(); const txReceipt = await testProxyContract .attachStakingContract(testContract2.address) .awaitTransactionSuccessAsync({ from: authorizedAddress }); // Validate `ContractAttachedToProxy` event verifyEventsFromLogs( txReceipt.logs, [ { newStakingContractAddress: testContract2.address, }, ], StakingProxyEvents.StakingContractAttachedToProxy, ); // Check that `init` was called on destination contract verifyEventsFromLogs( txReceipt.logs, [ { initCalled: true, }, ], TestProxyDestinationEvents.InitCalled, ); // Validate new staking contract address const finalStakingContractAddress = await testProxyContract.stakingContract().callAsync(); expect(finalStakingContractAddress).to.be.equal(testContract2.address); expect(finalStakingContractAddress).to.not.equal(initStakingContractAddress); }); it('should revert if call to `init` on new staking contract fails', async () => { await testProxyContract.setInitFailFlag().awaitTransactionSuccessAsync(); const tx = testProxyContract.attachStakingContract(testContract2.address).awaitTransactionSuccessAsync({ from: authorizedAddress, }); const expectedError = 'INIT_FAIL_FLAG_SET'; return expect(tx).to.revertWith(expectedError); }); it('should revert if called by unauthorized address', async () => { const tx = testProxyContract.attachStakingContract(testContract2.address).awaitTransactionSuccessAsync({ from: notAuthorizedAddresses[0], }); const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(notAuthorizedAddresses[0]); return expect(tx).to.revertWith(expectedError); }); }); describe('detachStakingContract', () => { it('should detach staking contract', async () => { // Cache existing staking contract and attach a new one const initStakingContractAddress = await testProxyContract.stakingContract().callAsync(); const txReceipt = await testProxyContract.detachStakingContract().awaitTransactionSuccessAsync({ from: authorizedAddress, }); // Validate that event was emitted verifyEventsFromLogs(txReceipt.logs, [{}], StakingProxyEvents.StakingContractDetachedFromProxy); // Validate staking contract address was unset const finalStakingContractAddress = await testProxyContract.stakingContract().callAsync(); expect(finalStakingContractAddress).to.be.equal(stakingConstants.NIL_ADDRESS); expect(finalStakingContractAddress).to.not.equal(initStakingContractAddress); }); it('should revert if called by unauthorized address', async () => { const tx = testProxyContract.detachStakingContract().awaitTransactionSuccessAsync({ from: notAuthorizedAddresses[0], }); const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(notAuthorizedAddresses[0]); return expect(tx).to.revertWith(expectedError); }); }); describe('batchExecute', () => { it('should execute no-op if no calls to make', async () => { await testProxyContract.batchExecute([]).awaitTransactionSuccessAsync(); }); it('should call one function and return the output', async () => { const calls = [testContract.echo(testString).getABIEncodedTransactionData()]; const rawResults = await testProxyContract.batchExecute(calls).callAsync(); expect(rawResults.length).to.equal(1); const returnValues = [testContract.getABIDecodedReturnData<{}>('echo', rawResults[0])]; expect(returnValues[0]).to.equal(testString); }); it('should call multiple functions and return their outputs', async () => { const calls = [ testContract.echo(testString).getABIEncodedTransactionData(), testContract.doMath(new BigNumber(2), new BigNumber(1)).getABIEncodedTransactionData(), ]; const rawResults = await testProxyContract.batchExecute(calls).callAsync(); expect(rawResults.length).to.equal(2); const returnValues = [ testContract.getABIDecodedReturnData<string>('echo', rawResults[0]), testContract.getABIDecodedReturnData<BigNumber[]>('doMath', rawResults[1]), ]; expect(returnValues[0]).to.equal(testString); expect(returnValues[1][0]).to.bignumber.equal(new BigNumber(3)); expect(returnValues[1][1]).to.bignumber.equal(new BigNumber(1)); }); it('should revert if a call reverts', async () => { const calls = [ testContract.echo(testString).getABIEncodedTransactionData(), testContract.die().getABIEncodedTransactionData(), testContract.doMath(new BigNumber(2), new BigNumber(1)).getABIEncodedTransactionData(), ]; const tx = testProxyContract.batchExecute(calls).callAsync(); const expectedError = testRevertString; return expect(tx).to.revertWith(expectedError); }); it('should revert if no staking contract is attached', async () => { await testProxyContract.detachStakingContract().awaitTransactionSuccessAsync({ from: authorizedAddress }); const calls = [testContract.echo(testString).getABIEncodedTransactionData()]; const tx = testProxyContract.batchExecute(calls).callAsync(); const expectedError = new StakingRevertErrors.ProxyDestinationCannotBeNilError(); return expect(tx).to.revertWith(expectedError); }); }); describe('assertValidStorageParams', () => { const validStorageParams = { epochDurationInSeconds: new BigNumber(stakingConstants.ONE_DAY_IN_SECONDS * 5), cobbDouglasAlphaNumerator: new BigNumber(1), cobbDouglasAlphaDenominator: new BigNumber(1), rewardDelegatedStakeWeight: constants.PPM_DENOMINATOR, minimumPoolStake: new BigNumber(100), }; it('should not revert if all storage params are valid', async () => { await testProxyContract.setTestStorageParams(validStorageParams).awaitTransactionSuccessAsync(); await testProxyContract.assertValidStorageParams().callAsync(); }); it('should revert if `epochDurationInSeconds` is less than 5 days', async () => { const invalidStorageParams = { ...validStorageParams, epochDurationInSeconds: new BigNumber(0), }; await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync(); const tx = testProxyContract.assertValidStorageParams().callAsync(); const expectedError = new StakingRevertErrors.InvalidParamValueError( StakingRevertErrors.InvalidParamValueErrorCodes.InvalidEpochDuration, ); return expect(tx).to.revertWith(expectedError); }); it('should revert if `epochDurationInSeconds` is greater than 30 days', async () => { const invalidStorageParams = { ...validStorageParams, epochDurationInSeconds: new BigNumber(stakingConstants.ONE_DAY_IN_SECONDS * 31), }; await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync(); const tx = testProxyContract.assertValidStorageParams().callAsync(); const expectedError = new StakingRevertErrors.InvalidParamValueError( StakingRevertErrors.InvalidParamValueErrorCodes.InvalidEpochDuration, ); return expect(tx).to.revertWith(expectedError); }); it('should revert if `cobbDouglasAlphaNumerator` is greater than `cobbDouglasAlphaDenominator`', async () => { const invalidStorageParams = { ...validStorageParams, cobbDouglasAlphaNumerator: new BigNumber(2), cobbDouglasAlphaDenominator: new BigNumber(1), }; await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync(); const tx = testProxyContract.assertValidStorageParams().callAsync(); const expectedError = new StakingRevertErrors.InvalidParamValueError( StakingRevertErrors.InvalidParamValueErrorCodes.InvalidCobbDouglasAlpha, ); return expect(tx).to.revertWith(expectedError); }); it('should revert if `cobbDouglasAlphaDenominator` equals zero', async () => { const invalidStorageParams = { ...validStorageParams, cobbDouglasAlphaDenominator: new BigNumber(0), }; await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync(); const tx = testProxyContract.assertValidStorageParams().callAsync(); const expectedError = new StakingRevertErrors.InvalidParamValueError( StakingRevertErrors.InvalidParamValueErrorCodes.InvalidCobbDouglasAlpha, ); return expect(tx).to.revertWith(expectedError); }); it('should revert if `rewardDelegatedStakeWeight` is greater than PPM_DENOMINATOR', async () => { const invalidStorageParams = { ...validStorageParams, rewardDelegatedStakeWeight: new BigNumber(constants.PPM_DENOMINATOR + 1), }; await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync(); const tx = testProxyContract.assertValidStorageParams().callAsync(); const expectedError = new StakingRevertErrors.InvalidParamValueError( StakingRevertErrors.InvalidParamValueErrorCodes.InvalidRewardDelegatedStakeWeight, ); return expect(tx).to.revertWith(expectedError); }); it('should revert if `minimumPoolStake` is less than two', async () => { const invalidStorageParams = { ...validStorageParams, minimumPoolStake: new BigNumber(1), }; await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync(); const tx = testProxyContract.assertValidStorageParams().callAsync(); const expectedError = new StakingRevertErrors.InvalidParamValueError( StakingRevertErrors.InvalidParamValueErrorCodes.InvalidMinimumPoolStake, ); return expect(tx).to.revertWith(expectedError); }); }); }); // tslint:disable: max-file-line-count
the_stack
import { dirname } from 'path'; import { addImportToModule, addBootstrapToModule, addSymbolToNgModuleMetadata, findNodes, } from '@schematics/angular/utility/ast-utils'; import { InsertChange, Change } from '@schematics/angular/utility/change'; import { SchematicsException, Rule, Tree } from '@angular-devkit/schematics'; import * as ts from 'typescript'; import { toComponentClassName, Node, removeNode, getFileContents, getJsonFile } from './utils'; class RemoveContent implements Node { constructor(private pos: number, private end: number) { } getStart() { return this.pos; } getFullStart() { return this.pos; } getEnd() { return this.end; } } export function getSymbolsToAddToObject(path: string, node: any, metadataField: string, symbolName: string) { // Get all the children property assignment of object literals. const matchingProperties: Array<ts.ObjectLiteralElement> = (node as ts.ObjectLiteralExpression).properties .filter((prop) => prop.kind === ts.SyntaxKind.PropertyAssignment) // Filter out every fields that's not 'metadataField'. Also handles string literals // (but not expressions). .filter((prop: ts.PropertyAssignment) => { const name = prop.name; switch (name.kind) { case ts.SyntaxKind.Identifier: return (name as ts.Identifier).getText() === metadataField; case ts.SyntaxKind.StringLiteral: return (name as ts.StringLiteral).text === metadataField; } return false; }); // Get the last node of the array literal. if (!matchingProperties) { return []; } if (matchingProperties.length === 0) { // We haven't found the field in the metadata declaration. Insert a new field. const expr = node as ts.ObjectLiteralExpression; let pos: number; let textToInsert: string; if (expr.properties.length === 0) { pos = expr.getEnd() - 1; textToInsert = ` ${metadataField}: [${symbolName}],\n`; } else { node = expr.properties[expr.properties.length - 1]; pos = node.getEnd(); // Get the indentation of the last element, if any. const text = node.getFullText(); const matches = text.match(/^\r?\n\s*/); if (matches && matches.length > 0) { textToInsert = `,${matches[0]}${metadataField}: ${symbolName},`; } else { textToInsert = `, ${metadataField}: ${symbolName},`; } } return [new InsertChange(path, pos, textToInsert)]; } const assignment = matchingProperties[0] as ts.PropertyAssignment; // If it's not an array, keep the original value. if (assignment.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) { return []; } const arrLiteral = assignment.initializer as ts.ArrayLiteralExpression; if (arrLiteral.elements.length === 0) { // Forward the property. node = arrLiteral; } else { node = arrLiteral.elements; } if (!node) { console.log('No app module found. Please add your new class to your component.'); return []; } if (Array.isArray(node)) { const nodeArray = node as {} as Array<ts.Node>; const symbolsArray = nodeArray.map((n) => n.getText()); if (symbolsArray.indexOf(symbolName) !== -1) { return []; } node = node[node.length - 1]; } let toInsert: string; let position = node.getEnd(); if (node.kind === ts.SyntaxKind.ObjectLiteralExpression) { // We haven't found the field in the metadata declaration. Insert a new // field. const expr = node as ts.ObjectLiteralExpression; if (expr.properties.length === 0) { position = expr.getEnd() - 1; toInsert = ` ${metadataField}: [${symbolName}],\n`; } else { node = expr.properties[expr.properties.length - 1]; position = node.getEnd(); // Get the indentation of the last element, if any. const text = node.getFullText(); if (text.match('^\r?\r?\n')) { toInsert = `,${text.match(/^\r?\n\s+/)[0]}${metadataField}: [${symbolName},]`; } else { toInsert = `, ${metadataField}: [${symbolName},]`; } } } else if (node.kind === ts.SyntaxKind.ArrayLiteralExpression) { // We found the field but it's empty. Insert it just before the `]`. position--; toInsert = `${symbolName}`; } else { // Get the indentation of the last element, if any. const text = node.getFullText(); if (text.match(/^\r?\n/)) { toInsert = `,${text.match(/^\r?\n(\r?)\s+/)[0]}${symbolName},`; } else { toInsert = `, ${symbolName},`; } } return [new InsertChange(path, position, toInsert)]; } export function findFullImports(importName: string, source: ts.SourceFile): Array<ts.ImportDeclaration | ts.ImportSpecifier | RemoveContent> { const allImports = collectDeepNodes<ts.ImportDeclaration>(source, ts.SyntaxKind.ImportDeclaration); return allImports // Filter out import statements that are either `import 'XYZ'` or `import * as X from 'XYZ'`. .filter(({ importClause: clause }) => clause && !clause.name && clause.namedBindings && clause.namedBindings.kind === ts.SyntaxKind.NamedImports, ) .reduce(( imports: Array<ts.ImportDeclaration | ts.ImportSpecifier | RemoveContent>, importDecl: ts.ImportDeclaration, ) => { const importClause = importDecl.importClause as ts.ImportClause; const namedImports = importClause.namedBindings as ts.NamedImports; namedImports.elements.forEach((importSpec: ts.ImportSpecifier) => { const importId = importSpec.name; if (!(importId.text === importName)) { return; } if (namedImports.elements.length === 1) { imports.push(importDecl); } else { const toRemove = normalizeNodeToRemove<ts.ImportSpecifier>(importSpec, source); imports.push(toRemove); } }); return imports; }, []); } export function findImports(importName: string, source: ts.SourceFile): Array<ts.ImportDeclaration> { const allImports = collectDeepNodes<ts.ImportDeclaration>(source, ts.SyntaxKind.ImportDeclaration); return allImports .filter(({ importClause: clause }) => clause && !clause.name && clause.namedBindings && clause.namedBindings.kind === ts.SyntaxKind.NamedImports, ) .reduce(( imports: Array<ts.ImportDeclaration>, importDecl: ts.ImportDeclaration, ) => { const importClause = importDecl.importClause as ts.ImportClause; const namedImports = importClause.namedBindings as ts.NamedImports; namedImports.elements.forEach((importSpec: ts.ImportSpecifier) => { const importId = importSpec.name; if (importId.text === importName) { imports.push(importDecl); } }); return imports; }, []); } export function findMetadataValueInArray(source: ts.Node, property: string, value: string): Array<ts.Node | RemoveContent> { const decorators = collectDeepNodes<ts.Decorator>(source, ts.SyntaxKind.Decorator); return getNodesToRemoveFromNestedArray(decorators, property, value); } export function getNodesToRemoveFromNestedArray(nodes: Array<ts.Node>, property: string, value: string) { const valuesNode = nodes .reduce( (allNodes, current) => [ ...allNodes, ...collectDeepNodes<ts.PropertyAssignment>(current, ts.SyntaxKind.PropertyAssignment), ], []) .find((assignment) => { let isValueForProperty = false; ts.forEachChild(assignment, (child: ts.Node) => { if (child.kind === ts.SyntaxKind.Identifier && child.getText() === property) { isValueForProperty = true; } }); return isValueForProperty; }); if (!valuesNode) { return []; } let arrayLiteral; ts.forEachChild(valuesNode, (child: ts.Node) => { if (child.kind === ts.SyntaxKind.ArrayLiteralExpression) { arrayLiteral = child; } }); if (!arrayLiteral) { return []; } const values: Array<ts.Node | RemoveContent> = []; ts.forEachChild(arrayLiteral, (child: ts.Node) => { if (child.getText() === value) { const toRemove = normalizeNodeToRemove(child, arrayLiteral); values.push(toRemove); } }); return values; } /** * * @param node The node that should be removed * @param source The source file that we are removing from * This method ensures that if there's a comma before or after the node, * it will be removed, too. */ function normalizeNodeToRemove<T extends ts.Node>(node: T, source: ts.Node) : (T | RemoveContent) { const content = source.getText(); const nodeStart = node.getFullStart(); const nodeEnd = node.getEnd(); const start = nodeStart - source.getFullStart(); const symbolBefore = content.substring(start - 1, start); if (symbolBefore === ',') { return new RemoveContent(nodeStart - 1, nodeEnd); } else { return new RemoveContent(nodeStart, nodeEnd + 1); } } export function addBootstrapToNgModule(modulePath: string, rootComponentName: string): Rule { return (host: Tree) => { const content = host.read(modulePath); if (!content) { throw new SchematicsException(`File ${modulePath} does not exist.`); } const sourceText = content.toString('utf-8'); const source = ts.createSourceFile(modulePath, sourceText, ts.ScriptTarget.Latest, true); const componentModule = `./${rootComponentName}.component`; const rootComponentClassName = toComponentClassName(rootComponentName); const importChanges = addImportToModule(<any>source, modulePath, 'NativeScriptModule', '@nativescript/angular'); const bootstrapChanges = addBootstrapToModule(<any>source, modulePath, rootComponentClassName, componentModule); const declarationChanges = addSymbolToNgModuleMetadata( <any>source, modulePath, 'declarations', rootComponentClassName, ); const changes = [ ...importChanges, ...bootstrapChanges, ...declarationChanges, ]; const recorder = host.beginUpdate(modulePath); for (const change of changes) { if (change instanceof InsertChange) { recorder.insertLeft(change.pos, change.toAdd); } } host.commitUpdate(recorder); return host; }; } export function collectDeepNodes<T extends ts.Node>(node: ts.Node, kind: ts.SyntaxKind): Array<T> { const nodes: Array<T> = []; const helper = (child: ts.Node) => { if (child.kind === kind) { nodes.push(child as T); } ts.forEachChild(child, helper); }; ts.forEachChild(node, helper); return nodes; } export function filterByChildNode( root: ts.Node, condition: (node: ts.Node) => boolean, ): boolean { let matches = false; const helper = (child: ts.Node) => { if (condition(child)) { matches = true; return; } }; ts.forEachChild(root, helper); return matches; } export const getDecoratedClass = (tree: Tree, filePath: string, decoratorName: string, className: string) => { return getDecoratedClasses(tree, filePath, decoratorName) .find((c) => !!(c.name && c.name.getText() === className)); }; export const getDecoratedClasses = (tree: Tree, filePath: string, decoratorName: string) => { const moduleSource = getSourceFile(tree, filePath); const classes = collectDeepNodes<ts.ClassDeclaration>(moduleSource, ts.SyntaxKind.ClassDeclaration); return classes.filter((c) => !!getDecorator(c, decoratorName)); }; export const getDecoratorMetadataFromClass = (classNode: ts.Node, decoratorName: string) => { const decorator = getDecorator(classNode, decoratorName); if (!decorator) { return; } return (<ts.CallExpression>decorator.expression).arguments[0]; }; const getDecorator = (node: ts.Node, name: string) => { return node.decorators && node.decorators.find((decorator: ts.Decorator) => decorator.expression.kind === ts.SyntaxKind.CallExpression && (<ts.CallExpression>decorator.expression).expression.getText() === name, ); }; export const removeMetadataArrayValue = (tree: Tree, filePath: string, property: string, value: string) => { const source = getSourceFile(tree, filePath); const nodesToRemove = findMetadataValueInArray(source, property, value); nodesToRemove.forEach((declaration) => removeNode(declaration, filePath, tree), ); }; export const removeImport = (tree: Tree, filePath: string, importName: string) => { const source = getSourceFile(tree, filePath); const importsToRemove = findFullImports(importName, source); importsToRemove.forEach((declaration) => removeNode(declaration, filePath, tree), ); }; /** * Insert `toInsert` after the last occurence of `ts.SyntaxKind[nodes[i].kind]` * or after the last of occurence of `syntaxKind` if the last occurence is a sub child * of ts.SyntaxKind[nodes[i].kind] and save the changes in file. * * @param nodes insert after the last occurence of nodes * @param toInsert string to insert * @param file file to insert changes into * @param fallbackPos position to insert if toInsert happens to be the first occurence * @param syntaxKind the ts.SyntaxKind of the subchildren to insert after * @return Change instance * @throw Error if toInsert is first occurence but fall back is not set */ export function insertBeforeFirstOccurence(nodes: Array<ts.Node>, toInsert: string, file: string, fallbackPos: number, syntaxKind?: ts.SyntaxKind): Change { let firstItem: any = nodes.sort(nodesByPosition).shift(); if (!firstItem) { throw new Error(); } if (syntaxKind) { firstItem = findNodes(<any>firstItem, syntaxKind).sort(<any>nodesByPosition).shift(); } if (!firstItem && fallbackPos === undefined) { throw new Error(`tried to insert ${toInsert} as first occurence with no fallback position`); } const firstItemPosition: number = firstItem ? firstItem.getStart() : fallbackPos; return new InsertChange(file, firstItemPosition, toInsert); } /** * Helper for sorting nodes. * @return function to sort nodes in increasing order of position in sourceFile */ function nodesByPosition(first: ts.Node, second: ts.Node): number { return first.getStart() - second.getStart(); } export interface SearchParam { name?: string; kind: ts.SyntaxKind; } export function findNode<T extends ts.Node>(node: ts.Node, searchParams: Array<SearchParam>, filter: string = ''): T { const matchingNodes = findMatchingNodes<T>(node, searchParams); if (matchingNodes.length === 0) { // TODO: This might require a better error message. const nodesText = searchParams .map((item) => item.name || item.kind) .reduce((name, currentResult) => name + ' => ' + currentResult); throw new SchematicsException(`Failed to find ${nodesText} in ${node.getSourceFile().fileName}.`); } const result = matchingNodes .filter((n) => n.getText() .includes(filter)); if (result.length !== 1) { const nodesText = searchParams .map((item) => item.name) .reduce((name, concatNames) => name + ' => ' + concatNames); if (result.length === 0) { if (filter !== '') { throw new SchematicsException(`Failed to find ${filter} for ${nodesText} in ${node.getSourceFile().fileName}.`); } else { throw new SchematicsException(`Failed to find ${nodesText} in ${node.getSourceFile().fileName}.`); } } else { throw new SchematicsException( `Found too many [${result.length} / expected 1] ${nodesText} in ${node.getSourceFile().fileName}.`, ); } } return result[0]; } export function findMatchingNodes<T extends ts.Node>( node: ts.Node, searchParams: Array<SearchParam>, index = 0, ): Array<T> { const searchParam = searchParams[index]; const nodes: Array<T> = []; const helper = (child: ts.Node) => { if (isMatchingNode(child, searchParam)) { if (index === searchParams.length - 1) { nodes.push(child as T); } else { nodes.push(...findMatchingNodes<T>(child, searchParams, index + 1)); } } else { if (child.getChildCount() > 0) { ts.forEachChild(child, helper); } } }; ts.forEachChild(node, helper); return nodes; } /** * Check if the node.kind matches the searchParam.kind * Also, if name provided, then check if we got the node with the right param name */ function isMatchingNode(node: ts.Node, searchParam: SearchParam) { if (node.kind !== searchParam.kind) { return false; } // If name provided the run it through checkNameForKind check // otherwise just return true return (searchParam.name) ? checkNameForKind(node, searchParam) : true; } function checkNameForKind(node: ts.Node, searchParam: SearchParam): boolean { if (!searchParam.name) { throw new SchematicsException( `checkNameForKind shouldn't be called without a name. Object => ${JSON.stringify(searchParam)}`, ); } let child: ts.Node; switch (searchParam.kind) { case ts.SyntaxKind.VariableDeclaration: case ts.SyntaxKind.PropertyAssignment: child = node.getChildAt(0); break; case ts.SyntaxKind.CallExpression: const callExpression = node as ts.CallExpression; const expression = callExpression.expression; // if function is an object's property - i.e. parent.fname() if (ts.isPropertyAccessExpression(expression)) { child = expression.name; } else { child = expression; } break; case ts.SyntaxKind.Identifier: child = node; break; case ts.SyntaxKind.NewExpression: const newExpression = node as ts.NewExpression; child = newExpression.expression; break; case ts.SyntaxKind.ImportDeclaration: const importDeclaration = node as ts.ImportDeclaration; if (!importDeclaration.importClause || !importDeclaration.importClause.namedBindings) { return false; } const namedBindings = importDeclaration.importClause.namedBindings; // for imports like: import { a, b } from 'path' // import names [a,b] are at: node.importClause.namedBindings.elements if (ts.isNamedImports(namedBindings)) { const elements = namedBindings.elements; return elements.some((element) => element.getText() === searchParam.name); } // otherwise, it is an import like: import * as abc from 'path' // import name [abc] is at: node.importClause.namedBindings.name child = namedBindings.name; break; case ts.SyntaxKind.ClassDeclaration: const classDeclaration = node as ts.ClassDeclaration; if (!classDeclaration.name) { return false; } child = classDeclaration.name; break; case ts.SyntaxKind.Decorator: const decorator = node as ts.Decorator; const decoratorCallExpression = decorator.expression as ts.CallExpression; child = decoratorCallExpression.expression; break; default: throw new SchematicsException(`compareNameForKind: not prepared for this [${node.kind}] ts.SyntaxKind`); } return child.getText() === searchParam.name; } export function findImportPath(source: ts.Node, name) { const node = findNode<ts.ImportDeclaration>(source, [ { kind: ts.SyntaxKind.ImportDeclaration, name }, ]); const moduleSpecifier = node.moduleSpecifier as ts.StringLiteral; return moduleSpecifier.text; } export const updateNodeText = (tree: Tree, node: ts.Node, newText: string) => { const recorder = tree.beginUpdate(node.getSourceFile().fileName); recorder.remove(node.getStart(), node.getText().length); recorder.insertLeft(node.getStart(), newText); tree.commitUpdate(recorder); }; export const replaceTextInNode = (tree: Tree, node: ts.Node, oldText: string, newText: string) => { const index = node.getStart() + node.getText().indexOf(oldText); const recorder = tree.beginUpdate(node.getSourceFile().fileName); recorder.remove(index, oldText.length); recorder.insertLeft(index, newText); tree.commitUpdate(recorder); }; export const getSourceFile = (host: Tree, path: string): ts.SourceFile => { const buffer = host.read(path); if (!buffer) { throw new SchematicsException( `Could not find file at ${path}. See https://github.com/NativeScript/nativescript-schematics/issues/172.`, ); } const content = buffer.toString(); const source = ts.createSourceFile(path, content, ts.ScriptTarget.Latest, true); return source; }; export function getCompilerOptions(tree: Tree, tsConfigPath: string) : ts.CompilerOptions | undefined { const tsConfigObject = parseTsConfigFile(tree, tsConfigPath); if (!tsConfigObject) { return; } const compilerOptions = tsConfigObject.options; return compilerOptions; } function parseTsConfigFile(tree: Tree, tsConfigPath: string): ts.ParsedCommandLine { const config = getJsonFile(tree, tsConfigPath); const host: ts.ParseConfigHost = { useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames, readDirectory: ts.sys.readDirectory, fileExists: (file: string) => tree.exists(file), readFile: (file: string) => getFileContents(tree, file), }; const basePath = dirname(tsConfigPath); const tsConfigObject = ts.parseJsonConfigFileContent(config, host, basePath); return tsConfigObject; }
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { AcceptAdministratorInvitationCommand, AcceptAdministratorInvitationCommandInput, AcceptAdministratorInvitationCommandOutput, } from "./commands/AcceptAdministratorInvitationCommand"; import { AcceptInvitationCommand, AcceptInvitationCommandInput, AcceptInvitationCommandOutput, } from "./commands/AcceptInvitationCommand"; import { BatchDisableStandardsCommand, BatchDisableStandardsCommandInput, BatchDisableStandardsCommandOutput, } from "./commands/BatchDisableStandardsCommand"; import { BatchEnableStandardsCommand, BatchEnableStandardsCommandInput, BatchEnableStandardsCommandOutput, } from "./commands/BatchEnableStandardsCommand"; import { BatchImportFindingsCommand, BatchImportFindingsCommandInput, BatchImportFindingsCommandOutput, } from "./commands/BatchImportFindingsCommand"; import { BatchUpdateFindingsCommand, BatchUpdateFindingsCommandInput, BatchUpdateFindingsCommandOutput, } from "./commands/BatchUpdateFindingsCommand"; import { CreateActionTargetCommand, CreateActionTargetCommandInput, CreateActionTargetCommandOutput, } from "./commands/CreateActionTargetCommand"; import { CreateInsightCommand, CreateInsightCommandInput, CreateInsightCommandOutput, } from "./commands/CreateInsightCommand"; import { CreateMembersCommand, CreateMembersCommandInput, CreateMembersCommandOutput, } from "./commands/CreateMembersCommand"; import { DeclineInvitationsCommand, DeclineInvitationsCommandInput, DeclineInvitationsCommandOutput, } from "./commands/DeclineInvitationsCommand"; import { DeleteActionTargetCommand, DeleteActionTargetCommandInput, DeleteActionTargetCommandOutput, } from "./commands/DeleteActionTargetCommand"; import { DeleteInsightCommand, DeleteInsightCommandInput, DeleteInsightCommandOutput, } from "./commands/DeleteInsightCommand"; import { DeleteInvitationsCommand, DeleteInvitationsCommandInput, DeleteInvitationsCommandOutput, } from "./commands/DeleteInvitationsCommand"; import { DeleteMembersCommand, DeleteMembersCommandInput, DeleteMembersCommandOutput, } from "./commands/DeleteMembersCommand"; import { DescribeActionTargetsCommand, DescribeActionTargetsCommandInput, DescribeActionTargetsCommandOutput, } from "./commands/DescribeActionTargetsCommand"; import { DescribeHubCommand, DescribeHubCommandInput, DescribeHubCommandOutput } from "./commands/DescribeHubCommand"; import { DescribeOrganizationConfigurationCommand, DescribeOrganizationConfigurationCommandInput, DescribeOrganizationConfigurationCommandOutput, } from "./commands/DescribeOrganizationConfigurationCommand"; import { DescribeProductsCommand, DescribeProductsCommandInput, DescribeProductsCommandOutput, } from "./commands/DescribeProductsCommand"; import { DescribeStandardsCommand, DescribeStandardsCommandInput, DescribeStandardsCommandOutput, } from "./commands/DescribeStandardsCommand"; import { DescribeStandardsControlsCommand, DescribeStandardsControlsCommandInput, DescribeStandardsControlsCommandOutput, } from "./commands/DescribeStandardsControlsCommand"; import { DisableImportFindingsForProductCommand, DisableImportFindingsForProductCommandInput, DisableImportFindingsForProductCommandOutput, } from "./commands/DisableImportFindingsForProductCommand"; import { DisableOrganizationAdminAccountCommand, DisableOrganizationAdminAccountCommandInput, DisableOrganizationAdminAccountCommandOutput, } from "./commands/DisableOrganizationAdminAccountCommand"; import { DisableSecurityHubCommand, DisableSecurityHubCommandInput, DisableSecurityHubCommandOutput, } from "./commands/DisableSecurityHubCommand"; import { DisassociateFromAdministratorAccountCommand, DisassociateFromAdministratorAccountCommandInput, DisassociateFromAdministratorAccountCommandOutput, } from "./commands/DisassociateFromAdministratorAccountCommand"; import { DisassociateFromMasterAccountCommand, DisassociateFromMasterAccountCommandInput, DisassociateFromMasterAccountCommandOutput, } from "./commands/DisassociateFromMasterAccountCommand"; import { DisassociateMembersCommand, DisassociateMembersCommandInput, DisassociateMembersCommandOutput, } from "./commands/DisassociateMembersCommand"; import { EnableImportFindingsForProductCommand, EnableImportFindingsForProductCommandInput, EnableImportFindingsForProductCommandOutput, } from "./commands/EnableImportFindingsForProductCommand"; import { EnableOrganizationAdminAccountCommand, EnableOrganizationAdminAccountCommandInput, EnableOrganizationAdminAccountCommandOutput, } from "./commands/EnableOrganizationAdminAccountCommand"; import { EnableSecurityHubCommand, EnableSecurityHubCommandInput, EnableSecurityHubCommandOutput, } from "./commands/EnableSecurityHubCommand"; import { GetAdministratorAccountCommand, GetAdministratorAccountCommandInput, GetAdministratorAccountCommandOutput, } from "./commands/GetAdministratorAccountCommand"; import { GetEnabledStandardsCommand, GetEnabledStandardsCommandInput, GetEnabledStandardsCommandOutput, } from "./commands/GetEnabledStandardsCommand"; import { GetFindingsCommand, GetFindingsCommandInput, GetFindingsCommandOutput } from "./commands/GetFindingsCommand"; import { GetInsightResultsCommand, GetInsightResultsCommandInput, GetInsightResultsCommandOutput, } from "./commands/GetInsightResultsCommand"; import { GetInsightsCommand, GetInsightsCommandInput, GetInsightsCommandOutput } from "./commands/GetInsightsCommand"; import { GetInvitationsCountCommand, GetInvitationsCountCommandInput, GetInvitationsCountCommandOutput, } from "./commands/GetInvitationsCountCommand"; import { GetMasterAccountCommand, GetMasterAccountCommandInput, GetMasterAccountCommandOutput, } from "./commands/GetMasterAccountCommand"; import { GetMembersCommand, GetMembersCommandInput, GetMembersCommandOutput } from "./commands/GetMembersCommand"; import { InviteMembersCommand, InviteMembersCommandInput, InviteMembersCommandOutput, } from "./commands/InviteMembersCommand"; import { ListEnabledProductsForImportCommand, ListEnabledProductsForImportCommandInput, ListEnabledProductsForImportCommandOutput, } from "./commands/ListEnabledProductsForImportCommand"; import { ListInvitationsCommand, ListInvitationsCommandInput, ListInvitationsCommandOutput, } from "./commands/ListInvitationsCommand"; import { ListMembersCommand, ListMembersCommandInput, ListMembersCommandOutput } from "./commands/ListMembersCommand"; import { ListOrganizationAdminAccountsCommand, ListOrganizationAdminAccountsCommandInput, ListOrganizationAdminAccountsCommandOutput, } from "./commands/ListOrganizationAdminAccountsCommand"; import { ListTagsForResourceCommand, ListTagsForResourceCommandInput, ListTagsForResourceCommandOutput, } from "./commands/ListTagsForResourceCommand"; import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand"; import { UntagResourceCommand, UntagResourceCommandInput, UntagResourceCommandOutput, } from "./commands/UntagResourceCommand"; import { UpdateActionTargetCommand, UpdateActionTargetCommandInput, UpdateActionTargetCommandOutput, } from "./commands/UpdateActionTargetCommand"; import { UpdateFindingsCommand, UpdateFindingsCommandInput, UpdateFindingsCommandOutput, } from "./commands/UpdateFindingsCommand"; import { UpdateInsightCommand, UpdateInsightCommandInput, UpdateInsightCommandOutput, } from "./commands/UpdateInsightCommand"; import { UpdateOrganizationConfigurationCommand, UpdateOrganizationConfigurationCommandInput, UpdateOrganizationConfigurationCommandOutput, } from "./commands/UpdateOrganizationConfigurationCommand"; import { UpdateSecurityHubConfigurationCommand, UpdateSecurityHubConfigurationCommandInput, UpdateSecurityHubConfigurationCommandOutput, } from "./commands/UpdateSecurityHubConfigurationCommand"; import { UpdateStandardsControlCommand, UpdateStandardsControlCommandInput, UpdateStandardsControlCommandOutput, } from "./commands/UpdateStandardsControlCommand"; import { SecurityHubClient } from "./SecurityHubClient"; /** * <p>Security Hub provides you with a comprehensive view of the security state of your Amazon Web Services environment and resources. It also provides you with the readiness status * of your environment based on controls from supported security standards. Security Hub collects * security data from Amazon Web Services accounts, services, and integrated third-party products and helps * you analyze security trends in your environment to identify the highest priority security * issues. For more information about Security Hub, see the <i>Security Hub<a href="https://docs.aws.amazon.com/securityhub/latest/userguide/what-is-securityhub.html">User * Guide</a> * </i>.</p> * <p>When you use operations in the Security Hub API, the requests are executed only in the Amazon Web Services * Region that is currently active or in the specific Amazon Web Services Region that you specify in your * request. Any configuration or settings change that results from the operation is applied * only to that Region. To make the same change in other Regions, execute the same command for * each Region to apply the change to.</p> * <p>For example, if your Region is set to <code>us-west-2</code>, when you use <code>CreateMembers</code> to add a member account to Security Hub, the association of * the member account with the administrator account is created only in the <code>us-west-2</code> * Region. Security Hub must be enabled for the member account in the same Region that the invitation * was sent from.</p> * <p>The following throttling limits apply to using Security Hub API operations.</p> * <ul> * <li> * <p> * <code>BatchEnableStandards</code> - <code>RateLimit</code> of 1 * request per second, <code>BurstLimit</code> of 1 request per second.</p> * </li> * <li> * <p> * <code>GetFindings</code> - <code>RateLimit</code> of 3 requests per second. * <code>BurstLimit</code> of 6 requests per second.</p> * </li> * <li> * <p> * <code>UpdateFindings</code> - <code>RateLimit</code> of 1 request per * second. <code>BurstLimit</code> of 5 requests per second.</p> * </li> * <li> * <p> * <code>UpdateStandardsControl</code> - <code>RateLimit</code> of * 1 request per second, <code>BurstLimit</code> of 5 requests per second.</p> * </li> * <li> * <p>All other operations - <code>RateLimit</code> of 10 requests per second. * <code>BurstLimit</code> of 30 requests per second.</p> * </li> * </ul> */ export class SecurityHub extends SecurityHubClient { /** * <p>Accepts the invitation to be a member account and be monitored by the Security Hub administrator * account that the invitation was sent from.</p> * <p>This operation is only used by member accounts that are not added through * Organizations.</p> * <p>When the member account accepts the invitation, permission is granted to the administrator * account to view findings generated in the member account.</p> */ public acceptAdministratorInvitation( args: AcceptAdministratorInvitationCommandInput, options?: __HttpHandlerOptions ): Promise<AcceptAdministratorInvitationCommandOutput>; public acceptAdministratorInvitation( args: AcceptAdministratorInvitationCommandInput, cb: (err: any, data?: AcceptAdministratorInvitationCommandOutput) => void ): void; public acceptAdministratorInvitation( args: AcceptAdministratorInvitationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: AcceptAdministratorInvitationCommandOutput) => void ): void; public acceptAdministratorInvitation( args: AcceptAdministratorInvitationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AcceptAdministratorInvitationCommandOutput) => void), cb?: (err: any, data?: AcceptAdministratorInvitationCommandOutput) => void ): Promise<AcceptAdministratorInvitationCommandOutput> | void { const command = new AcceptAdministratorInvitationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * @deprecated * * <p>This method is deprecated. Instead, use <code>AcceptAdministratorInvitation</code>.</p> * <p>The Security Hub console continues to use <code>AcceptInvitation</code>. It will eventually change to use <code>AcceptAdministratorInvitation</code>. Any IAM policies that specifically control access to this function must continue to use <code>AcceptInvitation</code>. You should also add <code>AcceptAdministratorInvitation</code> to your policies to ensure that the correct permissions are in place after the console begins to use <code>AcceptAdministratorInvitation</code>.</p> * <p>Accepts the invitation to be a member account and be monitored by the Security Hub administrator * account that the invitation was sent from.</p> * <p>This operation is only used by member accounts that are not added through * Organizations.</p> * <p>When the member account accepts the invitation, permission is granted to the administrator * account to view findings generated in the member account.</p> */ public acceptInvitation( args: AcceptInvitationCommandInput, options?: __HttpHandlerOptions ): Promise<AcceptInvitationCommandOutput>; public acceptInvitation( args: AcceptInvitationCommandInput, cb: (err: any, data?: AcceptInvitationCommandOutput) => void ): void; public acceptInvitation( args: AcceptInvitationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: AcceptInvitationCommandOutput) => void ): void; public acceptInvitation( args: AcceptInvitationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AcceptInvitationCommandOutput) => void), cb?: (err: any, data?: AcceptInvitationCommandOutput) => void ): Promise<AcceptInvitationCommandOutput> | void { const command = new AcceptInvitationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Disables the standards specified by the provided * <code>StandardsSubscriptionArns</code>.</p> * <p>For more information, see <a href="https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards.html">Security Standards</a> section of the <i>Security Hub User * Guide</i>.</p> */ public batchDisableStandards( args: BatchDisableStandardsCommandInput, options?: __HttpHandlerOptions ): Promise<BatchDisableStandardsCommandOutput>; public batchDisableStandards( args: BatchDisableStandardsCommandInput, cb: (err: any, data?: BatchDisableStandardsCommandOutput) => void ): void; public batchDisableStandards( args: BatchDisableStandardsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: BatchDisableStandardsCommandOutput) => void ): void; public batchDisableStandards( args: BatchDisableStandardsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchDisableStandardsCommandOutput) => void), cb?: (err: any, data?: BatchDisableStandardsCommandOutput) => void ): Promise<BatchDisableStandardsCommandOutput> | void { const command = new BatchDisableStandardsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Enables the standards specified by the provided <code>StandardsArn</code>. To obtain the * ARN for a standard, use the <code>DescribeStandards</code> * operation.</p> * <p>For more information, see the <a href="https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards.html">Security Standards</a> * section of the <i>Security Hub User Guide</i>.</p> */ public batchEnableStandards( args: BatchEnableStandardsCommandInput, options?: __HttpHandlerOptions ): Promise<BatchEnableStandardsCommandOutput>; public batchEnableStandards( args: BatchEnableStandardsCommandInput, cb: (err: any, data?: BatchEnableStandardsCommandOutput) => void ): void; public batchEnableStandards( args: BatchEnableStandardsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: BatchEnableStandardsCommandOutput) => void ): void; public batchEnableStandards( args: BatchEnableStandardsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchEnableStandardsCommandOutput) => void), cb?: (err: any, data?: BatchEnableStandardsCommandOutput) => void ): Promise<BatchEnableStandardsCommandOutput> | void { const command = new BatchEnableStandardsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Imports security findings generated from an integrated product into Security Hub. * This action is requested by the integrated product to import its findings into * Security Hub.</p> * <p>The maximum allowed size for a finding is 240 Kb. An error is returned for any finding * larger than 240 Kb.</p> * <p>After a finding is created, <code>BatchImportFindings</code> cannot be used to update * the following finding fields and objects, which Security Hub customers use to manage their * investigation workflow.</p> * <ul> * <li> * <p> * <code>Note</code> * </p> * </li> * <li> * <p> * <code>UserDefinedFields</code> * </p> * </li> * <li> * <p> * <code>VerificationState</code> * </p> * </li> * <li> * <p> * <code>Workflow</code> * </p> * </li> * </ul> * <p>Finding providers also should not use <code>BatchImportFindings</code> to update the following attributes.</p> * <ul> * <li> * <p> * <code>Confidence</code> * </p> * </li> * <li> * <p> * <code>Criticality</code> * </p> * </li> * <li> * <p> * <code>RelatedFindings</code> * </p> * </li> * <li> * <p> * <code>Severity</code> * </p> * </li> * <li> * <p> * <code>Types</code> * </p> * </li> * </ul> * <p>Instead, finding providers use <code>FindingProviderFields</code> to provide values for these attributes.</p> */ public batchImportFindings( args: BatchImportFindingsCommandInput, options?: __HttpHandlerOptions ): Promise<BatchImportFindingsCommandOutput>; public batchImportFindings( args: BatchImportFindingsCommandInput, cb: (err: any, data?: BatchImportFindingsCommandOutput) => void ): void; public batchImportFindings( args: BatchImportFindingsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: BatchImportFindingsCommandOutput) => void ): void; public batchImportFindings( args: BatchImportFindingsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchImportFindingsCommandOutput) => void), cb?: (err: any, data?: BatchImportFindingsCommandOutput) => void ): Promise<BatchImportFindingsCommandOutput> | void { const command = new BatchImportFindingsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Used by Security Hub customers to update information about their investigation into a finding. * Requested by administrator accounts or member accounts. Administrator accounts can update findings for * their account and their member accounts. Member accounts can update findings for their * account.</p> * <p>Updates from <code>BatchUpdateFindings</code> do not affect the value of * <code>UpdatedAt</code> for a finding.</p> * <p>Administrator and member accounts can use <code>BatchUpdateFindings</code> to update the * following finding fields and objects.</p> * <ul> * <li> * <p> * <code>Confidence</code> * </p> * </li> * <li> * <p> * <code>Criticality</code> * </p> * </li> * <li> * <p> * <code>Note</code> * </p> * </li> * <li> * <p> * <code>RelatedFindings</code> * </p> * </li> * <li> * <p> * <code>Severity</code> * </p> * </li> * <li> * <p> * <code>Types</code> * </p> * </li> * <li> * <p> * <code>UserDefinedFields</code> * </p> * </li> * <li> * <p> * <code>VerificationState</code> * </p> * </li> * <li> * <p> * <code>Workflow</code> * </p> * </li> * </ul> * <p>You can configure IAM policies to restrict access to fields and field values. For * example, you might not want member accounts to be able to suppress findings or change the * finding severity. See <a href="https://docs.aws.amazon.com/securityhub/latest/userguide/finding-update-batchupdatefindings.html#batchupdatefindings-configure-access">Configuring access to BatchUpdateFindings</a> in the * <i>Security Hub User Guide</i>.</p> */ public batchUpdateFindings( args: BatchUpdateFindingsCommandInput, options?: __HttpHandlerOptions ): Promise<BatchUpdateFindingsCommandOutput>; public batchUpdateFindings( args: BatchUpdateFindingsCommandInput, cb: (err: any, data?: BatchUpdateFindingsCommandOutput) => void ): void; public batchUpdateFindings( args: BatchUpdateFindingsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: BatchUpdateFindingsCommandOutput) => void ): void; public batchUpdateFindings( args: BatchUpdateFindingsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchUpdateFindingsCommandOutput) => void), cb?: (err: any, data?: BatchUpdateFindingsCommandOutput) => void ): Promise<BatchUpdateFindingsCommandOutput> | void { const command = new BatchUpdateFindingsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a custom action target in Security Hub.</p> * <p>You can use custom actions on findings and insights in Security Hub to trigger target actions * in Amazon CloudWatch Events.</p> */ public createActionTarget( args: CreateActionTargetCommandInput, options?: __HttpHandlerOptions ): Promise<CreateActionTargetCommandOutput>; public createActionTarget( args: CreateActionTargetCommandInput, cb: (err: any, data?: CreateActionTargetCommandOutput) => void ): void; public createActionTarget( args: CreateActionTargetCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateActionTargetCommandOutput) => void ): void; public createActionTarget( args: CreateActionTargetCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateActionTargetCommandOutput) => void), cb?: (err: any, data?: CreateActionTargetCommandOutput) => void ): Promise<CreateActionTargetCommandOutput> | void { const command = new CreateActionTargetCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a custom insight in Security Hub. An insight is a consolidation of findings that relate * to a security issue that requires attention or remediation.</p> * <p>To group the related findings in the insight, use the * <code>GroupByAttribute</code>.</p> */ public createInsight( args: CreateInsightCommandInput, options?: __HttpHandlerOptions ): Promise<CreateInsightCommandOutput>; public createInsight( args: CreateInsightCommandInput, cb: (err: any, data?: CreateInsightCommandOutput) => void ): void; public createInsight( args: CreateInsightCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateInsightCommandOutput) => void ): void; public createInsight( args: CreateInsightCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateInsightCommandOutput) => void), cb?: (err: any, data?: CreateInsightCommandOutput) => void ): Promise<CreateInsightCommandOutput> | void { const command = new CreateInsightCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a member association in Security Hub between the specified accounts and the account * used to make the request, which is the administrator account. If you are integrated with * Organizations, then the administrator account is designated by the organization management account.</p> * <p> * <code>CreateMembers</code> is always used to add accounts that are not organization * members.</p> * <p>For accounts that are managed using Organizations, <code>CreateMembers</code> is only used * in the following cases:</p> * <ul> * <li> * <p>Security Hub is not configured to automatically add new organization accounts.</p> * </li> * <li> * <p>The account was disassociated or deleted in Security Hub.</p> * </li> * </ul> * <p>This action can only be used by an account that has Security Hub enabled. To enable Security Hub, you * can use the <code>EnableSecurityHub</code> operation.</p> * <p>For accounts that are not organization members, you create the account association and * then send an invitation to the member account. To send the invitation, you use the * <code>InviteMembers</code> operation. If the account owner accepts * the invitation, the account becomes a member account in Security Hub.</p> * <p>Accounts that are managed using Organizations do not receive an invitation. They * automatically become a member account in Security Hub.</p> * <ul> * <li> * <p>If the organization account does not have Security Hub enabled, then Security Hub and the default standards are automatically enabled. Note that Security Hub cannot be enabled automatically for the organization management account. The organization management account must enable Security Hub before the administrator account enables it as a member account.</p> * </li> * <li> * <p>For organization accounts that already have Security Hub enabled, Security Hub does not make any other changes to those accounts. It does not change their enabled standards or controls.</p> * </li> * </ul> * * <p>A permissions policy is added that permits the administrator account to view the findings * generated in the member account.</p> * <p>To remove the association between the administrator and member accounts, use the <code>DisassociateFromMasterAccount</code> or <code>DisassociateMembers</code> operation.</p> */ public createMembers( args: CreateMembersCommandInput, options?: __HttpHandlerOptions ): Promise<CreateMembersCommandOutput>; public createMembers( args: CreateMembersCommandInput, cb: (err: any, data?: CreateMembersCommandOutput) => void ): void; public createMembers( args: CreateMembersCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateMembersCommandOutput) => void ): void; public createMembers( args: CreateMembersCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateMembersCommandOutput) => void), cb?: (err: any, data?: CreateMembersCommandOutput) => void ): Promise<CreateMembersCommandOutput> | void { const command = new CreateMembersCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Declines invitations to become a member account.</p> * <p>This operation is only used by accounts that are not part of an organization. * Organization accounts do not receive invitations.</p> */ public declineInvitations( args: DeclineInvitationsCommandInput, options?: __HttpHandlerOptions ): Promise<DeclineInvitationsCommandOutput>; public declineInvitations( args: DeclineInvitationsCommandInput, cb: (err: any, data?: DeclineInvitationsCommandOutput) => void ): void; public declineInvitations( args: DeclineInvitationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeclineInvitationsCommandOutput) => void ): void; public declineInvitations( args: DeclineInvitationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeclineInvitationsCommandOutput) => void), cb?: (err: any, data?: DeclineInvitationsCommandOutput) => void ): Promise<DeclineInvitationsCommandOutput> | void { const command = new DeclineInvitationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a custom action target from Security Hub.</p> * <p>Deleting a custom action target does not affect any findings or insights that were * already sent to Amazon CloudWatch Events using the custom action.</p> */ public deleteActionTarget( args: DeleteActionTargetCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteActionTargetCommandOutput>; public deleteActionTarget( args: DeleteActionTargetCommandInput, cb: (err: any, data?: DeleteActionTargetCommandOutput) => void ): void; public deleteActionTarget( args: DeleteActionTargetCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteActionTargetCommandOutput) => void ): void; public deleteActionTarget( args: DeleteActionTargetCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteActionTargetCommandOutput) => void), cb?: (err: any, data?: DeleteActionTargetCommandOutput) => void ): Promise<DeleteActionTargetCommandOutput> | void { const command = new DeleteActionTargetCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes the insight specified by the <code>InsightArn</code>.</p> */ public deleteInsight( args: DeleteInsightCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteInsightCommandOutput>; public deleteInsight( args: DeleteInsightCommandInput, cb: (err: any, data?: DeleteInsightCommandOutput) => void ): void; public deleteInsight( args: DeleteInsightCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteInsightCommandOutput) => void ): void; public deleteInsight( args: DeleteInsightCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteInsightCommandOutput) => void), cb?: (err: any, data?: DeleteInsightCommandOutput) => void ): Promise<DeleteInsightCommandOutput> | void { const command = new DeleteInsightCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes invitations received by the Amazon Web Services account to become a member account.</p> * <p>This operation is only used by accounts that are not part of an organization. * Organization accounts do not receive invitations.</p> */ public deleteInvitations( args: DeleteInvitationsCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteInvitationsCommandOutput>; public deleteInvitations( args: DeleteInvitationsCommandInput, cb: (err: any, data?: DeleteInvitationsCommandOutput) => void ): void; public deleteInvitations( args: DeleteInvitationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteInvitationsCommandOutput) => void ): void; public deleteInvitations( args: DeleteInvitationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteInvitationsCommandOutput) => void), cb?: (err: any, data?: DeleteInvitationsCommandOutput) => void ): Promise<DeleteInvitationsCommandOutput> | void { const command = new DeleteInvitationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes the specified member accounts from Security Hub.</p> * <p>Can be used to delete member accounts that belong to an organization as well as member * accounts that were invited manually.</p> */ public deleteMembers( args: DeleteMembersCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteMembersCommandOutput>; public deleteMembers( args: DeleteMembersCommandInput, cb: (err: any, data?: DeleteMembersCommandOutput) => void ): void; public deleteMembers( args: DeleteMembersCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteMembersCommandOutput) => void ): void; public deleteMembers( args: DeleteMembersCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteMembersCommandOutput) => void), cb?: (err: any, data?: DeleteMembersCommandOutput) => void ): Promise<DeleteMembersCommandOutput> | void { const command = new DeleteMembersCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of the custom action targets in Security Hub in your account.</p> */ public describeActionTargets( args: DescribeActionTargetsCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeActionTargetsCommandOutput>; public describeActionTargets( args: DescribeActionTargetsCommandInput, cb: (err: any, data?: DescribeActionTargetsCommandOutput) => void ): void; public describeActionTargets( args: DescribeActionTargetsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeActionTargetsCommandOutput) => void ): void; public describeActionTargets( args: DescribeActionTargetsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeActionTargetsCommandOutput) => void), cb?: (err: any, data?: DescribeActionTargetsCommandOutput) => void ): Promise<DescribeActionTargetsCommandOutput> | void { const command = new DescribeActionTargetsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns details about the Hub resource in your account, including the * <code>HubArn</code> and the time when you enabled Security Hub.</p> */ public describeHub(args: DescribeHubCommandInput, options?: __HttpHandlerOptions): Promise<DescribeHubCommandOutput>; public describeHub(args: DescribeHubCommandInput, cb: (err: any, data?: DescribeHubCommandOutput) => void): void; public describeHub( args: DescribeHubCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeHubCommandOutput) => void ): void; public describeHub( args: DescribeHubCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeHubCommandOutput) => void), cb?: (err: any, data?: DescribeHubCommandOutput) => void ): Promise<DescribeHubCommandOutput> | void { const command = new DescribeHubCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about the Organizations configuration for Security Hub. Can only be * called from a Security Hub administrator account.</p> */ public describeOrganizationConfiguration( args: DescribeOrganizationConfigurationCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeOrganizationConfigurationCommandOutput>; public describeOrganizationConfiguration( args: DescribeOrganizationConfigurationCommandInput, cb: (err: any, data?: DescribeOrganizationConfigurationCommandOutput) => void ): void; public describeOrganizationConfiguration( args: DescribeOrganizationConfigurationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeOrganizationConfigurationCommandOutput) => void ): void; public describeOrganizationConfiguration( args: DescribeOrganizationConfigurationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeOrganizationConfigurationCommandOutput) => void), cb?: (err: any, data?: DescribeOrganizationConfigurationCommandOutput) => void ): Promise<DescribeOrganizationConfigurationCommandOutput> | void { const command = new DescribeOrganizationConfigurationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about product integrations in Security Hub.</p> * <p>You can optionally provide an integration ARN. If you provide an integration ARN, then * the results only include that integration.</p> * <p>If you do not provide an integration ARN, then the results include all of the available * product integrations. </p> */ public describeProducts( args: DescribeProductsCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeProductsCommandOutput>; public describeProducts( args: DescribeProductsCommandInput, cb: (err: any, data?: DescribeProductsCommandOutput) => void ): void; public describeProducts( args: DescribeProductsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeProductsCommandOutput) => void ): void; public describeProducts( args: DescribeProductsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeProductsCommandOutput) => void), cb?: (err: any, data?: DescribeProductsCommandOutput) => void ): Promise<DescribeProductsCommandOutput> | void { const command = new DescribeProductsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of the available standards in Security Hub.</p> * <p>For each standard, the results include the standard ARN, the name, and a description. </p> */ public describeStandards( args: DescribeStandardsCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeStandardsCommandOutput>; public describeStandards( args: DescribeStandardsCommandInput, cb: (err: any, data?: DescribeStandardsCommandOutput) => void ): void; public describeStandards( args: DescribeStandardsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeStandardsCommandOutput) => void ): void; public describeStandards( args: DescribeStandardsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeStandardsCommandOutput) => void), cb?: (err: any, data?: DescribeStandardsCommandOutput) => void ): Promise<DescribeStandardsCommandOutput> | void { const command = new DescribeStandardsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of security standards controls.</p> * <p>For each control, the results include information about whether it is currently enabled, * the severity, and a link to remediation information.</p> */ public describeStandardsControls( args: DescribeStandardsControlsCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeStandardsControlsCommandOutput>; public describeStandardsControls( args: DescribeStandardsControlsCommandInput, cb: (err: any, data?: DescribeStandardsControlsCommandOutput) => void ): void; public describeStandardsControls( args: DescribeStandardsControlsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeStandardsControlsCommandOutput) => void ): void; public describeStandardsControls( args: DescribeStandardsControlsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeStandardsControlsCommandOutput) => void), cb?: (err: any, data?: DescribeStandardsControlsCommandOutput) => void ): Promise<DescribeStandardsControlsCommandOutput> | void { const command = new DescribeStandardsControlsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Disables the integration of the specified product with Security Hub. After the integration is * disabled, findings from that product are no longer sent to Security Hub.</p> */ public disableImportFindingsForProduct( args: DisableImportFindingsForProductCommandInput, options?: __HttpHandlerOptions ): Promise<DisableImportFindingsForProductCommandOutput>; public disableImportFindingsForProduct( args: DisableImportFindingsForProductCommandInput, cb: (err: any, data?: DisableImportFindingsForProductCommandOutput) => void ): void; public disableImportFindingsForProduct( args: DisableImportFindingsForProductCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DisableImportFindingsForProductCommandOutput) => void ): void; public disableImportFindingsForProduct( args: DisableImportFindingsForProductCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DisableImportFindingsForProductCommandOutput) => void), cb?: (err: any, data?: DisableImportFindingsForProductCommandOutput) => void ): Promise<DisableImportFindingsForProductCommandOutput> | void { const command = new DisableImportFindingsForProductCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Disables a Security Hub administrator account. Can only be called by the organization * management account.</p> */ public disableOrganizationAdminAccount( args: DisableOrganizationAdminAccountCommandInput, options?: __HttpHandlerOptions ): Promise<DisableOrganizationAdminAccountCommandOutput>; public disableOrganizationAdminAccount( args: DisableOrganizationAdminAccountCommandInput, cb: (err: any, data?: DisableOrganizationAdminAccountCommandOutput) => void ): void; public disableOrganizationAdminAccount( args: DisableOrganizationAdminAccountCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DisableOrganizationAdminAccountCommandOutput) => void ): void; public disableOrganizationAdminAccount( args: DisableOrganizationAdminAccountCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DisableOrganizationAdminAccountCommandOutput) => void), cb?: (err: any, data?: DisableOrganizationAdminAccountCommandOutput) => void ): Promise<DisableOrganizationAdminAccountCommandOutput> | void { const command = new DisableOrganizationAdminAccountCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Disables Security Hub in your account only in the current Region. To disable Security Hub in all * Regions, you must submit one request per Region where you have enabled Security Hub.</p> * <p>When you disable Security Hub for an administrator account, it doesn't disable Security Hub for any associated * member accounts.</p> * <p>When you disable Security Hub, your existing findings and insights and any Security Hub configuration * settings are deleted after 90 days and cannot be recovered. Any standards that were enabled * are disabled, and your administrator and member account associations are removed.</p> * <p>If you want to save your existing findings, you must export them before you disable * Security Hub.</p> */ public disableSecurityHub( args: DisableSecurityHubCommandInput, options?: __HttpHandlerOptions ): Promise<DisableSecurityHubCommandOutput>; public disableSecurityHub( args: DisableSecurityHubCommandInput, cb: (err: any, data?: DisableSecurityHubCommandOutput) => void ): void; public disableSecurityHub( args: DisableSecurityHubCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DisableSecurityHubCommandOutput) => void ): void; public disableSecurityHub( args: DisableSecurityHubCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DisableSecurityHubCommandOutput) => void), cb?: (err: any, data?: DisableSecurityHubCommandOutput) => void ): Promise<DisableSecurityHubCommandOutput> | void { const command = new DisableSecurityHubCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Disassociates the current Security Hub member account from the associated administrator * account.</p> * <p>This operation is only used by accounts that are not part of an organization. For * organization accounts, only the administrator account can * disassociate a member account.</p> */ public disassociateFromAdministratorAccount( args: DisassociateFromAdministratorAccountCommandInput, options?: __HttpHandlerOptions ): Promise<DisassociateFromAdministratorAccountCommandOutput>; public disassociateFromAdministratorAccount( args: DisassociateFromAdministratorAccountCommandInput, cb: (err: any, data?: DisassociateFromAdministratorAccountCommandOutput) => void ): void; public disassociateFromAdministratorAccount( args: DisassociateFromAdministratorAccountCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DisassociateFromAdministratorAccountCommandOutput) => void ): void; public disassociateFromAdministratorAccount( args: DisassociateFromAdministratorAccountCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DisassociateFromAdministratorAccountCommandOutput) => void), cb?: (err: any, data?: DisassociateFromAdministratorAccountCommandOutput) => void ): Promise<DisassociateFromAdministratorAccountCommandOutput> | void { const command = new DisassociateFromAdministratorAccountCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * @deprecated * * <p>This method is deprecated. Instead, use <code>DisassociateFromAdministratorAccount</code>.</p> * <p>The Security Hub console continues to use <code>DisassociateFromMasterAccount</code>. It will eventually change to use <code>DisassociateFromAdministratorAccount</code>. Any IAM policies that specifically control access to this function must continue to use <code>DisassociateFromMasterAccount</code>. You should also add <code>DisassociateFromAdministratorAccount</code> to your policies to ensure that the correct permissions are in place after the console begins to use <code>DisassociateFromAdministratorAccount</code>.</p> * <p>Disassociates the current Security Hub member account from the associated administrator * account.</p> * <p>This operation is only used by accounts that are not part of an organization. For * organization accounts, only the administrator account can * disassociate a member account.</p> */ public disassociateFromMasterAccount( args: DisassociateFromMasterAccountCommandInput, options?: __HttpHandlerOptions ): Promise<DisassociateFromMasterAccountCommandOutput>; public disassociateFromMasterAccount( args: DisassociateFromMasterAccountCommandInput, cb: (err: any, data?: DisassociateFromMasterAccountCommandOutput) => void ): void; public disassociateFromMasterAccount( args: DisassociateFromMasterAccountCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DisassociateFromMasterAccountCommandOutput) => void ): void; public disassociateFromMasterAccount( args: DisassociateFromMasterAccountCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DisassociateFromMasterAccountCommandOutput) => void), cb?: (err: any, data?: DisassociateFromMasterAccountCommandOutput) => void ): Promise<DisassociateFromMasterAccountCommandOutput> | void { const command = new DisassociateFromMasterAccountCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Disassociates the specified member accounts from the associated administrator account.</p> * <p>Can be used to disassociate both accounts that are managed using Organizations and accounts that * were invited manually.</p> */ public disassociateMembers( args: DisassociateMembersCommandInput, options?: __HttpHandlerOptions ): Promise<DisassociateMembersCommandOutput>; public disassociateMembers( args: DisassociateMembersCommandInput, cb: (err: any, data?: DisassociateMembersCommandOutput) => void ): void; public disassociateMembers( args: DisassociateMembersCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DisassociateMembersCommandOutput) => void ): void; public disassociateMembers( args: DisassociateMembersCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DisassociateMembersCommandOutput) => void), cb?: (err: any, data?: DisassociateMembersCommandOutput) => void ): Promise<DisassociateMembersCommandOutput> | void { const command = new DisassociateMembersCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Enables the integration of a partner product with Security Hub. Integrated products send * findings to Security Hub.</p> * <p>When you enable a product integration, a permissions policy that grants permission for * the product to send findings to Security Hub is applied.</p> */ public enableImportFindingsForProduct( args: EnableImportFindingsForProductCommandInput, options?: __HttpHandlerOptions ): Promise<EnableImportFindingsForProductCommandOutput>; public enableImportFindingsForProduct( args: EnableImportFindingsForProductCommandInput, cb: (err: any, data?: EnableImportFindingsForProductCommandOutput) => void ): void; public enableImportFindingsForProduct( args: EnableImportFindingsForProductCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: EnableImportFindingsForProductCommandOutput) => void ): void; public enableImportFindingsForProduct( args: EnableImportFindingsForProductCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: EnableImportFindingsForProductCommandOutput) => void), cb?: (err: any, data?: EnableImportFindingsForProductCommandOutput) => void ): Promise<EnableImportFindingsForProductCommandOutput> | void { const command = new EnableImportFindingsForProductCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Designates the Security Hub administrator account for an organization. Can only be called by * the organization management account.</p> */ public enableOrganizationAdminAccount( args: EnableOrganizationAdminAccountCommandInput, options?: __HttpHandlerOptions ): Promise<EnableOrganizationAdminAccountCommandOutput>; public enableOrganizationAdminAccount( args: EnableOrganizationAdminAccountCommandInput, cb: (err: any, data?: EnableOrganizationAdminAccountCommandOutput) => void ): void; public enableOrganizationAdminAccount( args: EnableOrganizationAdminAccountCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: EnableOrganizationAdminAccountCommandOutput) => void ): void; public enableOrganizationAdminAccount( args: EnableOrganizationAdminAccountCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: EnableOrganizationAdminAccountCommandOutput) => void), cb?: (err: any, data?: EnableOrganizationAdminAccountCommandOutput) => void ): Promise<EnableOrganizationAdminAccountCommandOutput> | void { const command = new EnableOrganizationAdminAccountCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Enables Security Hub for your account in the current Region or the Region you specify in the * request.</p> * <p>When you enable Security Hub, you grant to Security Hub the permissions necessary to gather findings * from other services that are integrated with Security Hub.</p> * <p>When you use the <code>EnableSecurityHub</code> operation to enable Security Hub, you also * automatically enable the following standards.</p> * <ul> * <li> * <p>CIS Amazon Web Services Foundations</p> * </li> * <li> * <p>Amazon Web Services Foundational Security Best Practices</p> * </li> * </ul> * <p>You do not enable the Payment Card Industry Data Security Standard (PCI DSS) standard. </p> * <p>To not enable the automatically enabled standards, set * <code>EnableDefaultStandards</code> to <code>false</code>.</p> * <p>After you enable Security Hub, to enable a standard, use the <code>BatchEnableStandards</code> operation. To disable a standard, use the * <code>BatchDisableStandards</code> operation.</p> * <p>To learn more, see the <a href="https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-settingup.html">setup information</a> in the <i>Security Hub User Guide</i>.</p> */ public enableSecurityHub( args: EnableSecurityHubCommandInput, options?: __HttpHandlerOptions ): Promise<EnableSecurityHubCommandOutput>; public enableSecurityHub( args: EnableSecurityHubCommandInput, cb: (err: any, data?: EnableSecurityHubCommandOutput) => void ): void; public enableSecurityHub( args: EnableSecurityHubCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: EnableSecurityHubCommandOutput) => void ): void; public enableSecurityHub( args: EnableSecurityHubCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: EnableSecurityHubCommandOutput) => void), cb?: (err: any, data?: EnableSecurityHubCommandOutput) => void ): Promise<EnableSecurityHubCommandOutput> | void { const command = new EnableSecurityHubCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Provides the details for the Security Hub administrator account for the current member account.</p> * <p>Can be used by both member accounts that are managed using Organizations and accounts that were * invited manually.</p> */ public getAdministratorAccount( args: GetAdministratorAccountCommandInput, options?: __HttpHandlerOptions ): Promise<GetAdministratorAccountCommandOutput>; public getAdministratorAccount( args: GetAdministratorAccountCommandInput, cb: (err: any, data?: GetAdministratorAccountCommandOutput) => void ): void; public getAdministratorAccount( args: GetAdministratorAccountCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetAdministratorAccountCommandOutput) => void ): void; public getAdministratorAccount( args: GetAdministratorAccountCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetAdministratorAccountCommandOutput) => void), cb?: (err: any, data?: GetAdministratorAccountCommandOutput) => void ): Promise<GetAdministratorAccountCommandOutput> | void { const command = new GetAdministratorAccountCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of the standards that are currently enabled.</p> */ public getEnabledStandards( args: GetEnabledStandardsCommandInput, options?: __HttpHandlerOptions ): Promise<GetEnabledStandardsCommandOutput>; public getEnabledStandards( args: GetEnabledStandardsCommandInput, cb: (err: any, data?: GetEnabledStandardsCommandOutput) => void ): void; public getEnabledStandards( args: GetEnabledStandardsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetEnabledStandardsCommandOutput) => void ): void; public getEnabledStandards( args: GetEnabledStandardsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetEnabledStandardsCommandOutput) => void), cb?: (err: any, data?: GetEnabledStandardsCommandOutput) => void ): Promise<GetEnabledStandardsCommandOutput> | void { const command = new GetEnabledStandardsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of findings that match the specified criteria.</p> */ public getFindings(args: GetFindingsCommandInput, options?: __HttpHandlerOptions): Promise<GetFindingsCommandOutput>; public getFindings(args: GetFindingsCommandInput, cb: (err: any, data?: GetFindingsCommandOutput) => void): void; public getFindings( args: GetFindingsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetFindingsCommandOutput) => void ): void; public getFindings( args: GetFindingsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetFindingsCommandOutput) => void), cb?: (err: any, data?: GetFindingsCommandOutput) => void ): Promise<GetFindingsCommandOutput> | void { const command = new GetFindingsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the results of the Security Hub insight specified by the insight ARN.</p> */ public getInsightResults( args: GetInsightResultsCommandInput, options?: __HttpHandlerOptions ): Promise<GetInsightResultsCommandOutput>; public getInsightResults( args: GetInsightResultsCommandInput, cb: (err: any, data?: GetInsightResultsCommandOutput) => void ): void; public getInsightResults( args: GetInsightResultsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetInsightResultsCommandOutput) => void ): void; public getInsightResults( args: GetInsightResultsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetInsightResultsCommandOutput) => void), cb?: (err: any, data?: GetInsightResultsCommandOutput) => void ): Promise<GetInsightResultsCommandOutput> | void { const command = new GetInsightResultsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists and describes insights for the specified insight ARNs.</p> */ public getInsights(args: GetInsightsCommandInput, options?: __HttpHandlerOptions): Promise<GetInsightsCommandOutput>; public getInsights(args: GetInsightsCommandInput, cb: (err: any, data?: GetInsightsCommandOutput) => void): void; public getInsights( args: GetInsightsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetInsightsCommandOutput) => void ): void; public getInsights( args: GetInsightsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetInsightsCommandOutput) => void), cb?: (err: any, data?: GetInsightsCommandOutput) => void ): Promise<GetInsightsCommandOutput> | void { const command = new GetInsightsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns the count of all Security Hub membership invitations that were sent to the * current member account, not including the currently accepted invitation. </p> */ public getInvitationsCount( args: GetInvitationsCountCommandInput, options?: __HttpHandlerOptions ): Promise<GetInvitationsCountCommandOutput>; public getInvitationsCount( args: GetInvitationsCountCommandInput, cb: (err: any, data?: GetInvitationsCountCommandOutput) => void ): void; public getInvitationsCount( args: GetInvitationsCountCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetInvitationsCountCommandOutput) => void ): void; public getInvitationsCount( args: GetInvitationsCountCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetInvitationsCountCommandOutput) => void), cb?: (err: any, data?: GetInvitationsCountCommandOutput) => void ): Promise<GetInvitationsCountCommandOutput> | void { const command = new GetInvitationsCountCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * @deprecated * * <p>This method is deprecated. Instead, use <code>GetAdministratorAccount</code>.</p> * <p>The Security Hub console continues to use <code>GetMasterAccount</code>. It will eventually change to use <code>GetAdministratorAccount</code>. Any IAM policies that specifically control access to this function must continue to use <code>GetMasterAccount</code>. You should also add <code>GetAdministratorAccount</code> to your policies to ensure that the correct permissions are in place after the console begins to use <code>GetAdministratorAccount</code>.</p> * <p>Provides the details for the Security Hub administrator account for the current member account.</p> * <p>Can be used by both member accounts that are managed using Organizations and accounts that were * invited manually.</p> */ public getMasterAccount( args: GetMasterAccountCommandInput, options?: __HttpHandlerOptions ): Promise<GetMasterAccountCommandOutput>; public getMasterAccount( args: GetMasterAccountCommandInput, cb: (err: any, data?: GetMasterAccountCommandOutput) => void ): void; public getMasterAccount( args: GetMasterAccountCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetMasterAccountCommandOutput) => void ): void; public getMasterAccount( args: GetMasterAccountCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetMasterAccountCommandOutput) => void), cb?: (err: any, data?: GetMasterAccountCommandOutput) => void ): Promise<GetMasterAccountCommandOutput> | void { const command = new GetMasterAccountCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns the details for the Security Hub member accounts for the specified account IDs.</p> * <p>An administrator account can be either the delegated Security Hub administrator account for an * organization or an administrator account that enabled Security Hub manually.</p> * <p>The results include both member accounts that are managed using Organizations and accounts that * were invited manually.</p> */ public getMembers(args: GetMembersCommandInput, options?: __HttpHandlerOptions): Promise<GetMembersCommandOutput>; public getMembers(args: GetMembersCommandInput, cb: (err: any, data?: GetMembersCommandOutput) => void): void; public getMembers( args: GetMembersCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetMembersCommandOutput) => void ): void; public getMembers( args: GetMembersCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetMembersCommandOutput) => void), cb?: (err: any, data?: GetMembersCommandOutput) => void ): Promise<GetMembersCommandOutput> | void { const command = new GetMembersCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Invites other Amazon Web Services accounts to become member accounts for the Security Hub administrator account that * the invitation is sent from.</p> * <p>This operation is only used to invite accounts that do not belong to an organization. * Organization accounts do not receive invitations.</p> * <p>Before you can use this action to invite a member, you must first use the <code>CreateMembers</code> action to create the member account in Security Hub.</p> * <p>When the account owner enables Security Hub and accepts the invitation to become a member * account, the administrator account can view the findings generated from the member account.</p> */ public inviteMembers( args: InviteMembersCommandInput, options?: __HttpHandlerOptions ): Promise<InviteMembersCommandOutput>; public inviteMembers( args: InviteMembersCommandInput, cb: (err: any, data?: InviteMembersCommandOutput) => void ): void; public inviteMembers( args: InviteMembersCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: InviteMembersCommandOutput) => void ): void; public inviteMembers( args: InviteMembersCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: InviteMembersCommandOutput) => void), cb?: (err: any, data?: InviteMembersCommandOutput) => void ): Promise<InviteMembersCommandOutput> | void { const command = new InviteMembersCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists all findings-generating solutions (products) that you are subscribed to receive * findings from in Security Hub.</p> */ public listEnabledProductsForImport( args: ListEnabledProductsForImportCommandInput, options?: __HttpHandlerOptions ): Promise<ListEnabledProductsForImportCommandOutput>; public listEnabledProductsForImport( args: ListEnabledProductsForImportCommandInput, cb: (err: any, data?: ListEnabledProductsForImportCommandOutput) => void ): void; public listEnabledProductsForImport( args: ListEnabledProductsForImportCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListEnabledProductsForImportCommandOutput) => void ): void; public listEnabledProductsForImport( args: ListEnabledProductsForImportCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListEnabledProductsForImportCommandOutput) => void), cb?: (err: any, data?: ListEnabledProductsForImportCommandOutput) => void ): Promise<ListEnabledProductsForImportCommandOutput> | void { const command = new ListEnabledProductsForImportCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists all Security Hub membership invitations that were sent to the current Amazon Web Services account.</p> * <p>This operation is only used by accounts that are managed by invitation. * Accounts that are managed using the integration with Organizations do not receive invitations.</p> */ public listInvitations( args: ListInvitationsCommandInput, options?: __HttpHandlerOptions ): Promise<ListInvitationsCommandOutput>; public listInvitations( args: ListInvitationsCommandInput, cb: (err: any, data?: ListInvitationsCommandOutput) => void ): void; public listInvitations( args: ListInvitationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListInvitationsCommandOutput) => void ): void; public listInvitations( args: ListInvitationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListInvitationsCommandOutput) => void), cb?: (err: any, data?: ListInvitationsCommandOutput) => void ): Promise<ListInvitationsCommandOutput> | void { const command = new ListInvitationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists details about all member accounts for the current Security Hub administrator * account.</p> * <p>The results include both member accounts that belong to an organization and member * accounts that were invited manually.</p> */ public listMembers(args: ListMembersCommandInput, options?: __HttpHandlerOptions): Promise<ListMembersCommandOutput>; public listMembers(args: ListMembersCommandInput, cb: (err: any, data?: ListMembersCommandOutput) => void): void; public listMembers( args: ListMembersCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListMembersCommandOutput) => void ): void; public listMembers( args: ListMembersCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListMembersCommandOutput) => void), cb?: (err: any, data?: ListMembersCommandOutput) => void ): Promise<ListMembersCommandOutput> | void { const command = new ListMembersCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the Security Hub administrator accounts. Can only be called by the organization * management account.</p> */ public listOrganizationAdminAccounts( args: ListOrganizationAdminAccountsCommandInput, options?: __HttpHandlerOptions ): Promise<ListOrganizationAdminAccountsCommandOutput>; public listOrganizationAdminAccounts( args: ListOrganizationAdminAccountsCommandInput, cb: (err: any, data?: ListOrganizationAdminAccountsCommandOutput) => void ): void; public listOrganizationAdminAccounts( args: ListOrganizationAdminAccountsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListOrganizationAdminAccountsCommandOutput) => void ): void; public listOrganizationAdminAccounts( args: ListOrganizationAdminAccountsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListOrganizationAdminAccountsCommandOutput) => void), cb?: (err: any, data?: ListOrganizationAdminAccountsCommandOutput) => void ): Promise<ListOrganizationAdminAccountsCommandOutput> | void { const command = new ListOrganizationAdminAccountsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of tags associated with a resource.</p> */ public listTagsForResource( args: ListTagsForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<ListTagsForResourceCommandOutput>; public listTagsForResource( args: ListTagsForResourceCommandInput, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void), cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void ): Promise<ListTagsForResourceCommandOutput> | void { const command = new ListTagsForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Adds one or more tags to a resource.</p> */ public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>; public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void; public tagResource( args: TagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: TagResourceCommandOutput) => void ): void; public tagResource( args: TagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void), cb?: (err: any, data?: TagResourceCommandOutput) => void ): Promise<TagResourceCommandOutput> | void { const command = new TagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes one or more tags from a resource.</p> */ public untagResource( args: UntagResourceCommandInput, options?: __HttpHandlerOptions ): Promise<UntagResourceCommandOutput>; public untagResource( args: UntagResourceCommandInput, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void), cb?: (err: any, data?: UntagResourceCommandOutput) => void ): Promise<UntagResourceCommandOutput> | void { const command = new UntagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates the name and description of a custom action target in Security Hub.</p> */ public updateActionTarget( args: UpdateActionTargetCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateActionTargetCommandOutput>; public updateActionTarget( args: UpdateActionTargetCommandInput, cb: (err: any, data?: UpdateActionTargetCommandOutput) => void ): void; public updateActionTarget( args: UpdateActionTargetCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateActionTargetCommandOutput) => void ): void; public updateActionTarget( args: UpdateActionTargetCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateActionTargetCommandOutput) => void), cb?: (err: any, data?: UpdateActionTargetCommandOutput) => void ): Promise<UpdateActionTargetCommandOutput> | void { const command = new UpdateActionTargetCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * <code>UpdateFindings</code> is deprecated. Instead of <code>UpdateFindings</code>, use * <code>BatchUpdateFindings</code>.</p> * <p>Updates the <code>Note</code> and <code>RecordState</code> of the Security Hub-aggregated * findings that the filter attributes specify. Any member account that can view the finding * also sees the update to the finding.</p> */ public updateFindings( args: UpdateFindingsCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateFindingsCommandOutput>; public updateFindings( args: UpdateFindingsCommandInput, cb: (err: any, data?: UpdateFindingsCommandOutput) => void ): void; public updateFindings( args: UpdateFindingsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateFindingsCommandOutput) => void ): void; public updateFindings( args: UpdateFindingsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateFindingsCommandOutput) => void), cb?: (err: any, data?: UpdateFindingsCommandOutput) => void ): Promise<UpdateFindingsCommandOutput> | void { const command = new UpdateFindingsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates the Security Hub insight identified by the specified insight ARN.</p> */ public updateInsight( args: UpdateInsightCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateInsightCommandOutput>; public updateInsight( args: UpdateInsightCommandInput, cb: (err: any, data?: UpdateInsightCommandOutput) => void ): void; public updateInsight( args: UpdateInsightCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateInsightCommandOutput) => void ): void; public updateInsight( args: UpdateInsightCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateInsightCommandOutput) => void), cb?: (err: any, data?: UpdateInsightCommandOutput) => void ): Promise<UpdateInsightCommandOutput> | void { const command = new UpdateInsightCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Used to update the configuration related to Organizations. Can only be called from a * Security Hub administrator account.</p> */ public updateOrganizationConfiguration( args: UpdateOrganizationConfigurationCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateOrganizationConfigurationCommandOutput>; public updateOrganizationConfiguration( args: UpdateOrganizationConfigurationCommandInput, cb: (err: any, data?: UpdateOrganizationConfigurationCommandOutput) => void ): void; public updateOrganizationConfiguration( args: UpdateOrganizationConfigurationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateOrganizationConfigurationCommandOutput) => void ): void; public updateOrganizationConfiguration( args: UpdateOrganizationConfigurationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateOrganizationConfigurationCommandOutput) => void), cb?: (err: any, data?: UpdateOrganizationConfigurationCommandOutput) => void ): Promise<UpdateOrganizationConfigurationCommandOutput> | void { const command = new UpdateOrganizationConfigurationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates configuration options for Security Hub.</p> */ public updateSecurityHubConfiguration( args: UpdateSecurityHubConfigurationCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateSecurityHubConfigurationCommandOutput>; public updateSecurityHubConfiguration( args: UpdateSecurityHubConfigurationCommandInput, cb: (err: any, data?: UpdateSecurityHubConfigurationCommandOutput) => void ): void; public updateSecurityHubConfiguration( args: UpdateSecurityHubConfigurationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateSecurityHubConfigurationCommandOutput) => void ): void; public updateSecurityHubConfiguration( args: UpdateSecurityHubConfigurationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateSecurityHubConfigurationCommandOutput) => void), cb?: (err: any, data?: UpdateSecurityHubConfigurationCommandOutput) => void ): Promise<UpdateSecurityHubConfigurationCommandOutput> | void { const command = new UpdateSecurityHubConfigurationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Used to control whether an individual security standard control is enabled or * disabled.</p> */ public updateStandardsControl( args: UpdateStandardsControlCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateStandardsControlCommandOutput>; public updateStandardsControl( args: UpdateStandardsControlCommandInput, cb: (err: any, data?: UpdateStandardsControlCommandOutput) => void ): void; public updateStandardsControl( args: UpdateStandardsControlCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateStandardsControlCommandOutput) => void ): void; public updateStandardsControl( args: UpdateStandardsControlCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateStandardsControlCommandOutput) => void), cb?: (err: any, data?: UpdateStandardsControlCommandOutput) => void ): Promise<UpdateStandardsControlCommandOutput> | void { const command = new UpdateStandardsControlCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import { Observable } from 'rxjs/Observable'; import { ArmServiceHelper } from './arm.service-helper'; import { Jwt } from './../Utilities/jwt'; import { Url } from './../Utilities/url'; import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; import { ReplaySubject } from 'rxjs/ReplaySubject'; import { PinPartInfo, GetStartupInfo, NotificationInfo, NotificationStartedInfo, DataMessage, DataMessageResult, DirtyStateInfo, SubscriptionRequest, BladeResult, EventFilter, EventVerbs, TokenType, CheckPermissionRequest, CheckPermissionResponse, CheckLockRequest, CheckLockResponse, LockType, FrameBladeParams, SendToken2, } from './../models/portal'; import { Event, Data, Verbs, Action, LogEntryLevel, Message, UpdateBladeInfo, OpenBladeInfo, StartupInfo, TimerEvent, BroadcastMessage, BroadcastMessageId, } from '../models/portal'; import { ErrorEvent } from '../models/error-event'; import { BroadcastService } from './broadcast.service'; import { BroadcastEvent, EventMessage } from '../models/broadcast-event'; import { AiService } from './ai.service'; import { Guid } from '../Utilities/Guid'; import { SpecCostQueryInput, SpecCostQueryResult } from '../../site/spec-picker/price-spec-manager/billing-models'; import { Subscription } from '../models/subscription'; import { ConfigService } from 'app/shared/services/config.service'; import { SlotSwapInfo, SlotNewInfo } from '../models/slot-events'; import { ByosData } from '../../site/byos/byos'; import { LogService } from './log.service'; import { LogCategories } from '../models/constants'; export interface IPortalService { getStartupInfo(); sendTimerEvent(evt: TimerEvent); openBladeDeprecated(bladeInfo: OpenBladeInfo, source: string); openBlade(bladeInfo: OpenBladeInfo, source: string); openCollectorBlade(resourceId: string, name: string, source: string, getAppSettingCallback: (appSettingName: string) => void); openCollectorBladeWithInputs( resourceId: string, obj: any, source: string, getAppSettingCallback: (appSettingName: string) => void, bladeName?: string ); getAdToken(tokenType: TokenType); getSpecCosts(query: SpecCostQueryInput): Observable<SpecCostQueryResult>; getSubscription(subscriptionId: string): Observable<Subscription>; closeBlades(); updateBladeInfo(title: string, subtitle: string); pinPart(pinPartInfo: PinPartInfo); startNotification(title: string, description: string); stopNotification(id: string, success: boolean, description: string); logAction(subcomponent: string, action: string, data?: any): void; setDirtyState(dirty: boolean); updateDirtyState(dirty: boolean, message?: string); logMessage(level: LogEntryLevel, message: string, ...restArgs: any[]); returnPcv3Results<T>(results: T); broadcastMessage<T>(id: BroadcastMessageId, resourceId: string, metadata?: T); returnByosSelections(selections: ByosData); hasPermission(resourceId: string, actions: string[]); hasLock(resourceId: string, type: LockType); } @Injectable() export class PortalService implements IPortalService { public sessionId = ''; public resourceId: string; public isEmbeddedFunctions = Url.getParameterByName(window.location.href, 'appsvc.embedded') === 'functions'; private portalSignature = 'FxAppBlade'; private portalSignatureFrameBlade = 'FxFrameBlade'; private embeddedSignature = 'FunctionsEmbedded'; private acceptedSignatures = [this.portalSignature, this.portalSignatureFrameBlade, this.embeddedSignature]; private acceptedOriginsSuffix = [ 'portal.azure.com', 'portal.microsoftazure.de', 'portal.azure.cn', 'portal.azure.us', 'portal.azure.eaglex.ic.gov', 'portal.azure.microsoft.scloud', ]; private startupInfo: StartupInfo<any> | null; private startupInfoObservable: ReplaySubject<StartupInfo<any>>; private getAppSettingCallback: (appSettingName: string) => void; private shellSrc: string; private notificationStartStream: Subject<NotificationStartedInfo>; private operationStream = new Subject<DataMessage<any>>(); public static inIFrame(): boolean { return window.parent !== window && window.location.pathname !== '/context.html'; } public static inTab(): boolean { return Url.getParameterByName(null, 'tabbed') === 'true'; } private frameId; constructor( private _broadcastService: BroadcastService, private _aiService: AiService, private _configService: ConfigService, private _logService: LogService ) { this.startupInfoObservable = new ReplaySubject<StartupInfo<void>>(1); this.notificationStartStream = new Subject<NotificationStartedInfo>(); this.frameId = Url.getParameterByName(null, 'frameId'); if (PortalService.inIFrame()) { this.initializeIframe(); } } getStartupInfo() { return this.startupInfoObservable; } private initializeIframe(): void { const shellUrl = decodeURI(window.location.href); this.shellSrc = Url.getParameterByName(shellUrl, 'trustedAuthority'); window.addEventListener(Verbs.message, this.iframeReceivedMsg.bind(this), false); const appsvc = window.appsvc; const getStartupInfoObj: GetStartupInfo = { iframeHostName: appsvc && appsvc.env && appsvc.env.hostName ? appsvc.env.hostName : '', iframeAppName: appsvc && appsvc.env && appsvc.env.appName ? appsvc.env.appName : '', }; // This is a required message. It tells the shell that your iframe is ready to receive messages. this.postMessage(Verbs.ready, null); this.postMessage(Verbs.getStartupInfo, this._packageData(getStartupInfoObj)); this.postMessage(Verbs.initializationcomplete, null); this._broadcastService.subscribe<ErrorEvent>(BroadcastEvent.Error, error => { if (error.message) { this.logMessage(LogEntryLevel.Error, error.message); } }); } setInboundEventFilter(allowedIFrameEventVerbs: string[]) { const payload: EventFilter = { allowedIFrameEventVerbs: allowedIFrameEventVerbs || [] }; this.postMessage(Verbs.setFrameboundEventFilter, this._packageData(payload)); } sendTimerEvent(evt: TimerEvent) { this.postMessage(Verbs.logTimerEvent, this._packageData(evt)); } // Deprecated openBladeDeprecated<T = any>(bladeInfo: OpenBladeInfo<T>, source: string) { this.logAction(source, 'open-blade ' + bladeInfo.detailBlade); this._aiService.trackEvent('/site/open-blade', { targetBlade: bladeInfo.detailBlade, targetExtension: bladeInfo.extension, source: source, }); this.postMessage(Verbs.openBlade, this._packageData(bladeInfo)); } // Deprecated openFrameBladeDeprecated<T = any>(bladeInfo: OpenBladeInfo<FrameBladeParams<T>>, source: string) { this.openBladeDeprecated(bladeInfo, source); } // Returns an Observable which resolves when blade is close. // Optionally may also return a value openBlade<T = any>(bladeInfo: OpenBladeInfo<T>, source: string): Observable<BladeResult<any>> { const payload: DataMessage<OpenBladeInfo<T>> = { operationId: Guid.newGuid(), data: bladeInfo, }; this.postMessage(Verbs.openBlade2, this._packageData(payload)); return this.operationStream .filter(o => o.operationId === payload.operationId) .first() .map((r: DataMessage<DataMessageResult<BladeResult<any>>>) => { return r.data.result; }); } openFrameBlade<T = any>(bladeInfo: OpenBladeInfo<FrameBladeParams<T>>, source: string): Observable<BladeResult<any>> { return this.openBlade(bladeInfo, source); } openCollectorBlade(resourceId: string, name: string, source: string, getAppSettingCallback: (appSettingName: string) => void): void { this.logAction(source, 'open-blade-collector' + name, null); this._aiService.trackEvent('/site/open-collector-blade', { targetBlade: name, source: source, }); this.getAppSettingCallback = getAppSettingCallback; const payload = { resourceId: resourceId, bladeName: name, }; this.postMessage(Verbs.openBladeCollector, this._packageData(payload)); } openCollectorBladeWithInputs( resourceId: string, obj: any, source: string, getAppSettingCallback: (appSettingName: string) => void, bladeName?: string ) { this.logAction(source, 'open-blade-collector-inputs' + obj.bladeName, null); this._aiService.trackEvent('/site/open-collector-blade', { targetBlade: obj.bladeName, source: source, }); this.getAppSettingCallback = getAppSettingCallback; const operationId = Guid.newGuid(); const payload = { resourceId: resourceId, input: obj, bladeName: bladeName, operationId: operationId, }; this.postMessage(Verbs.openBladeCollectorInputs, this._packageData(payload)); return this.operationStream .filter(o => o.operationId === operationId) .first() .switchMap((o: DataMessage<DataMessageResult<any>>) => { if (o.data.status === 'success') { return Observable.of(o.data); } else if (o.data.status === 'cancelled') { return Observable.of(null); } else { return Observable.throw(o.data); } }); } getAdToken(tokenType: TokenType) { this.logAction('portal-service', `get-ad-token: ${tokenType}`, null); const operationId = Guid.newGuid(); const payload = { operationId: operationId, data: { tokenType: tokenType, }, }; this.postMessage('get-ad-token', this._packageData(payload)); return this.operationStream .filter(o => o.operationId === operationId) .first() .switchMap((o: DataMessage<DataMessageResult<any>>) => { if (o.data.status === 'success') { return Observable.of(o.data); } else if (o.data.status === 'cancelled') { return Observable.of(null); } else { return Observable.throw(o.data); } }); } hasPermission(resourceId: string, actions: string[]) { this.logAction('portal-service', 'has-permission', { resourceId }); const operationId = Guid.newGuid(); const payload: DataMessage<CheckPermissionRequest> = { operationId, data: { resourceId, actions, }, }; this.postMessage(Verbs.hasPermission, this._packageData(payload)); return this.operationStream .filter(o => o.operationId === operationId) .first() .switchMap((o: DataMessage<DataMessageResult<CheckPermissionResponse>>) => { if (o.data.status !== 'success') { this._logService.error(LogCategories.portalServiceHasPermission, 'hasPermission', payload); } return Observable.of(o.data.result.hasPermission); }); } hasLock(resourceId: string, type: LockType) { this.logAction('portal-service', 'has-lock', { resourceId }); const operationId = Guid.newGuid(); const payload: DataMessage<CheckLockRequest> = { operationId, data: { resourceId, type, }, }; this.postMessage(Verbs.hasLock, this._packageData(payload)); return this.operationStream .filter(o => o.operationId === operationId) .first() .switchMap((o: DataMessage<DataMessageResult<CheckLockResponse>>) => { if (o.data.status !== 'success') { this._logService.error(LogCategories.portalServiceHasLock, 'hasLock', payload); } return Observable.of(o.data.result.hasLock); }); } getSpecCosts(query: SpecCostQueryInput): Observable<SpecCostQueryResult> { const payload: DataMessage<SpecCostQueryInput> = { operationId: Guid.newGuid(), data: query, }; this.postMessage(Verbs.getSpecCosts, this._packageData(payload)); return this.operationStream .filter(o => o.operationId === payload.operationId) .first() .map((r: DataMessage<DataMessageResult<SpecCostQueryResult>>) => { return r.data.result; }); } getSubscription(subscriptionId: string): Observable<Subscription> { const payload: DataMessage<SubscriptionRequest> = { operationId: Guid.newGuid(), data: { subscriptionId: subscriptionId, }, }; this.postMessage(Verbs.getSubscriptionInfo, this._packageData(payload)); return this.operationStream .filter(o => o.operationId === payload.operationId) .first() .map((r: DataMessage<DataMessageResult<Subscription>>) => { return r.data.result; }); } closeBlades() { this.postMessage(Verbs.closeBlades, this._packageData({})); } closeSelf(data?: any) { this.postMessage(Verbs.closeSelf, data || ''); } switchMenuItem(data?: any) { this.postMessage(Verbs.switchMenuItem, data || ''); } updateBladeInfo(title: string, subtitle: string) { const payload: UpdateBladeInfo = { title: title, subtitle: subtitle, }; this.postMessage(Verbs.updateBladeInfo, this._packageData(payload)); } pinPart(pinPartInfo: PinPartInfo) { this.postMessage(Verbs.pinPart, this._packageData(pinPartInfo)); } startNotification(title: string, description: string): Subject<NotificationStartedInfo> { if (PortalService.inIFrame()) { const payload: NotificationInfo = { state: 'start', title: title, description: description, }; this.postMessage(Verbs.setNotification, this._packageData(payload)); } else { setTimeout(() => { this.notificationStartStream.next({ id: 'id' }); }); } return this.notificationStartStream; } stopNotification(id: string, success: boolean, description: string) { let state = 'success'; if (!success) { state = 'fail'; } const payload: NotificationInfo = { id: id, state: state, title: null, description: description, }; this.postMessage(Verbs.setNotification, this._packageData(payload)); } logAction(subcomponent: string, action: string, data?: { [name: string]: string }): void { const actionStr = this._packageData(<Action>{ subcomponent: subcomponent, action: action, data: data, }); this._aiService.trackEvent(`/${subcomponent}/${action}`, data); this.postMessage(Verbs.logAction, actionStr); } // Deprecated setDirtyState(dirty: boolean): void { this.updateDirtyState(dirty); } updateDirtyState(dirty: boolean, message?: string): void { const info: DirtyStateInfo = { dirty: dirty, message: message, }; this.postMessage(Verbs.updateDirtyState, this._packageData(info)); } broadcastMessage<T>(id: BroadcastMessageId, resourceId: string, metadata?: T): void { const info: BroadcastMessage<T> = { id, resourceId, metadata, }; this.postMessage(Verbs.broadcastMessage, this._packageData(info)); } logMessage(level: LogEntryLevel, message: string, ...restArgs: any[]) { const messageStr = this._packageData(<Message>{ level: level, message: message, restArgs: restArgs, }); this.postMessage(Verbs.logMessage, messageStr); } returnPcv3Results<T>(results: T) { const payload: DataMessage<T> = { operationId: Guid.newGuid(), data: results, }; this.postMessage(Verbs.returnPCV3Results, this._packageData(payload)); } returnByosSelections(selections: ByosData) { const payload: DataMessage<ByosData> = { operationId: Guid.newGuid(), data: selections, }; this.postMessage(Verbs.returnByosSelections, this._packageData(payload)); } private iframeReceivedMsg(event: Event): void { if (!event || !event.data) { return; } else if (event.data.data && event.data.data.frameId && event.data.data.frameId !== this.frameId) { return; } else if ( !this._configService.isOnPrem() && !this._configService.isStandalone() && !this.acceptedOriginsSuffix.find(o => event.origin.toLowerCase().endsWith(o.toLowerCase())) ) { return; } else if (!this.acceptedSignatures.find(s => event.data.signature !== s)) { return; } const data = event.data.data; const methodName = event.data.kind; console.log(`[iFrame-${this.frameId}] Received mesg: ${methodName} for frameId: ${event.data.data && event.data.data.frameId}`); if (methodName === Verbs.sendStartupInfo) { this.startupInfo = <StartupInfo<void>>data; this.sessionId = this.startupInfo.sessionId; this._aiService.setSessionId(this.sessionId); // Prefer whatever Ibiza sends us if hosted in iframe. This is mainly for national clouds ArmServiceHelper.armEndpoint = this.startupInfo.armEndpoint ? this.startupInfo.armEndpoint : ArmServiceHelper.armEndpoint; window.appsvc.env.azureResourceManagerEndpoint = ArmServiceHelper.armEndpoint; window.appsvc.env.armToken = this.startupInfo.token; window.appsvc.resourceId = this.startupInfo.resourceId; window.appsvc.feature = this.startupInfo.featureInfo && this.startupInfo.featureInfo.feature; window.appsvc.frameId = this.frameId; this.startupInfoObservable.next(this.startupInfo); this.logTokenExpiration(this.startupInfo.token, '/portal-service/token-new-startupInfo'); } else if (methodName === Verbs.sendToken2) { const sendTokenMessage = <SendToken2>data; const token = sendTokenMessage && sendTokenMessage.token; if (this.startupInfo && !!token && this.startupInfo.token !== token) { this.startupInfo.token = token; this.startupInfoObservable.next(this.startupInfo); this.logTokenExpiration(this.startupInfo.token, '/portal-service/token-new'); } } else if (methodName === Verbs.sendAppSettingName) { if (this.getAppSettingCallback) { this.getAppSettingCallback(data); this.getAppSettingCallback = null; } } else if (methodName === Verbs.sendNotificationStarted) { this.notificationStartStream.next(data); } else if (methodName === Verbs.sendInputs) { if (!this.startupInfo) { return; } this.startupInfo.resourceId = data.resourceId; this.startupInfoObservable.next(this.startupInfo); } else if (methodName === Verbs.sendData) { this.operationStream.next(data); } else if (methodName === EventVerbs.siteUpdated) { const siteUpdatedMessage: EventMessage<void> = data; this._broadcastService.broadcastEvent(BroadcastEvent.SiteUpdated, siteUpdatedMessage); } else if (methodName === EventVerbs.planUpdated) { const planUpdatedMessage: EventMessage<void> = data; this._broadcastService.broadcastEvent(BroadcastEvent.PlanUpdated, planUpdatedMessage); } else if (methodName === EventVerbs.slotSwap) { const slotSwapMessage: EventMessage<SlotSwapInfo> = data; this._broadcastService.broadcastEvent(BroadcastEvent.SlotSwap, slotSwapMessage); } else if (methodName === EventVerbs.slotNew) { const slotNewMessage: EventMessage<SlotNewInfo> = data; this._broadcastService.broadcastEvent(BroadcastEvent.SlotNew, slotNewMessage); } else if (methodName === EventVerbs.sendByosSelection) { const byosConfiguration: EventMessage<ByosData> = { metadata: data, resourceId: data.appResourceId, }; this._broadcastService.broadcastEvent(BroadcastEvent.ByosConfigReceived, byosConfiguration); } } private logTokenExpiration(token: string, eventId: string) { const jwt = Jwt.tryParseJwt(this.startupInfo.token); this._aiService.trackEvent(eventId, { expire: jwt ? new Date(jwt.exp).toISOString() : '', }); } private _packageData(data: any) { data.frameId = this.frameId; return JSON.stringify(data); } private postMessage(verb: string, data: string) { if (Url.getParameterByName(null, 'appsvc.bladetype') === 'appblade') { window.parent.postMessage( <Data>{ signature: this.portalSignature, kind: verb, data: data, }, this.shellSrc ); } else { window.parent.postMessage( <Data>{ signature: this.portalSignatureFrameBlade, kind: verb, data: data, }, this.shellSrc ); } } }
the_stack
import { ClassType, JsonAppendOptions, JsonClassTypeOptions, JsonDecoratorOptions, JsonFilterOptions, JsonFormatOptions, JsonIdentityInfoOptions, JsonIdentityReferenceOptions, JsonIgnorePropertiesOptions, JsonIncludeOptions, JsonNamingOptions, JsonPropertyOptions, JsonPropertyOrderOptions, JsonRootNameOptions, JsonSerializeOptions, JsonStringifierContext, JsonStringifierFilterOptions, JsonStringifierTransformerContext, JsonSubTypesOptions, JsonTypeIdResolverOptions, JsonTypeInfoOptions, JsonViewOptions, InternalDecorators, JsonValueOptions, JsonUnwrappedOptions, JsonGetterOptions, JsonAnyGetterOptions, JsonTypeIdOptions, JsonTypeNameOptions, ClassList } from '../@types'; import { JsonPropertyAccess, JsonIncludeType, JsonTypeInfoAs, JsonTypeInfoId, JsonFormatShape, ObjectIdGenerator, PropertyNamingStrategy, JsonFilterType } from '../decorators'; import { castObjLiteral, classHasOwnProperty, classPropertiesToVirtualPropertiesMapping, getClassProperties, getDeepestClass, getDefaultPrimitiveTypeValue, getDefaultValue, getMetadata, getObjectKeysWithPropertyDescriptorNames, hasMetadata, isConstructorPrimitiveType, isIterableNoMapNoString, isObjLiteral, isSameConstructor, isSameConstructorOrExtensionOf, isSameConstructorOrExtensionOfNoObject, isValueEmpty, isVariablePrimitiveType, makeMetadataKeysWithContext, mapVirtualPropertiesToClassProperties, sortMappersByOrder } from '../util'; // import * as moment from 'moment'; // import {v1 as uuidv1, v3 as uuidv3, v4 as uuidv4, v5 as uuidv5} from 'uuid'; import {JacksonError} from './JacksonError'; import * as cloneDeep from 'lodash.clonedeep'; import * as clone from 'lodash.clone'; import {DefaultSerializationFeatureValues} from '../databind'; /** * Json Stringifier Global Context used by {@link JsonStringifier.transform} to store global information. */ interface JsonStringifierGlobalContext { /** * WeakMap used to track all objects by {@link JsonIdentityInfo}. */ globalValueAlreadySeen: WeakMap<any, any>; /** * Integer sequence generator counter used by {@link JsonIdentityInfo}. */ intSequenceGenerator: number; } /** * JsonStringifier provides functionality for writing JSON. * It is also highly customizable to work both with different styles of JSON content, * and to support more advanced Object concepts such as polymorphism and Object identity. */ export class JsonStringifier<T> { /** * Default context to use during serialization. */ defaultContext: JsonStringifierContext; /** * * @param defaultContext - Default context to use during serialization. */ constructor(defaultContext: JsonStringifierContext = JsonStringifier.makeDefaultContext()) { this.defaultContext = defaultContext; } /** * Make a default {@link JsonStringifierContext}. */ static makeDefaultContext(): JsonStringifierContext { return { mainCreator: null, features: { serialization: { ...DefaultSerializationFeatureValues } }, serializers: [], decoratorsEnabled: {}, withViews: null, forType: new Map(), withContextGroups: [], _internalDecorators: new Map(), _propertyParentCreator: null, attributes: {}, filters: {}, format: null, dateLibrary: null, uuidLibrary: null }; } /** * Merge multiple {@link JsonStringifierContext} into one. * Array direct properties will be concatenated, instead, Map and Object Literal direct properties will be merged. * All the other properties, such as {@link JsonStringifierContext.mainCreator}, will be completely replaced. * * @param contexts - list of contexts to be merged. */ static mergeContexts(contexts: JsonStringifierContext[]): JsonStringifierContext { const finalContext = JsonStringifier.makeDefaultContext(); for (const context of contexts) { if (context == null) { continue; } if (context.mainCreator != null) { finalContext.mainCreator = context.mainCreator; } if (context.decoratorsEnabled != null) { finalContext.decoratorsEnabled = { ...finalContext.decoratorsEnabled, ...context.decoratorsEnabled }; } if (context.withViews != null) { finalContext.withViews = context.withViews; } if (context.withContextGroups != null) { finalContext.withContextGroups = finalContext.withContextGroups.concat(context.withContextGroups); } if (context.serializers != null) { finalContext.serializers = finalContext.serializers.concat(context.serializers); } if (context.features != null && context.features.serialization != null) { finalContext.features.serialization = { ...finalContext.features.serialization, ...context.features.serialization }; } if (context.filters != null) { finalContext.filters = { ...finalContext.filters, ...context.filters }; } if (context.attributes != null) { finalContext.attributes = { ...finalContext.attributes, ...context.attributes }; } if (context.format != null) { finalContext.format = context.format; } if (context.forType != null) { finalContext.forType = new Map([ ...finalContext.forType, ...context.forType] ); } if (context.dateLibrary != null) { finalContext.dateLibrary = context.dateLibrary; } if (context.uuidLibrary != null) { finalContext.uuidLibrary = context.uuidLibrary; } if (context._internalDecorators != null) { finalContext._internalDecorators = new Map([ ...finalContext._internalDecorators, ...context._internalDecorators] ); } if (context._propertyParentCreator != null) { finalContext._propertyParentCreator = context._propertyParentCreator; } } finalContext.serializers = sortMappersByOrder(finalContext.serializers); return finalContext; } /** * Method for serializing a JavaScript object or a value to a JSON string. * * @param obj - the JavaScript object or value to be serialized. * @param context - the context to be used during serialization. */ stringify(obj: T, context?: JsonStringifierContext): string { const preProcessedObj = this.transform(obj, context); return JSON.stringify(preProcessedObj, null, context.format); } /** * Method for applying json decorators to a JavaScript object/value. * It returns a JavaScript object/value with json decorators applied and ready to be JSON serialized. * * @param value - the JavaScript object or value to be preprocessed. * @param context - the context to be used during serialization preprocessing. */ transform(value: any, context?: JsonStringifierContext): any { const globalContext: JsonStringifierGlobalContext = { globalValueAlreadySeen: new WeakMap<any, any>(), intSequenceGenerator: 1 }; context = JsonStringifier.mergeContexts([this.defaultContext, context]); let newContext: JsonStringifierTransformerContext = this.convertStringifierContextToTransformerContext(context); newContext.mainCreator = (newContext.mainCreator && newContext.mainCreator[0] !== Object) ? newContext.mainCreator : [(value != null) ? (value.constructor as ObjectConstructor) : Object]; newContext._propertyParentCreator = newContext.mainCreator[0]; newContext = cloneDeep(newContext); const currentMainCreator = newContext.mainCreator[0]; value = castObjLiteral(currentMainCreator, value); const preProcessedObj = this.deepTransform('', value, newContext, globalContext, new Map<any, any>()); return preProcessedObj; } /** * Recursive {@link JsonStringifier.transform}. * * @param key - key name representing the object property being preprocessed. * @param value - the JavaScript object or value to preprocessed. * @param context - the context to be used during serialization preprocessing. * @param globalContext - the global context to be used during serialization preprocessing. * @param valueAlreadySeen - Map used to manage object circular references. */ private deepTransform(key: string, value: any, context: JsonStringifierTransformerContext, globalContext: JsonStringifierGlobalContext, valueAlreadySeen: Map<any, any>): any { context = { withContextGroups: [], features: { serialization: {} }, filters: {}, serializers: [], attributes: {}, _internalDecorators: new Map(), ...context }; context = cloneDeep(context); if (value != null && context._internalDecorators != null && context._internalDecorators.size > 0) { let target = context.mainCreator[0]; while (target.name && !context._internalDecorators.has(target)) { target = Object.getPrototypeOf(target); } if (context._internalDecorators.has(target)) { if (context._internalDecorators.get(target).depth === 0) { context._internalDecorators.delete(target); } else { context._internalDecorators.get(target).depth--; } } } if (context.forType && context.forType.has(context.mainCreator[0])) { context = { mainCreator: context.mainCreator, ...context, ...(context.forType.get(context.mainCreator[0])) }; context = cloneDeep(context); } const currentMainCreator = context.mainCreator[0]; value = this.invokeCustomSerializers(key, value, context); value = this.stringifyJsonSerializeClass(value, context); if (value == null && isConstructorPrimitiveType(context.mainCreator[0])) { value = this.getDefaultValue(context); } if (value != null && value.constructor === Number && isNaN(value as number) && context.features.serialization.WRITE_NAN_AS_ZERO) { value = 0; } else if (value === Infinity) { if (context.features.serialization.WRITE_POSITIVE_INFINITY_AS_NUMBER_MAX_SAFE_INTEGER) { value = Number.MAX_SAFE_INTEGER; } else if (context.features.serialization.WRITE_POSITIVE_INFINITY_AS_NUMBER_MAX_VALUE) { value = Number.MAX_VALUE; } } else if (value === -Infinity) { if (context.features.serialization.WRITE_NEGATIVE_INFINITY_AS_NUMBER_MIN_SAFE_INTEGER) { value = Number.MIN_SAFE_INTEGER; } else if (context.features.serialization.WRITE_NEGATIVE_INFINITY_AS_NUMBER_MIN_VALUE) { value = Number.MIN_VALUE; } } else if (value != null && value instanceof Date && context.features.serialization.WRITE_DATES_AS_TIMESTAMPS) { value = value.getTime(); } if (value != null) { const identity = globalContext.globalValueAlreadySeen.get(value); if (identity) { return identity; } value = this.stringifyJsonFormatClass(value, context); if (BigInt && isSameConstructorOrExtensionOfNoObject(value.constructor, BigInt)) { return value.toString() + 'n'; } else if (value instanceof RegExp) { const replacement = value.toString(); return replacement.substring(1, replacement.length - 1); } else if (value instanceof Date) { return value; } else if (value instanceof Map || (isObjLiteral(value) && currentMainCreator === Object)) { value = this.stringifyMapAndObjLiteral(key, value, context, globalContext, new Map(valueAlreadySeen)); } else if (typeof value === 'object' && !isIterableNoMapNoString(value)) { // Infinite recursion is already handled by JSON.stringify(); // if (valueAlreadySeen.has(value)) { // throw new JacksonError(`Infinite recursion on key "${key}" of type "${currentMainCreator.name}"`); // } valueAlreadySeen.set(value, (identity) ? identity : null); let replacement = {}; const jsonValueOptions: JsonValueOptions = getMetadata('JsonValue', context.mainCreator[0], null, context); if (jsonValueOptions) { let jsonValue = this.stringifyJsonValue(value, context); const newContext: JsonStringifierTransformerContext = cloneDeep(context); let newMainCreator; const jsonClass: JsonClassTypeOptions = getMetadata('JsonClassType', currentMainCreator, jsonValueOptions._propertyKey, context); if (jsonClass && jsonClass.type) { newMainCreator = jsonClass.type(); } else { newMainCreator = [Object]; } if (jsonValue != null && jsonValue.constructor !== Object) { newMainCreator[0] = jsonValue.constructor; } newContext.mainCreator = newMainCreator; newContext._propertyParentCreator = newContext.mainCreator[0]; jsonValue = castObjLiteral(newContext.mainCreator[0], jsonValue); replacement = this.deepTransform(key, jsonValue, newContext, globalContext, new Map(valueAlreadySeen)); return replacement; } const isPrepJsonAppend = this.isPrependJsonAppend(context); if (isPrepJsonAppend) { this.stringifyJsonAppend(replacement, context); } let keys = getClassProperties(currentMainCreator, value, context, { withGettersAsProperty: true }); keys = this.stringifyJsonPropertyOrder(keys, context); const namingMap = new Map<string, string>(); for (const k of keys) { if (!this.stringifyHasJsonIgnore(k, context) && this.stringifyHasVirtualPropertyGetter(k, context) && this.stringifyHasJsonView(k, context) && !this.stringifyIsIgnoredByJsonPropertyAccess(k, context) && !this.stringifyHasJsonBackReference(k, context) && !this.stringifyIsPropertyKeyExcludedByJsonFilter(k, context) && classHasOwnProperty(currentMainCreator, k, value, context, {withGettersAsProperty: true})) { let newKey = this.stringifyJsonNaming(replacement, k, context); namingMap.set(k, newKey); // if it has a JsonIdentityReference, then we can skip all these methods because // the entire object will be replaced later by the identity value if (!this.hasJsonIdentityReferenceAlwaysAsId(context)) { const jsonIdentityInfo: JsonIdentityInfoOptions = getMetadata('JsonIdentityInfo', currentMainCreator, null, context); if (value === value[k] && jsonIdentityInfo == null) { if (context.features.serialization.FAIL_ON_SELF_REFERENCES) { // eslint-disable-next-line max-len throw new JacksonError(`Direct self-reference leading to cycle (through reference chain: ${currentMainCreator.name}["${k}"])`); } if (context.features.serialization.WRITE_SELF_REFERENCES_AS_NULL) { value[k] = null; } } this.propagateDecorators(value, k, context); replacement[newKey] = this.stringifyJsonGetter(value, k, context); if (this.stringifyHasJsonIgnoreTypeByKey(replacement, newKey, context)) { delete replacement[newKey]; continue; } if (!this.stringifyJsonInclude(replacement, newKey, context)) { namingMap.delete(k); delete replacement[newKey]; continue; } if (replacement[newKey] == null) { this.stringifyJsonSerializePropertyNull(replacement, k, newKey, context); } this.stringifyJsonSerializeProperty(replacement, k, newKey, context); if (replacement[newKey] != null) { replacement[newKey] = this.stringifyJsonFormatProperty(replacement, k, newKey, context); this.stringifyJsonRawValue(replacement, k, newKey, context); this.stringifyJsonFilter(replacement, value, k, newKey, context); newKey = this.stringifyJsonVirtualProperty(replacement, k, newKey, context, namingMap); if (!isIterableNoMapNoString(replacement[newKey])) { this.stringifyJsonUnwrapped(replacement, value, k, newKey, context, globalContext, new Map(valueAlreadySeen)); } } else { newKey = this.stringifyJsonVirtualProperty(replacement, k, newKey, context, namingMap); } } } } if (this.hasJsonIdentityReferenceAlwaysAsId(context)) { replacement = this.stringifyJsonIdentityReference(value, context); } else { this.stringifyJsonAnyGetter(replacement, value, context); if (!isPrepJsonAppend) { this.stringifyJsonAppend(replacement, context); } this.stringifyJsonIdentityInfo(replacement, value, context, globalContext); // eslint-disable-next-line guard-for-in for (const k in replacement) { const oldKey = namingMap.get(k); const newContext: JsonStringifierTransformerContext = cloneDeep(context); newContext._propertyParentCreator = currentMainCreator; let newMainCreator; const jsonClass: JsonClassTypeOptions = getMetadata('JsonClassType', currentMainCreator, oldKey, context); if (jsonClass && jsonClass.type) { newMainCreator = jsonClass.type(); } else { newMainCreator = [Object]; } if (replacement[k] != null && replacement[k].constructor !== Object) { newMainCreator[0] = replacement[k].constructor; } newContext.mainCreator = newMainCreator; replacement[k] = castObjLiteral(newContext.mainCreator[0], replacement[k]); replacement[k] = this.deepTransform(oldKey, replacement[k], newContext, globalContext, new Map(valueAlreadySeen)); } replacement = this.stringifyJsonRootName(replacement, context); replacement = this.stringifyJsonTypeInfo(replacement, value, context); } return replacement; } else if (isIterableNoMapNoString(value)) { const replacement = this.stringifyIterable(key, value, context, globalContext, new Map(valueAlreadySeen)); return replacement; } } return value; } /** * * @param context */ private convertStringifierContextToTransformerContext(context: JsonStringifierContext): JsonStringifierTransformerContext { const newContext: JsonStringifierTransformerContext = { mainCreator: context.mainCreator ? context.mainCreator() : [Object] }; for (const key in context) { if (key !== 'mainCreator') { newContext[key] = context[key]; } } return newContext; } /** * * @param key * @param value * @param context */ private invokeCustomSerializers(key: string, value: any, context: JsonStringifierTransformerContext): any { if (context.serializers) { const currentMainCreator = context.mainCreator[0]; for (const serializer of context.serializers) { if (serializer.type != null) { const classType = serializer.type(); if ( (value != null && typeof classType === 'string' && classType !== typeof value) || (typeof classType !== 'string' && currentMainCreator != null && !isSameConstructorOrExtensionOf(classType, currentMainCreator)) ) { continue; } } value = serializer.mapper(key, value, context); } } return value; } /** * * @param context */ private getDefaultValue(context: JsonStringifierTransformerContext): any | null { let defaultValue = null; const currentMainCreator = context.mainCreator[0]; if (currentMainCreator === String && (context.features.serialization.SET_DEFAULT_VALUE_FOR_PRIMITIVES_ON_NULL || context.features.serialization.SET_DEFAULT_VALUE_FOR_STRING_ON_NULL) ) { defaultValue = getDefaultPrimitiveTypeValue(String); } else if (currentMainCreator === Number && (context.features.serialization.SET_DEFAULT_VALUE_FOR_PRIMITIVES_ON_NULL || context.features.serialization.SET_DEFAULT_VALUE_FOR_NUMBER_ON_NULL) ) { defaultValue = getDefaultPrimitiveTypeValue(Number); } else if (currentMainCreator === Boolean && (context.features.serialization.SET_DEFAULT_VALUE_FOR_PRIMITIVES_ON_NULL || context.features.serialization.SET_DEFAULT_VALUE_FOR_BOOLEAN_ON_NULL) ) { defaultValue = getDefaultPrimitiveTypeValue(Boolean); } else if (BigInt && currentMainCreator === BigInt && (context.features.serialization.SET_DEFAULT_VALUE_FOR_PRIMITIVES_ON_NULL || context.features.serialization.SET_DEFAULT_VALUE_FOR_BIGINT_ON_NULL) ) { defaultValue = getDefaultPrimitiveTypeValue(BigInt); } return defaultValue; } /** * Propagate decorators to class properties, * only for the first level (depth) of recursion. * * Used, for example, in case of decorators applied on an iterable, such as an Array. * In this case, the decorators are applied to each item of the iterable and not on the iterable itself.JsonFormat * @param obj * @param key * @param context */ private propagateDecorators(obj: any, key: string, context: JsonStringifierTransformerContext): void { const currentMainCreator = context.mainCreator[0]; const jsonClass: JsonClassTypeOptions = getMetadata('JsonClassType', currentMainCreator, key, context); // Decorators list that can be propagated const metadataKeys = [ 'JsonIgnoreProperties', 'JsonTypeInfo', 'JsonSubTypes', 'JsonTypeIdResolver', 'JsonFilter', 'JsonIdentityInfo', 'JsonIdentityReference', 'JsonPropertyOrder' ]; const decoratorsNameFound = []; const decoratorsToBeApplied: InternalDecorators = { depth: 1 }; let deepestClass = null; if (jsonClass) { deepestClass = getDeepestClass(jsonClass.type()); } else { deepestClass = (obj[key] != null) ? obj[key].constructor : Object; } for (const metadataKey of metadataKeys) { const jsonDecoratorOptions: JsonDecoratorOptions = getMetadata(metadataKey, currentMainCreator, key, context); if (jsonDecoratorOptions) { const metadataKeysWithContext = makeMetadataKeysWithContext(metadataKey, {contextGroups: jsonDecoratorOptions.contextGroups}); for (const metadataKeyWithContext of metadataKeysWithContext) { decoratorsToBeApplied[metadataKeyWithContext] = jsonDecoratorOptions; } decoratorsNameFound.push(metadataKey); } } if (deepestClass != null && decoratorsNameFound.length > 0) { context._internalDecorators.set(deepestClass, decoratorsToBeApplied); } } /** * * @param key * @param context */ private stringifyHasVirtualPropertyGetter(key: string, context: JsonStringifierTransformerContext): any { const currentMainCreator = context.mainCreator[0]; const jsonVirtualProperty: JsonPropertyOptions | JsonGetterOptions = getMetadata('JsonVirtualProperty:' + key, currentMainCreator, null, context); if (jsonVirtualProperty && jsonVirtualProperty._descriptor != null) { return typeof jsonVirtualProperty._descriptor.value === 'function' || jsonVirtualProperty._descriptor.get != null || jsonVirtualProperty._descriptor.set == null; } return true; } /** * * @param obj * @param key * @param context */ private stringifyJsonGetter(obj: any, key: string, context: JsonStringifierTransformerContext): any { const currentMainCreator = context.mainCreator[0]; const jsonVirtualProperty: JsonPropertyOptions | JsonGetterOptions = getMetadata('JsonVirtualProperty:' + key, currentMainCreator, null, context); const jsonIgnoreProperties: JsonIgnorePropertiesOptions = getMetadata('JsonIgnoreProperties', currentMainCreator, null, context); if (jsonVirtualProperty && !(jsonIgnoreProperties && !jsonIgnoreProperties.allowGetters && jsonIgnoreProperties.value.includes(jsonVirtualProperty.value)) ) { return (jsonVirtualProperty._descriptor != null && typeof jsonVirtualProperty._descriptor.value === 'function') ? obj[key]() : obj[key]; } return obj[key]; } /** * * @param replacement * @param obj * @param context */ private stringifyJsonAnyGetter(replacement: any, obj: any, context: JsonStringifierTransformerContext): void { const currentMainCreator = context.mainCreator[0]; const jsonAnyGetter: JsonAnyGetterOptions = getMetadata('JsonAnyGetter', currentMainCreator, null, context); if (jsonAnyGetter && obj[jsonAnyGetter._propertyKey]) { const map = (typeof obj[jsonAnyGetter._propertyKey] === 'function') ? obj[jsonAnyGetter._propertyKey]() : obj[jsonAnyGetter._propertyKey]; if (!(map instanceof Map) && !isObjLiteral(map)) { // eslint-disable-next-line max-len throw new JacksonError(`Property ${currentMainCreator.name}["${jsonAnyGetter._propertyKey}"] decorated with @JsonAnyGetter() returned a "${map.constructor.name}": expected "Map" or "Object Literal".`); } if (map instanceof Map) { for (const [k, value] of map) { replacement[k] = value; } } else { for (const k in map) { if (Object.hasOwnProperty.call(map, k)) { replacement[k] = map[k]; } } } if (jsonAnyGetter.value) { delete replacement[jsonAnyGetter.value]; } } } /** * * @param keys * @param context */ private stringifyJsonPropertyOrder(keys: string[], context: JsonStringifierTransformerContext): string[] { const currentMainCreator = context.mainCreator[0]; const jsonPropertyOrder: JsonPropertyOrderOptions = getMetadata('JsonPropertyOrder', currentMainCreator, null, context); if (context.features.serialization.SORT_PROPERTIES_ALPHABETICALLY || jsonPropertyOrder) { const classProperties = (jsonPropertyOrder) ? mapVirtualPropertiesToClassProperties(currentMainCreator, jsonPropertyOrder.value, context, {checkGetters: true}) : []; let remainingKeys = keys.filter(key => !classProperties.includes(key)); if (context.features.serialization.SORT_PROPERTIES_ALPHABETICALLY || jsonPropertyOrder.alphabetic) { const remainingKeysToVirtualPropertiesMapping = classPropertiesToVirtualPropertiesMapping(currentMainCreator, remainingKeys, context); const remainingVirtualKeysOrdered = new Map( [...remainingKeysToVirtualPropertiesMapping.entries()] .sort((a, b) => a[1] > b[1] ? 1 : -1) ); const remainingKeysOrdered = []; for (const [classProperty, virtualProperty] of remainingVirtualKeysOrdered) { remainingKeysOrdered.push(classProperty); } remainingKeys = remainingKeysOrdered; } keys = classProperties.concat(remainingKeys); } return keys; } /** * * @param oldKey * @param context */ private stringifyIsIgnoredByJsonPropertyAccess(oldKey: string, context: JsonStringifierTransformerContext): boolean { const jsonProperty: JsonPropertyOptions = getMetadata('JsonProperty', context.mainCreator[0], oldKey, context); if (jsonProperty) { return jsonProperty.access === JsonPropertyAccess.WRITE_ONLY; } return false; } /** * * @param replacement * @param oldKey * @param newKey * @param context * @param namingMap */ private stringifyJsonVirtualProperty(replacement: any, oldKey: string, newKey: string, context: JsonStringifierTransformerContext, namingMap: Map<string, string>): string { const jsonVirtualProperty: JsonPropertyOptions | JsonGetterOptions = getMetadata('JsonVirtualProperty:' + oldKey, context.mainCreator[0], null, context); if (jsonVirtualProperty && jsonVirtualProperty.value !== oldKey) { const newKeyUpdated = this.stringifyJsonNaming(replacement, jsonVirtualProperty.value, context); namingMap.set(oldKey, newKeyUpdated); replacement[newKeyUpdated] = replacement[newKey]; delete replacement[newKey]; return newKeyUpdated; } return newKey; } /** * * @param replacement * @param oldKey * @param newKey * @param context */ private stringifyJsonRawValue(replacement: any, oldKey: string, newKey: string, context: JsonStringifierTransformerContext): void { const jsonRawValue = hasMetadata('JsonRawValue', context.mainCreator[0], oldKey, context); if (jsonRawValue) { replacement[newKey] = JSON.parse(replacement[newKey]); } } /** * * @param obj * @param context */ private stringifyJsonValue(obj: any, context: JsonStringifierTransformerContext): null | any { const jsonValue: JsonValueOptions = getMetadata('JsonValue', context.mainCreator[0], null, context); if (jsonValue) { return (typeof obj[jsonValue._propertyKey] === 'function') ? obj[jsonValue._propertyKey]() : obj[jsonValue._propertyKey]; } return null; } /** * * @param replacement * @param context */ private stringifyJsonRootName(replacement: any, context: JsonStringifierTransformerContext): any { if (context.features.serialization.WRAP_ROOT_VALUE) { const jsonRootName: JsonRootNameOptions = getMetadata('JsonRootName', context.mainCreator[0], null, context); const wrapKey = (jsonRootName && jsonRootName.value) ? jsonRootName.value : context.mainCreator[0].constructor.name; const newReplacement = {}; newReplacement[wrapKey] = replacement; return newReplacement; } return replacement; } /** * * @param obj * @param context */ private stringifyJsonSerializeClass(obj: any, context: JsonStringifierTransformerContext): any { const jsonSerialize: JsonSerializeOptions = getMetadata('JsonSerialize', context.mainCreator[0], null, context); if (jsonSerialize && jsonSerialize.using) { return jsonSerialize.using(obj, context); } return obj; } /** * * @param replacement * @param oldKey * @param newKey * @param context */ private stringifyJsonSerializeProperty(replacement: any, oldKey: string, newKey: string, context: JsonStringifierTransformerContext): void { const jsonSerialize: JsonSerializeOptions = getMetadata('JsonSerialize', context.mainCreator[0], oldKey, context); if (jsonSerialize && jsonSerialize.using) { replacement[newKey] = jsonSerialize.using(replacement[newKey], context); } } /** * * @param replacement * @param oldKey * @param newKey * @param context */ private stringifyJsonSerializePropertyNull(replacement: any, oldKey: string, newKey: string, context: JsonStringifierTransformerContext): void { const jsonSerialize: JsonSerializeOptions = getMetadata('JsonSerialize', context.mainCreator[0], oldKey, context); if (jsonSerialize && jsonSerialize.nullsUsing) { replacement[newKey] = jsonSerialize.nullsUsing(context); } } /** * * @param key * @param context */ private stringifyHasJsonIgnore(key: string, context: JsonStringifierTransformerContext): boolean { const currentMainCreator = context.mainCreator[0]; const hasJsonIgnore = hasMetadata('JsonIgnore', currentMainCreator, key, context); if (!hasJsonIgnore) { const jsonIgnoreProperties: JsonIgnorePropertiesOptions = getMetadata('JsonIgnoreProperties', currentMainCreator, null, context); if (jsonIgnoreProperties) { const jsonVirtualProperty: JsonPropertyOptions | JsonGetterOptions = getMetadata('JsonVirtualProperty:' + key, currentMainCreator, null, context); if (jsonVirtualProperty && jsonIgnoreProperties.value.includes(jsonVirtualProperty.value)) { if (jsonVirtualProperty._descriptor != null && typeof jsonVirtualProperty._descriptor.value === 'function' && jsonIgnoreProperties.allowGetters) { return false; } return true; } return jsonIgnoreProperties.value.includes(key); } } return hasJsonIgnore; } /** * * @param obj * @param key * @param context */ private stringifyJsonInclude(obj: any, key: string, context: JsonStringifierTransformerContext): boolean { const currentMainCreator = context.mainCreator[0]; let jsonInclude: JsonIncludeOptions = getMetadata('JsonInclude', currentMainCreator, key, context); if (!jsonInclude) { jsonInclude = getMetadata('JsonInclude', currentMainCreator, null, context); jsonInclude = jsonInclude ? jsonInclude : context.features.serialization.DEFAULT_PROPERTY_INCLUSION; } if (jsonInclude) { const value = obj[key]; switch (jsonInclude.value) { case JsonIncludeType.NON_EMPTY: return !isValueEmpty(value); case JsonIncludeType.NON_NULL: return value != null; case JsonIncludeType.NON_DEFAULT: return value !== getDefaultValue(value) && !isValueEmpty(value); case JsonIncludeType.CUSTOM: return !jsonInclude.valueFilter(value); } } return true; } /** * * @param replacement * @param key * @param context */ private stringifyHasJsonIgnoreTypeByKey(replacement: any, key: string, context: JsonStringifierTransformerContext): boolean { const currentMainCreator = context.mainCreator[0]; let classType: ClassList<ClassType<any>>; const jsonClass: JsonClassTypeOptions = getMetadata('JsonClassType', currentMainCreator, key, context); if (jsonClass && jsonClass.type) { classType = jsonClass.type(); } else { classType = [Object]; } const value = replacement[key]; if (value != null && value.constructor !== Object) { classType[0] = value.constructor; } return hasMetadata('JsonIgnoreType', classType[0], null, context); } /** * * @param value * @param key * @param context */ private stringifyHasJsonIgnoreTypeByValue(value: any, key: string, context: JsonStringifierTransformerContext): boolean { let classType: ClassList<ClassType<any>>; const jsonClass: JsonClassTypeOptions = getMetadata('JsonClassType', context._propertyParentCreator, key, context); if (jsonClass && jsonClass.type) { classType = jsonClass.type(); } else { classType = [Object]; } if (value != null && value.constructor !== Object) { classType[0] = value.constructor; } return hasMetadata('JsonIgnoreType', classType[0], null, context); } /** * * @param key * @param context */ private stringifyHasJsonBackReference(key: string, context: JsonStringifierTransformerContext): boolean { return hasMetadata('JsonBackReference', context.mainCreator[0], key, context); } /** * * @param replacement * @param obj * @param context */ private stringifyJsonTypeInfo(replacement: any, obj: any, context: JsonStringifierTransformerContext): any { const currentMainCreator = context.mainCreator[0]; const jsonTypeInfo: JsonTypeInfoOptions = getMetadata('JsonTypeInfo', currentMainCreator, null, context); if (jsonTypeInfo) { let jsonTypeName: string; const jsonTypeIdResolver: JsonTypeIdResolverOptions = getMetadata('JsonTypeIdResolver', currentMainCreator, null, context); if (jsonTypeIdResolver && jsonTypeIdResolver.resolver) { jsonTypeName = jsonTypeIdResolver.resolver.idFromValue(obj, context); } if (!jsonTypeName) { const jsonTypeId: JsonTypeIdOptions = getMetadata('JsonTypeId', currentMainCreator, null, context); if (jsonTypeId) { if (typeof obj[jsonTypeId._propertyKey] === 'function') { jsonTypeName = obj[jsonTypeId._propertyKey](); } else { jsonTypeName = obj[jsonTypeId._propertyKey]; delete replacement[jsonTypeId._propertyKey]; } } } if (!jsonTypeName) { const jsonSubTypes: JsonSubTypesOptions = getMetadata('JsonSubTypes', currentMainCreator, null, context); if (jsonSubTypes && jsonSubTypes.types) { for (const subType of jsonSubTypes.types) { if (subType.name && isSameConstructor(subType.class(), currentMainCreator)) { jsonTypeName = subType.name; break; } } } } if (!jsonTypeName) { const jsonTypeNameOptions: JsonTypeNameOptions = getMetadata('JsonTypeName', currentMainCreator, null, context); if (jsonTypeNameOptions && jsonTypeNameOptions.value != null && jsonTypeNameOptions.value.trim() !== '') { jsonTypeName = jsonTypeNameOptions.value; } } if (!jsonTypeName) { switch (jsonTypeInfo.use) { case JsonTypeInfoId.NAME: jsonTypeName = currentMainCreator.name; break; } } let newReplacement: any; switch (jsonTypeInfo.include) { case JsonTypeInfoAs.PROPERTY: replacement[jsonTypeInfo.property] = jsonTypeName; break; case JsonTypeInfoAs.WRAPPER_OBJECT: newReplacement = {}; newReplacement[jsonTypeName] = replacement; replacement = newReplacement; break; case JsonTypeInfoAs.WRAPPER_ARRAY: newReplacement = [jsonTypeName, replacement]; replacement = newReplacement; break; } } return replacement; } /** * * @param replacement * @param oldKey * @param newKey * @param context */ private stringifyJsonFormatProperty(replacement: any, oldKey: string, newKey: string, context: JsonStringifierTransformerContext): any { const jsonFormat: JsonFormatOptions = getMetadata('JsonFormat', context.mainCreator[0], oldKey, context); if (jsonFormat) { return this.stringifyJsonFormat(jsonFormat, replacement[newKey], context); } return replacement[newKey]; } /** * * @param obj * @param context */ private stringifyJsonFormatClass(obj: any, context: JsonStringifierTransformerContext): any { const jsonFormat: JsonFormatOptions = getMetadata('JsonFormat', context.mainCreator[0], null, context); if (jsonFormat) { return this.stringifyJsonFormat(jsonFormat, obj, context); } return obj; } /** * * @param jsonFormat * @param replacement * @param context */ private stringifyJsonFormat(jsonFormat: JsonFormatOptions, replacement: any, context: JsonStringifierTransformerContext): any { let formattedValue = replacement; switch (jsonFormat.shape) { case JsonFormatShape.ARRAY: if (typeof replacement === 'object') { if (replacement instanceof Set || replacement instanceof Map) { formattedValue = [...replacement]; } else { formattedValue = Object.values(replacement); } } else { formattedValue = [replacement]; } break; case JsonFormatShape.BOOLEAN: formattedValue = !!replacement; break; case JsonFormatShape.NUMBER_FLOAT: if (replacement instanceof Date) { formattedValue = parseFloat(replacement.getTime().toString()); } else { formattedValue = parseFloat(replacement); } break; case JsonFormatShape.NUMBER_INT: if (replacement instanceof Date) { formattedValue = replacement.getTime(); } else { formattedValue = parseInt(replacement, 10); } break; case JsonFormatShape.OBJECT: if (replacement instanceof Set) { formattedValue = Object.assign({}, [...replacement]); } else if (replacement instanceof Map) { const newValue = {}; for (const [k, val] of replacement) { newValue[k] = val; } formattedValue = newValue; } else { formattedValue = Object.assign({}, replacement); } break; case JsonFormatShape.SCALAR: if (!isVariablePrimitiveType(replacement)) { formattedValue = null; } break; case JsonFormatShape.STRING: if (replacement instanceof Date) { const locale = jsonFormat.locale; const timezone = (jsonFormat.timezone) ? { timeZone: jsonFormat.timezone } : {}; const dateLibrary = jsonFormat.dateLibrary != null ? jsonFormat.dateLibrary : context.dateLibrary; if (dateLibrary == null) { // eslint-disable-next-line max-len throw new JacksonError('No date library has been set. To be able to use @JsonFormat() on class properties of type "Date" with JsonFormatShape.STRING, a date library needs to be set. Date libraries supported: "https://github.com/moment/moment", "https://github.com/iamkun/dayjs/".'); } formattedValue = dateLibrary( new Date(replacement.toLocaleString('en-US', timezone))).locale(locale).format(jsonFormat.pattern); } else { if (replacement != null && replacement.constructor === Number) { if (jsonFormat.radix != null && jsonFormat.radix.constructor === Number) { formattedValue = replacement.toString(jsonFormat.radix); } else if (jsonFormat.toExponential != null && jsonFormat.toExponential.constructor === Number) { formattedValue = replacement.toExponential(jsonFormat.toExponential); } else if (jsonFormat.toFixed != null && jsonFormat.toFixed.constructor === Number) { formattedValue = replacement.toFixed(jsonFormat.toFixed); } else if (jsonFormat.toPrecision != null && jsonFormat.toPrecision.constructor === Number) { formattedValue = replacement.toPrecision(jsonFormat.toPrecision); } else { formattedValue = replacement.toString(); } } else { formattedValue = replacement.toString(); } } break; } return formattedValue; } /** * * @param key * @param context */ private stringifyHasJsonView(key: string, context: JsonStringifierTransformerContext): boolean { const currentMainCreator = context.mainCreator[0]; if (context.withViews) { let jsonView: JsonViewOptions = getMetadata('JsonView', currentMainCreator, key, context); if (!jsonView) { jsonView = getMetadata('JsonView', currentMainCreator, null, context); } if (jsonView && jsonView.value) { const views = jsonView.value(); const withViews = context.withViews(); for (const view of views) { for (const withView of withViews) { if (isSameConstructorOrExtensionOf(view, withView)) { return true; } } } return false; } return context.features.serialization.DEFAULT_VIEW_INCLUSION; } return true; } /** * * @param replacement * @param obj * @param oldKey * @param newKey * @param context * @param globalContext * @param valueAlreadySeen */ private stringifyJsonUnwrapped(replacement: any, obj: any, oldKey: string, newKey: string, context: JsonStringifierTransformerContext, globalContext: JsonStringifierGlobalContext, valueAlreadySeen: Map<any, any>): void { const currentMainCreator = context.mainCreator[0]; const jsonUnwrapped: JsonUnwrappedOptions = getMetadata('JsonUnwrapped', currentMainCreator, oldKey, context); if (jsonUnwrapped) { let objValue = (typeof obj[oldKey] === 'function') ? obj[oldKey]() : obj[oldKey]; const newContext = cloneDeep(context); let newMainCreator; const jsonClass: JsonClassTypeOptions = getMetadata('JsonClassType', currentMainCreator, oldKey, context); if (jsonClass && jsonClass.type) { newMainCreator = jsonClass.type(); } else { newMainCreator = [Object]; } if (obj[oldKey] != null && objValue.constructor !== Object) { newMainCreator[0] = objValue.constructor; } newContext.mainCreator = newMainCreator; const hasJsonTypeInfo = (typeof objValue === 'object') ? hasMetadata('JsonTypeInfo', newContext.mainCreator, null, newContext) : false; if (hasJsonTypeInfo) { // eslint-disable-next-line max-len throw new JacksonError(`Unwrapped property requires use of type information: cannot serialize (through reference chain: ${currentMainCreator.name}["${oldKey}"])`); } const prefix = (jsonUnwrapped.prefix != null) ? jsonUnwrapped.prefix : ''; const suffix = (jsonUnwrapped.suffix != null) ? jsonUnwrapped.suffix : ''; objValue = castObjLiteral(newContext.mainCreator[0], objValue); const objTransformed = this.deepTransform(oldKey, objValue, newContext, globalContext, new Map(valueAlreadySeen)); const keys = Object.keys(objTransformed); for (const objKey of keys) { const newKeyWrapped = prefix + objKey + suffix; replacement[newKeyWrapped] = objTransformed[objKey]; } delete replacement[newKey]; } } /** * * @param replacement * @param obj * @param context * @param globalContext */ private stringifyJsonIdentityInfo(replacement: any, obj: any, context: JsonStringifierTransformerContext, globalContext: JsonStringifierGlobalContext): void { const currentMainCreator = context.mainCreator[0]; const jsonIdentityInfo: JsonIdentityInfoOptions = getMetadata('JsonIdentityInfo', currentMainCreator, null, context); if (jsonIdentityInfo) { if (globalContext.globalValueAlreadySeen.has(obj)) { replacement[jsonIdentityInfo.property] = globalContext.globalValueAlreadySeen.get(obj); } else { if (typeof jsonIdentityInfo.generator === 'function') { replacement[jsonIdentityInfo.property] = jsonIdentityInfo.generator(obj); } else { let uuidLibrary; if (jsonIdentityInfo.generator === ObjectIdGenerator.UUIDv5Generator || jsonIdentityInfo.generator === ObjectIdGenerator.UUIDv4Generator || jsonIdentityInfo.generator === ObjectIdGenerator.UUIDv3Generator || jsonIdentityInfo.generator === ObjectIdGenerator.UUIDv1Generator) { uuidLibrary = jsonIdentityInfo.uuidLibrary != null ? jsonIdentityInfo.uuidLibrary : context.uuidLibrary; if (uuidLibrary == null) { // eslint-disable-next-line max-len throw new JacksonError('No UUID library has been set. To be able to use @JsonIdentityInfo() with any UUID ObjectIdGenerator, an UUID library needs to be set. UUID library supported: "https://github.com/uuidjs/uuid".'); } } switch (jsonIdentityInfo.generator) { case ObjectIdGenerator.IntSequenceGenerator: globalContext.intSequenceGenerator++; replacement[jsonIdentityInfo.property] = globalContext.intSequenceGenerator; break; case ObjectIdGenerator.None: replacement[jsonIdentityInfo.property] = null; break; case ObjectIdGenerator.PropertyGenerator: if (!Object.hasOwnProperty.call(replacement, jsonIdentityInfo.property)) { // eslint-disable-next-line max-len throw new JacksonError(`Invalid Object Id definition for "${currentMainCreator.name}": cannot find property with name "${jsonIdentityInfo.property}"`); } break; case ObjectIdGenerator.UUIDv5Generator: const uuidv5Options = jsonIdentityInfo.uuidv5; const uuidv5Args: any[] = [uuidv5Options.name, uuidv5Options.namespace]; if (uuidv5Options.buffer != null) { uuidv5Args.push(uuidv5Options.buffer); if (uuidv5Options.offset != null) { uuidv5Args.push(uuidv5Options.offset); } } replacement[jsonIdentityInfo.property] = uuidLibrary.v5(...uuidv5Args); break; case ObjectIdGenerator.UUIDv4Generator: const uuidv4Options = jsonIdentityInfo.uuidv4; const uuidv4Args: any[] = [uuidv4Options.options]; if (uuidv4Options.buffer != null) { uuidv4Args.push(uuidv4Options.buffer); if (uuidv4Options.offset != null) { uuidv4Args.push(uuidv4Options.offset); } } replacement[jsonIdentityInfo.property] = uuidLibrary.v4(...uuidv4Args); break; case ObjectIdGenerator.UUIDv3Generator: const uuidv3Options = jsonIdentityInfo.uuidv3; const uuidv3Args: any[] = [uuidv3Options.name, uuidv3Options.namespace]; if (uuidv3Options.buffer != null) { uuidv3Args.push(uuidv3Options.buffer); if (uuidv3Options.offset != null) { uuidv3Args.push(uuidv3Options.offset); } } replacement[jsonIdentityInfo.property] = uuidLibrary.v3(...uuidv3Args); break; case ObjectIdGenerator.UUIDv1Generator: const uuidv1Options = jsonIdentityInfo.uuidv1; const uuidv1Args: any[] = [uuidv1Options.options]; if (uuidv1Options.buffer != null) { uuidv1Args.push(uuidv1Options.buffer); if (uuidv1Options.offset != null) { uuidv1Args.push(uuidv1Options.offset); } } replacement[jsonIdentityInfo.property] = uuidLibrary.v1(...uuidv1Args); break; } } } if (!globalContext.globalValueAlreadySeen.has(obj)) { const objIdentifier = (typeof replacement[jsonIdentityInfo.property] === 'function') ? replacement[jsonIdentityInfo.property]() : replacement[jsonIdentityInfo.property]; globalContext.globalValueAlreadySeen.set(obj, objIdentifier); } } } /** * * @param context */ private hasJsonIdentityReferenceAlwaysAsId(context: JsonStringifierTransformerContext): boolean { const currentMainCreator = context.mainCreator[0]; const jsonIdentityInfo: JsonIdentityInfoOptions = getMetadata('JsonIdentityInfo', currentMainCreator, null, context); const jsonIdentityReference: JsonIdentityReferenceOptions = getMetadata('JsonIdentityReference', currentMainCreator, null, context); return jsonIdentityReference != null && jsonIdentityReference.alwaysAsId && jsonIdentityInfo != null; } /** * * @param obj * @param context */ private stringifyJsonIdentityReference(obj: any, context: JsonStringifierTransformerContext): any { const jsonIdentityInfo: JsonIdentityInfoOptions = getMetadata('JsonIdentityInfo', context.mainCreator[0], null, context); return obj[jsonIdentityInfo.property]; } /** * * @param key * @param iterableNoString * @param context * @param globalContext * @param valueAlreadySeen */ private stringifyIterable(key: string, iterableNoString: any, context: JsonStringifierTransformerContext, globalContext: JsonStringifierGlobalContext, valueAlreadySeen: Map<any, any>): any[] { const jsonSerialize: JsonSerializeOptions = getMetadata('JsonSerialize', context._propertyParentCreator, key, context); const iterable = [...iterableNoString]; const newIterable = []; for (let value of iterable) { const newContext = cloneDeep(context); let newMainCreator; if (context.mainCreator.length > 1) { newMainCreator = newContext.mainCreator[1]; } else { newMainCreator = [Object]; } if (value != null && value.constructor !== Object) { newMainCreator[0] = value.constructor; } newContext.mainCreator = newMainCreator; if (jsonSerialize && jsonSerialize.contentUsing) { value = jsonSerialize.contentUsing(value, newContext); } value = castObjLiteral(newContext.mainCreator[0], value); if (this.stringifyHasJsonIgnoreTypeByValue(value, key, newContext)) { continue; } newIterable.push(this.deepTransform(key, value, newContext, globalContext, new Map(valueAlreadySeen))); } return newIterable; } /** * * @param key * @param map * @param context * @param globalContext * @param valueAlreadySeen */ private stringifyMapAndObjLiteral(key: string, map: Map<any, any> | Record<string, any>, context: JsonStringifierTransformerContext, globalContext: JsonStringifierGlobalContext, valueAlreadySeen: Map<any, any>): any { const currentCreators = context.mainCreator; const jsonSerialize: JsonSerializeOptions = getMetadata('JsonSerialize', context._propertyParentCreator, key, context); let jsonInclude: JsonIncludeOptions = getMetadata('JsonInclude', context._propertyParentCreator, key, context); if (!jsonInclude) { jsonInclude = getMetadata('JsonInclude', context._propertyParentCreator, null, context); jsonInclude = jsonInclude ? jsonInclude : context.features.serialization.DEFAULT_PROPERTY_INCLUSION; } const newValue = {}; let mapKeys = (map instanceof Map) ? [...map.keys()] : getObjectKeysWithPropertyDescriptorNames(map, null, context); if (context.features.serialization.ORDER_MAP_AND_OBJECT_LITERAL_ENTRIES_BY_KEYS) { mapKeys = mapKeys.sort(); } const newContext = cloneDeep(context); if (currentCreators.length > 1 && currentCreators[1] instanceof Array) { newContext.mainCreator = currentCreators[1] as [ClassType<any>]; } else { newContext.mainCreator = [Object]; } const mapCurrentCreators = newContext.mainCreator; for (let mapKey of mapKeys) { let mapValue = (map instanceof Map) ? map.get(mapKey) : map[mapKey]; const keyNewContext = cloneDeep(newContext); const valueNewContext = cloneDeep(newContext); if (mapCurrentCreators[0] instanceof Array) { keyNewContext.mainCreator = mapCurrentCreators[0] as [ClassType<any>]; } else { keyNewContext.mainCreator = [mapCurrentCreators[0]] as [ClassType<any>]; } if (keyNewContext.mainCreator[0] === Object) { keyNewContext.mainCreator[0] = mapKey.constructor; } if (mapCurrentCreators.length > 1) { if (mapCurrentCreators[1] instanceof Array) { valueNewContext.mainCreator = mapCurrentCreators[1] as [ClassType<any>]; } else { valueNewContext.mainCreator = [mapCurrentCreators[1]] as [ClassType<any>]; } } else { valueNewContext.mainCreator = [Object]; } if (mapValue != null && mapValue.constructor !== Object && valueNewContext.mainCreator[0] === Object) { valueNewContext.mainCreator[0] = mapValue.constructor; } if (jsonSerialize && (jsonSerialize.contentUsing || jsonSerialize.keyUsing)) { mapKey = (jsonSerialize.keyUsing) ? jsonSerialize.keyUsing(mapKey, keyNewContext) : mapKey; mapValue = (jsonSerialize.contentUsing) ? jsonSerialize.contentUsing(mapValue, valueNewContext) : mapValue; if (mapKey != null && mapKey.constructor !== Object) { keyNewContext.mainCreator[0] = mapKey.constructor; } if (mapValue != null && mapValue.constructor !== Object) { valueNewContext.mainCreator[0] = mapValue.constructor; } } if (jsonInclude && jsonInclude.content != null && jsonInclude.content !== JsonIncludeType.ALWAYS) { switch (jsonInclude.content) { case JsonIncludeType.NON_EMPTY: if (isValueEmpty(mapValue)) { continue; } break; case JsonIncludeType.NON_NULL: if (mapValue == null) { continue; } break; case JsonIncludeType.NON_DEFAULT: if (mapValue === getDefaultValue(mapValue) || isValueEmpty(mapValue)) { continue; } break; case JsonIncludeType.CUSTOM: if (jsonInclude.contentFilter(mapValue)) { continue; } break; } } if (context.features.serialization.WRITE_DATE_KEYS_AS_TIMESTAMPS) { if (map instanceof Map && mapKey instanceof Date) { mapKey = mapKey.getTime(); } else if (!(map instanceof Map) && currentCreators[0] === Object && isSameConstructorOrExtensionOfNoObject(keyNewContext.mainCreator[0], Date)) { mapKey = (new keyNewContext.mainCreator[0](mapKey)).getTime(); } } mapValue = castObjLiteral(newContext.mainCreator[0], mapValue); if (this.stringifyHasJsonIgnoreTypeByValue(mapValue, key, valueNewContext)) { continue; } const mapValueStringified = this.deepTransform(mapKey, mapValue, valueNewContext, globalContext, new Map(valueAlreadySeen)); newValue[mapKey.toString()] = mapValueStringified; } return newValue; } /** * * @param filter * @param key * @param context */ private isPropertyKeyExcludedByJsonFilter(filter: JsonStringifierFilterOptions, key: string, context: JsonStringifierTransformerContext): boolean { if (filter.values == null) { return false; } const jsonProperty: JsonPropertyOptions = getMetadata('JsonProperty', context.mainCreator[0], key, context); switch (filter.type) { case JsonFilterType.FILTER_OUT_ALL_EXCEPT: return !filter.values.includes(key) && !(jsonProperty && filter.values.includes(jsonProperty.value)); case JsonFilterType.SERIALIZE_ALL: return false; case JsonFilterType.SERIALIZE_ALL_EXCEPT: return filter.values.includes(key) || (jsonProperty && filter.values.includes(jsonProperty.value)); } } /** * * @param key * @param context */ private stringifyIsPropertyKeyExcludedByJsonFilter(key: string, context: JsonStringifierTransformerContext): boolean { const jsonFilter: JsonFilterOptions = getMetadata('JsonFilter', context.mainCreator[0], null, context); if (jsonFilter) { const filter = context.filters[jsonFilter.value]; if (filter) { return this.isPropertyKeyExcludedByJsonFilter(filter, key, context); } } return false; } /** * * @param replacement * @param obj * @param oldKey * @param newKey * @param context */ private stringifyJsonFilter(replacement: any, obj: any, oldKey: string, newKey: string, context: JsonStringifierTransformerContext) { const currentMainCreator = context.mainCreator[0]; const jsonFilter: JsonFilterOptions = getMetadata('JsonFilter', currentMainCreator, oldKey, context); if (jsonFilter) { const filter = context.filters[jsonFilter.value]; if (filter) { replacement[newKey] = clone( (typeof obj[oldKey] === 'function') ? obj[oldKey]() : obj[oldKey] ); // eslint-disable-next-line guard-for-in for (const propertyKey in obj[oldKey]) { const newContext = cloneDeep(context); let newMainCreator; const jsonClass: JsonClassTypeOptions = getMetadata('JsonClassType', currentMainCreator, oldKey, context); if (jsonClass && jsonClass.type) { newMainCreator = jsonClass.type(); } else { newMainCreator = [Object]; } if (obj[oldKey] != null && obj[oldKey].constructor !== Object) { newMainCreator[0] = obj[oldKey].constructor; } newContext.mainCreator = newMainCreator; const isExcluded = this.isPropertyKeyExcludedByJsonFilter(filter, propertyKey, newContext); if (isExcluded) { delete replacement[newKey][propertyKey]; } } } } } /** * * @param context */ private isPrependJsonAppend(context: JsonStringifierTransformerContext) { const jsonAppend: JsonAppendOptions = getMetadata('JsonAppend', context.mainCreator[0], null, context); return jsonAppend && jsonAppend.prepend; } /** * * @param replacement * @param context */ private stringifyJsonAppend(replacement: any, context: JsonStringifierTransformerContext) { const currentMainCreator = context.mainCreator[0]; const jsonAppend: JsonAppendOptions = getMetadata('JsonAppend', currentMainCreator, null, context); if (jsonAppend) { for (const attr of jsonAppend.attrs) { const attributeKey = attr.value; if (attributeKey != null) { if (attr.required && !Object.hasOwnProperty.call(context.attributes, attributeKey)) { // eslint-disable-next-line max-len throw new JacksonError(`Missing @JsonAppend() required attribute "${attributeKey}" for class "${currentMainCreator.name}".`); } const value = context.attributes[attributeKey]; const key = attr.propName ? attr.propName : attributeKey; switch (attr.include) { case JsonIncludeType.NON_EMPTY: if (isValueEmpty(value)) { continue; } break; case JsonIncludeType.NON_NULL: if (value == null) { continue; } break; case JsonIncludeType.NON_DEFAULT: if (value === getDefaultValue(value) || isValueEmpty(value)) { continue; } break; } replacement[key] = value; } } } } /** * * @param replacement * @param key * @param context */ private stringifyJsonNaming(replacement: any, key: string, context: JsonStringifierTransformerContext): string { const jsonNamingOptions: JsonNamingOptions = getMetadata('JsonNaming', context.mainCreator[0], null, context); if (jsonNamingOptions && jsonNamingOptions.strategy != null) { const tokens = key.split(/(?=[A-Z])/); const tokensLength = tokens.length; let newKey = ''; for (let i = 0; i < tokensLength; i++) { let token = tokens[i]; let separator = ''; switch (jsonNamingOptions.strategy) { case PropertyNamingStrategy.KEBAB_CASE: token = token.toLowerCase(); separator = '-'; break; case PropertyNamingStrategy.LOWER_CAMEL_CASE: if (i === 0) { token = token.toLowerCase(); } else { token = token.charAt(0).toUpperCase() + token.slice(1); } break; case PropertyNamingStrategy.LOWER_CASE: token = token.toLowerCase(); break; case PropertyNamingStrategy.LOWER_DOT_CASE: token = token.toLowerCase(); separator = '.'; break; case PropertyNamingStrategy.SNAKE_CASE: token = token.toLowerCase(); separator = (i > 0 && tokens[i - 1].endsWith('_')) ? '' : '_'; break; case PropertyNamingStrategy.UPPER_CAMEL_CASE: token = token.charAt(0).toUpperCase() + token.slice(1); break; } newKey += (newKey !== '' && token.length > 1) ? separator + token : token; } if (newKey !== key) { replacement[newKey] = replacement[key]; delete replacement[key]; } return newKey; } return key; } }
the_stack
import OAuth2Service = GoogleAppsScriptOAuth2.OAuth2Service; import CacheService = GoogleAppsScript.Cache.CacheService; import HtmlOutput = GoogleAppsScript.HTML.HtmlOutput; import AppsScriptHttpRequestEvent = GoogleAppsScript.Events.AppsScriptHttpRequestEvent; import Properties = GoogleAppsScript.Properties.Properties; function getScriptProperties_(): Properties { return PropertiesService.getScriptProperties(); } function getDocumentProperties_(): Properties { return PropertiesService.getDocumentProperties(); } function getDocumentCache_(): GoogleAppsScript.Cache.Cache { const cache = CacheService.getDocumentCache(); if (!cache) { throw new Error('BUG: Null cache'); } return cache; } // region UI function onInstall(): void { onOpen(); } function onOpen(): void { SpreadsheetApp .getUi() .createAddonMenu() .addItem('Authorize Character', 'showSSOModal') .addItem('Deauthorize Character', 'deauthorizeCharacter') .addItem('Set Main Character', 'setMainCharacter') .addItem('Enable Sheet Auth Storage', 'setAuthStorage') .addItem('Reset', 'reset') .addToUi(); } function showSSOModal(): void { const template = HtmlService.createTemplateFromFile('authorize'); template.authorizationUrl = getOAuthService_(Utilities.getUuid()).getAuthorizationUrl(); SpreadsheetApp.getUi().showModalDialog(template.evaluate().setWidth(400).setHeight(250), 'GESI EVE SSO'); } function deauthorizeCharacter(): void { const ui = SpreadsheetApp.getUi(); const response = ui.prompt('Deauthorize Character', 'Enter the name of the character you wish to deauthorize.', ui.ButtonSet.OK_CANCEL); if (response.getSelectedButton() !== ui.Button.OK) return; const character = getCharacterData(response.getResponseText()); getClient(character.name).reset(); ui.alert(`Successfully deauthorized ${character.name}.`); } function setMainCharacter() { const ui = SpreadsheetApp.getUi(); const response = ui.prompt('Set Main Character', 'Enter the name of the character you wish to use as your main.', ui.ButtonSet.OK_CANCEL); if (response.getSelectedButton() !== ui.Button.OK) return; const character = getCharacterData(response.getResponseText()); setMainCharacter_(character.name); ui.alert(`${character.name} is now your main character.`); } function setAuthStorage() { const ui = SpreadsheetApp.getUi(); const useSheetStorage: boolean = ui.alert(`Use sheet based authenticated character storage?\n\nYou probably don't want to do this unless you know what you're doing.`, ui.ButtonSet.YES_NO) === ui.Button.YES; getDocumentProperties_().setProperty('SHEET_STORAGE', useSheetStorage ? 'true' : 'false'); ui.alert( useSheetStorage ? 'You are now using sheet based storage.' : 'You are now using properties based storage.', ); } function reset() { const ui = SpreadsheetApp.getUi(); const response = ui.alert('Reset?', 'Are you sure you want to reset your data?', ui.ButtonSet.YES_NO); if (response === ui.Button.NO) return; Object.keys(getAuthenticatedCharacters()).forEach((characterName: string) => { getClient(characterName).reset(); }); getDocumentProperties_().deleteAllProperties(); } // endregion /** * Parses array data into more readable format * * @param {string} endpointName (Required) Name of the endpoint data to be parsed is from. * @param {string} columnName (Required) Name of the column to be parsed. * @param {string} data (Required) Cell that holds the data to be parsed. * @param {boolean} show_column_headers Default: True, Boolean if column headings should be listed or not. * @return Parsed array data. * @customfunction */ function parseArray(endpointName: string, columnName: string, data: string, show_column_headers: boolean = true): SheetsArray { let result: SheetsArray = []; const endpoint_header: IHeader = getEndpoints()[endpointName].headers.find((eh: IHeader) => eh.name === columnName)!; if (show_column_headers) result.push(endpoint_header ? endpoint_header.sub_headers! : [columnName.slice(0, -1) + '_id']); // Kinda a hack but it works for now :shrug: if (!endpoint_header || !endpoint_header.hasOwnProperty('sub_headers')) { JSON.parse(data).forEach((o: any) => result.push([o])); } else { JSON.parse(data).forEach((o: any) => { result.push( endpoint_header.sub_headers!.map((k: string) => { return Array.isArray(o[k]) ? JSON.stringify(o[k]) : o[k]; }), ); }); } return result; } /** * @return The character that will be used by default for authenticated endpoints. * @customfunction */ function getMainCharacter(): string | null { return getDocumentProperties_().getProperty('MAIN_CHARACTER'); } /** * @return {ICharacterMap} An object representing the characters that have been authenticated * @customfunction */ function getAuthenticatedCharacters(): ICharacterMap { const properties = getDocumentProperties_().getProperties(); const characterMap: ICharacterMap = {}; // Migrate characters object to new metadata format if (properties.hasOwnProperty('characters')) { const characters = JSON.parse(properties['characters']); console.log(`migrating ${Object.keys(characters).length} characters`); Object.keys(characters).forEach((characterName: string) => { const characterData = characters[characterName]; setCharacterData_(characterName, characterData); characterMap[characterName] = characterData; }); getDocumentProperties_().deleteProperty('characters'); } else { Object.keys(properties).forEach((key: string) => { if (key.startsWith('character.')) { characterMap[key.replace('character.', '')] = JSON.parse(properties[key]); } }); } return characterMap; } /** * @return {string[] | null} An array of character names that have authenticated, or null if none have been. * @customfunction */ function getAuthenticatedCharacterNames(): string[] | null { const characters = Object.keys(getAuthenticatedCharacters()); return characters.length === 0 ? null : characters; } /** * @param {string} characterName The name of the character * @return {IAuthenticatedCharacter} A metadata object for this character * @customfunction */ function getCharacterData(characterName: string | null): IAuthenticatedCharacter { const characterMap = getAuthenticatedCharacters(); if (!characterName) throw new Error('No characters have been authenticated. Visit Add-ons => GEST => Authorize Character to do so.'); if (!characterMap.hasOwnProperty(characterName)) throw new Error(`${characterName} is not authed, or is misspelled.`); return characterMap[characterName]; } /** * Return the sheets formatted data related for the given functionName. * * @param {string} functionName The name of the endpoint that should be invoked * @param {object} params Any extra parameters that should be included in the ESI call * @return The data from the provided functionName * @customfunction */ function invoke(functionName: string, params: IFunctionParams = { show_column_headings: true }): SheetsArray { return getClient(params.name).setFunction(functionName).execute(params); } /** * Return the raw JSON data related to an ESI call * * @param {string} functionName The name of the endpoint that should be invoked * @param {object} params Any extra parameters that should be included in the ESI call * @return The raw JSON response from the provided functionName * @customfunction */ function invokeRaw<T>(functionName: string, params: IFunctionParams = { show_column_headings: false } as IFunctionParams): any { return getClient(params.name).setFunction(functionName).executeRaw<T>(params); } /** * Returns an ESIClient for the given characterName. * Can be used by advanced users for custom functions/scripts. * * @param characterName * @return {ESIClient} * @customfunction */ function getClient(characterName?: string): ESIClient { const characterData = getCharacterData(characterName || getMainCharacter()); const oauthService = getOAuthService_(characterData.id); return new ESIClient(oauthService, characterData); } /** * Returns the data from the provided functionName for each character as one list for use within a sheet. * * @param {string} functionName The name of the endpoint that should be invoked * @param {string | string[]} characterNames A single, comma separated, or vertical range of character names * @param {object} params Any extra parameters that should be included in the ESI call * @return * @customfunction */ function invokeMultiple(functionName: string, characterNames: string | string[] | string[][], params: IFunctionParams = { show_column_headings: true }): SheetsArray { const normalizedNames = normalizeNames_(characterNames); const firstCharacter = normalizedNames.shift(); const result = invoke(functionName, { ...params, name: firstCharacter }); if (params.show_column_headings) { const headers = result[0]; headers.push('character_name'); } result.forEach((item: any, idx: number) => { if (idx > 0 || !params.show_column_headings) item.push(firstCharacter); }); normalizedNames.forEach((name: string) => { const subResults = invoke(functionName, { ...params, name, show_column_headings: false }); subResults.forEach((item: any) => { item.push(name); result.push(item); }); }); return result; } /** * Returns the data from the provided functionName for each character as one list for use within custom functions/scripts. * * @param {string} functionName The name of the endpoint that should be invoked * @param {string | string[]} characterNames A single, comma separated, or vertical range of character names * @param {object} params Any extra parameters that should be included in the ESI call * @return * @customfunction */ function invokeMultipleRaw(functionName: string, characterNames: string | string[] | string[][], params: IFunctionParams = { show_column_headings: false }): SheetsArray { const normalizedNames = normalizeNames_(characterNames); const firstCharacter = normalizedNames.shift(); const result = normalizeResult_(invokeRaw(functionName, { ...params, name: firstCharacter })); result.forEach((item: any) => { item.character_name = firstCharacter; }); normalizedNames.forEach((name: string) => { const subResults = normalizeResult_(invokeRaw(functionName, { ...params, name: name })); subResults.forEach((item: any) => { item.character_name = name; result.push(item); }); }); return result; } // region oauth function authCallback(request: AppsScriptHttpRequestEvent): HtmlOutput { const id: string = request.parameter.serviceName; // Fetch the oauthService used for this flow const oauthService = getOAuthService_(id); // Complete the OAuth flow oauthService.handleCallback(request); // Parse the JWT access token for some basic information about this character const jwtToken = ESIClient.parseToken(oauthService.getAccessToken()); const characterId = parseInt(jwtToken.sub.split(':')[2]); // Fetch additional data about this character const affiliationData = getCharacterAffiliation_(characterId, oauthService); // If this character was previously authorized // update the ID of this character and reset the old service const characterData: string | null = getDocumentProperties_().getProperty(`character.${jwtToken.name}`); // If this character is already in the map, // Reset previous oauthService and delete character data if (characterData) { getOAuthService_(JSON.parse(characterData).id).reset(); } setCharacterData_(jwtToken.name, { id, alliance_id: affiliationData.alliance_id || null, character_id: affiliationData.character_id, corporation_id: affiliationData.corporation_id, name: jwtToken.name, }); // Set the main character if there is not one already if (!getMainCharacter()) setMainCharacter_(jwtToken.name); return HtmlService.createHtmlOutput(`Thank you for using GESI ${jwtToken.name}! You may close this tab.`); } function getCharacterAffiliation_(characterId: number, oauthClient: OAuth2Service): ICharacterAffiliation { return (new ESIClient(oauthClient, {} as IAuthenticatedCharacter)).setFunction('characters_affiliation').executeRaw<ICharacterAffiliation[]>({ characters: [[characterId]], show_column_headings: false })[0]; } function getOAuthService_(id: string, refreshToken?: string): OAuth2Service { const service = OAuth2.createService(id) .setAuthorizationBaseUrl(getScriptProperties_().getProperty('AUTHORIZE_URL')!) .setTokenUrl(getScriptProperties_().getProperty('TOKEN_URL')!) .setClientId(getScriptProperties_().getProperty('CLIENT_ID')!) .setClientSecret(getScriptProperties_().getProperty('CLIENT_SECRET')!) .setCallbackFunction('authCallback') .setParam('access_type', 'offline') .setParam('prompt', 'consent') .setScope(getScopes()); if (isUsingSheetStorage_()) { // @ts-ignore service.storage_ = new SheetStorage(id, getDocumentCache_(), refreshToken); } else { service .setPropertyStore(getDocumentProperties_()) .setCache(getDocumentCache_()) .setExpirationMinutes('18'); } return service; } function isUsingSheetStorage_(): boolean { return getDocumentProperties_().getProperty('SHEET_STORAGE') === 'true'; } // endregion function setCharacterData_(characterName: string, characterData: IAuthenticatedCharacter): void { getDocumentProperties_().setProperty(`character.${characterName}`, JSON.stringify(characterData)); } function setMainCharacter_(characterName: string): void { getDocumentProperties_().setProperty('MAIN_CHARACTER', characterName); } function normalizeResult_(result: any): any[] { return Array.isArray(result) ? result : [result]; } function normalizeNames_(characterNames: string | string[] | string[][]): string[] { let normalizedNames: string[]; if (Array.isArray(characterNames)) { // @ts-ignore normalizedNames = Array.isArray(characterNames[0]) ? characterNames.map((row: any) => row[0]) : characterNames; } else { normalizedNames = characterNames.split(','); } if (!normalizedNames || normalizedNames.length === 0) { throw new Error('characterNames must not be empty.'); } return normalizedNames.map(name => name.trim()); } interface IHeader { readonly name: string; readonly sub_headers?: string[]; } type ParameterType = 'path' | 'parameters' | 'body' | 'query'; interface IParameter { readonly description: string; readonly in: ParameterType; readonly name: string; readonly type: string; readonly required: boolean; } interface IEndpoint { /** @description Long description of the endpoint */ readonly description: string; /** @description The column headers that endpoint returns. Are ordered alphabetically */ readonly headers: IHeader[]; /** @description The HTTP method this endpoint uses */ readonly method: string; /** @description Whether this endpoint is paginated */ readonly paginated: boolean; /** @description The parameters this endpoint accepts */ readonly parameters: IParameter[]; /** @description The path, including parameters, of this endpoint */ readonly path: string; /** @description An optional required scope if this endpoint is authenticated */ readonly scope?: string; /** @description Short description of the endpoint */ readonly summary: string; /** @description The default version of this endpoint */ readonly version: string; } interface IEndpointList { [key: string]: IEndpoint; } interface IFunctionParams { show_column_headings: boolean; version?: string; name?: string; page?: number; [param: string]: any; } interface ICharacterData { readonly alliance_id: number | null; readonly character_id: number; readonly corporation_id: number; } interface IAuthenticatedCharacter extends ICharacterData { readonly id: string; readonly name: string; } interface ICharacterMap { [characterName: string]: IAuthenticatedCharacter; } type SheetsArray = any[][] interface IToken { readonly token_type: string; readonly refresh_token: string; readonly granted_time: number; readonly expires_in: number; readonly access_token: string | null; } interface IAccessTokenData { readonly azp: string; readonly exp: number; readonly iss: string; readonly name: string; readonly owner: string; readonly sub: string; } interface ICharacterAffiliation { readonly alliance_id?: number; readonly character_id: number; readonly corporation_id: number; readonly faction_id?: number; }
the_stack
import { VerticalAlignment, HorizontalAlignment, PositionSettings, Size, Util, ConnectedFit, Point } from '../services/overlay/utilities'; import { IPositionStrategy } from '../services/overlay/position'; import { fadeOut, fadeIn } from '../animations/main'; import { IgxSelectBase } from './select.common'; import { BaseFitPositionStrategy } from '../services/overlay/position/base-fit-position-strategy'; import { PlatformUtil } from '../core/utils'; import { Optional } from '@angular/core'; /** @hidden @internal */ export class SelectPositioningStrategy extends BaseFitPositionStrategy implements IPositionStrategy { /** @inheritdoc */ public settings: PositionSettings; private _selectDefaultSettings = { horizontalDirection: HorizontalAlignment.Right, verticalDirection: VerticalAlignment.Bottom, horizontalStartPoint: HorizontalAlignment.Left, verticalStartPoint: VerticalAlignment.Top, openAnimation: fadeIn, closeAnimation: fadeOut }; // Global variables required for cases of !initialCall (page scroll/overlay repositionAll) private global_yOffset = 0; private global_xOffset = 0; private global_styles: SelectStyles = {}; constructor(public select: IgxSelectBase, settings?: PositionSettings, @Optional() protected platform?: PlatformUtil) { super(); this.settings = Object.assign({}, this._selectDefaultSettings, settings); } /** @inheritdoc */ public position(contentElement: HTMLElement, size: Size, document?: Document, initialCall?: boolean, target?: Point | HTMLElement): void { const targetElement = target || this.settings.target; const rects = super.calculateElementRectangles(contentElement, targetElement); // selectFit obj, to be used for both cases of initialCall and !initialCall(page scroll/overlay repositionAll) const selectFit: SelectFit = { verticalOffset: this.global_yOffset, horizontalOffset: this.global_xOffset, targetRect: rects.targetRect, contentElementRect: rects.elementRect, styles: this.global_styles, scrollContainer: this.select.scrollContainer, scrollContainerRect: this.select.scrollContainer.getBoundingClientRect() }; if (initialCall) { this.select.scrollContainer.scrollTop = 0; // Fill in the required selectFit object properties. selectFit.viewPortRect = Util.getViewportRect(document); selectFit.itemElement = this.getInteractionItemElement(); selectFit.itemRect = selectFit.itemElement.getBoundingClientRect(); // Calculate input and selected item elements style related variables selectFit.styles = this.calculateStyles(selectFit, targetElement); selectFit.scrollAmount = this.calculateScrollAmount(selectFit); // Calculate how much to offset the overlay container. this.calculateYoffset(selectFit); this.calculateXoffset(selectFit); super.updateViewPortFit(selectFit); // container does not fit in viewPort and is out on Top or Bottom if (selectFit.fitVertical.back < 0 || selectFit.fitVertical.forward < 0) { this.fitInViewport(contentElement, selectFit); } // Calculate scrollTop independently of the dropdown, as we cover all `igsSelect` specific positioning and // scrolling to selected item scenarios here. this.select.scrollContainer.scrollTop = selectFit.scrollAmount; } this.setStyles(contentElement, selectFit); } /** * Obtain the selected item if there is such one or otherwise use the first one */ public getInteractionItemElement(): HTMLElement { let itemElement; if (this.select.selectedItem) { itemElement = this.select.selectedItem.element.nativeElement; } else { itemElement = this.select.getFirstItemElement(); } return itemElement; } /** * Position the items outer container so selected item text is positioned over input text and if header * And/OR footer - both header/footer are visible * * @param selectFit selectFit to use for computation. */ protected fitInViewport(contentElement: HTMLElement, selectFit: SelectFit) { const footer = selectFit.scrollContainerRect.bottom - selectFit.contentElementRect.bottom; const header = selectFit.scrollContainerRect.top - selectFit.contentElementRect.top; const lastItemFitSize = selectFit.targetRect.bottom + selectFit.styles.itemTextToInputTextDiff - footer; const firstItemFitSize = selectFit.targetRect.top - selectFit.styles.itemTextToInputTextDiff - header; // out of viewPort on Top if (selectFit.fitVertical.back < 0) { const possibleScrollAmount = selectFit.scrollContainer.scrollHeight - selectFit.scrollContainerRect.height - selectFit.scrollAmount; if (possibleScrollAmount + selectFit.fitVertical.back > 0 && firstItemFitSize > selectFit.viewPortRect.top) { selectFit.scrollAmount -= selectFit.fitVertical.back; selectFit.verticalOffset -= selectFit.fitVertical.back; this.global_yOffset = selectFit.verticalOffset; } else { selectFit.verticalOffset = 0 ; this.global_yOffset = 0; } // out of viewPort on Bottom } else if (selectFit.fitVertical.forward < 0) { if (selectFit.scrollAmount + selectFit.fitVertical.forward > 0 && lastItemFitSize < selectFit.viewPortRect.bottom) { selectFit.scrollAmount += selectFit.fitVertical.forward; selectFit.verticalOffset += selectFit.fitVertical.forward; this.global_yOffset = selectFit.verticalOffset; } else { selectFit.verticalOffset = -selectFit.contentElementRect.height + selectFit.targetRect.height; this.global_yOffset = selectFit.verticalOffset; } } } /** * Sets element's style which effectively positions the provided element * * @param element Element to position * @param selectFit selectFit to use for computation. * @param initialCall should be true if this is the initial call to the position method calling setStyles */ protected setStyles(contentElement: HTMLElement, selectFit: SelectFit) { super.setStyle(contentElement, selectFit.targetRect, selectFit.contentElementRect, selectFit); contentElement.style.width = `${selectFit.styles.contentElementNewWidth}px`; // manage container based on paddings? this.global_styles.contentElementNewWidth = selectFit.styles.contentElementNewWidth; } /** * Calculate selected item scroll position. */ private calculateScrollAmount(selectFit: SelectFit): number { const itemElementRect = selectFit.itemRect; const scrollContainer = selectFit.scrollContainer; const scrollContainerRect = selectFit.scrollContainerRect; const scrollDelta = scrollContainerRect.top - itemElementRect.top; let scrollPosition = scrollContainer.scrollTop - scrollDelta; const dropDownHeight = scrollContainer.clientHeight; scrollPosition -= dropDownHeight / 2; scrollPosition += itemElementRect.height / 2; return Math.round(Math.min(Math.max(0, scrollPosition), scrollContainer.scrollHeight - scrollContainerRect.height)); } /** * Calculate the necessary input and selected item styles to be used for positioning item text over input text. * Calculate & Set default items container width. * * @param selectFit selectFit to use for computation. */ private calculateStyles(selectFit: SelectFit, target: Point | HTMLElement): SelectStyles { const styles: SelectStyles = {}; const inputElementStyles = window.getComputedStyle(target as Element); const itemElementStyles = window.getComputedStyle(selectFit.itemElement); const numericInputFontSize = parseFloat(inputElementStyles.fontSize); const numericItemFontSize = parseFloat(itemElementStyles.fontSize); const inputTextToInputTop = (selectFit.targetRect.bottom - selectFit.targetRect.top - numericInputFontSize) / 2; const itemTextToItemTop = (selectFit.itemRect.height - numericItemFontSize) / 2; // Adjust for input top padding const negateInputPaddings = ( parseFloat(inputElementStyles.paddingTop) - parseFloat(inputElementStyles.paddingBottom) ) / 2; styles.itemTextToInputTextDiff = Math.round(itemTextToItemTop - inputTextToInputTop + negateInputPaddings); const numericLeftPadding = parseFloat(itemElementStyles.paddingLeft); const numericTextIndent = parseFloat(itemElementStyles.textIndent); styles.itemTextPadding = numericLeftPadding; styles.itemTextIndent = numericTextIndent; // 24 is the input's toggle ddl icon width styles.contentElementNewWidth = selectFit.targetRect.width + 24 + numericLeftPadding * 2; return styles; } /** * Calculate how much to offset the overlay container for Y-axis. */ private calculateYoffset(selectFit: SelectFit) { selectFit.verticalOffset = -(selectFit.itemRect.top - selectFit.contentElementRect.top + selectFit.styles.itemTextToInputTextDiff - selectFit.scrollAmount); this.global_yOffset = selectFit.verticalOffset; } /** * Calculate how much to offset the overlay container for X-axis. */ private calculateXoffset(selectFit: SelectFit) { selectFit.horizontalOffset = selectFit.styles.itemTextIndent - selectFit.styles.itemTextPadding; this.global_xOffset = selectFit.horizontalOffset; } } /** @hidden */ export interface SelectFit extends ConnectedFit { itemElement?: HTMLElement; scrollContainer: HTMLElement; scrollContainerRect: ClientRect; itemRect?: ClientRect; styles?: SelectStyles; scrollAmount?: number; } /** @hidden */ export interface SelectStyles { itemTextPadding?: number; itemTextIndent?: number; itemTextToInputTextDiff?: number; contentElementNewWidth?: number; numericLeftPadding?: number; }
the_stack
import { cleanNode, getStmt, intersection, nodesEqual, sortStmts, } from "analysis/SubstanceAnalysis"; import { prettyStmt } from "compiler/Substance"; import { cloneDeep, difference, get, groupBy, intersectionWith, map, sortBy, } from "lodash"; import { applyDiff, getDiff, rdiffResult } from "recursive-diff"; import { SynthesizedSubstance } from "synthesis/Synthesizer"; import { ASTNode, Identifier, metaProps } from "types/ast"; import { SubProg, SubStmt } from "types/substance"; import { Mutation } from "synthesis/Mutation"; //#region Generalized edits type Edit = Mutation; type DiffType = ASTNode["tag"]; export interface StmtDiff { diff: rdiffResult; stmt: SubStmt; diffType?: DiffType; originalValue: any; } export type SubDiff = UpdateDiff | AddDiff | DeleteDiff; export interface DiffSet { add: AddDiff[]; delete: DeleteDiff[]; update: UpdateDiff[]; } export interface UpdateDiff { diffType: "Update"; source: SubStmt; result: SubStmt; rawDiff: rdiffResult[]; stmtDiff: StmtDiff[]; } export interface AddDiff { diffType: "Add"; source: SubStmt; } export interface DeleteDiff { diffType: "Delete"; source: SubStmt; } const generalizedEdits = ( original: SubProg, editedProgs: SubProg[], mode: "exact" ): Edit => { switch (mode) { case "exact": return {} as any; // COMBAK: complete the function } }; /** * Compute the exact diffs between two Substance ASTs. * * @param left the original Substance program * @param right the changed Substance program * @returns a list of diffs */ export const diffSubProgs = (left: SubProg, right: SubProg): rdiffResult[] => { const diffs: rdiffResult[] = getDiff(left, right); // remove all diffs related to meta-properties const concreteDiffs: rdiffResult[] = diffs.filter( (diff: rdiffResult) => !diff.path.some((key: string | number) => metaProps.includes(key.toString()) ) ); return concreteDiffs; }; /** * Compute statement-insensitive diffs between two Substance ASTs. * * @param left the original Substance program * @param right the changed Substance program * @returns a list of diffs tagged with the original statement */ export const diffSubStmts = (left: SubProg, right: SubProg): StmtDiff[] => { // normalize the statement orderings of both ASTs first const [leftSorted, rightSorted] = [sortStmts(left), sortStmts(right)]; // compute the exact diffs between two normalized ASTs const exactDiffs: rdiffResult[] = diffSubProgs(leftSorted, rightSorted); return exactDiffs.map((d) => toStmtDiff(d, leftSorted)); }; /** * Determine if two Substance AST nodes are similar. The metric is whether the nodes have common descendents or are equal themselves. * * @param left a node in the Substance AST * @param right a node in the Substance AST * @returns if the nodes have common descendents */ export const similarNodes = (left: ASTNode, right: ASTNode): boolean => { const equalNodes = nodesEqual(left, right); const similarChildren = intersectionWith( left.children, right.children, similarNodes ); const similarLeft = intersectionWith([left], right.children, similarNodes); const similarRight = intersectionWith(left.children, [right], similarNodes); // console.log( // prettySubNode(left as any), // prettySubNode(right as any), // equalNodes, // similarChildren.map((n) => prettySubNode(n as any)), // similarLeft.map((n) => prettySubNode(n as any)), // similarRight.map((n) => prettySubNode(n as any)) // ); // console.log(left, right); return ( equalNodes || similarChildren.length > 0 || similarLeft.length > 0 || similarRight.length > 0 ); }; interface SimilarMapping { source: SubStmt; similarStmts: SubStmt[]; } export const subProgDiffs = (left: SubProg, right: SubProg): DiffSet => { const commonStmts = intersection(left, right); const leftFiltered = left.statements.filter((a) => { return intersectionWith(commonStmts, [a], nodesEqual).length === 0; }); const rightFiltered = right.statements.filter((a) => { return intersectionWith(commonStmts, [a], nodesEqual).length === 0; }); const similarMap = similarMappings(leftFiltered, rightFiltered); const update: UpdateDiff[] = updateDiffs(similarMap); const updatedSource: SubStmt[] = update.map((d) => d.source); const updatedResult: SubStmt[] = update.map((d) => d.result); // console.log(rightFiltered.map(prettyStmt).join("\n")); // console.log(updatedResult.map(prettyStmt).join("\n")); const deleted: DeleteDiff[] = leftFiltered .filter( (s) => intersectionWith([s], updatedSource, nodesEqual).length === 0 ) .map((s) => ({ diffType: "Delete", source: s })); const add: AddDiff[] = rightFiltered .filter( (s) => intersectionWith([s], updatedResult, nodesEqual).length === 0 ) .map((s) => ({ diffType: "Add", source: s })); return { update, add, delete: deleted }; }; export const showSubDiff = (d: SubDiff) => { switch (d.diffType) { case "Add": case "Delete": return `${d.diffType}: ${prettyStmt(d.source)}`; case "Update": return `${d.diffType}: ${prettyStmt(d.source)} -> ${prettyStmt( d.result )}\n\t${d.stmtDiff.map(showStmtDiff).join("\n\t")}`; } }; export const showDiffset = (d: DiffSet): string => [...d.add, ...d.delete, ...d.update].map(showSubDiff).join("\n"); export const updateDiffs = (mappings: SimilarMapping[]): UpdateDiff[] => { const picked = []; const diffs = []; for (const m of mappings) { const diff = toUpdateDiff(picked, m); if (diff) { diffs.push(diff); picked.push(diff.result); } } return diffs; }; const toUpdateDiff = ( picked: SubStmt[], { similarStmts, source }: SimilarMapping ): UpdateDiff | undefined => { const result = difference(similarStmts, picked)[0]; // TODO: insert ranking algorithm here if (result === undefined) return undefined; const rawDiffs = getDiff(cleanNode(source), cleanNode(result)); return { diffType: "Update", source, result, rawDiff: rawDiffs, stmtDiff: rawDiffs.map((d) => rawToStmtDiff(d, source)), }; }; /** * For each statement in `leftSet`, find out similar statements in `rightSet`. * * @param leftSet the first set of statements * @param rightSet the second set of statements * @returns */ export const similarMappings = ( leftSet: SubStmt[], rightSet: SubStmt[] ): SimilarMapping[] => { const mappings: SimilarMapping[] = []; for (const stmt of leftSet) { const similarSet: SubStmt[] = rightSet.filter((s) => similarNodes(stmt, s)); if (similarSet.length > 0) mappings.push({ source: stmt, // HACK: for consistent ordering similarStmts: sortBy(similarSet, prettyStmt), }); } return mappings; }; export const rawToStmtDiff = (diff: rdiffResult, source: SubStmt): StmtDiff => { const { path } = diff; const originalValue = get(source, path); const stmtDiff = { ...diff, path, }; return { diff, stmt: source, // diffType: diffType(source, stmtDiff), originalValue, }; }; export const toStmtDiff = (diff: rdiffResult, ast: SubProg): StmtDiff => { const [, stmtIndex, ...path] = diff.path; // TODO: encode the paths to AST in a more principled way const stmt = getStmt(ast, stmtIndex as number); const originalValue = get(stmt, path); const stmtDiff = { ...diff, path, }; return { diff: stmtDiff, stmt, diffType: diffType(stmt, stmtDiff), originalValue, }; }; /** * Infer the diff type from the AST-level diff by looking up the deepest tagged AST node in the diff path. * * @param node the top-level node changed * @param diff the diff defined for the node * @returns */ const diffType = (node: ASTNode, diff: rdiffResult): DiffType => { let tag = undefined; let currNode: ASTNode = node; for (const prop of diff.path) { currNode = currNode[prop]; if (currNode.tag) { tag = currNode.tag; } } if (!tag) return diff.path.join("."); else return tag; }; export const showStmtDiff = (d: StmtDiff): string => `Changed ${prettyStmt(d.stmt)} ${d.diffType ? `(${d.diffType})` : ""}: ${ d.originalValue } (${d.diff.path}) -> ${d.diff.val}`; export const applyStmtDiff = (prog: SubProg, stmtDiff: StmtDiff): SubProg => { const { diff, stmt } = stmtDiff; return { ...prog, statements: prog.statements.map((s: SubStmt) => { if (s === stmt) { const res: SubStmt = applyDiff(cloneDeep(s), [diff]); return res; } else return s; }), }; }; export const swapDiffID = (d: StmtDiff, id: Identifier): StmtDiff => { return { ...d, diff: { ...d.diff, val: id.value, }, }; }; /** * Apply a set of statement diffs on a Substance program. * NOTE: instead of sequencially applying each diff, we find all applicable diffs and apply them in a batch for each Substance statement * * @param prog the origianl Substance program * @param diffs a set of diffs to apply * @returns */ export const applyStmtDiffs = ( prog: SubProg, diffs: StmtDiff[], generalize?: (originalDiff: StmtDiff) => StmtDiff ): SubProg => ({ ...prog, statements: prog.statements.map((stmt: SubStmt) => applyDiff(stmt, findDiffs(stmt, diffs)) ), }); export const findDiffs = (stmt: SubStmt, diffs: StmtDiff[]): rdiffResult[] => diffs.filter((d) => d.stmt === stmt).map((d) => d.diff); //#endregion //#region Specification synthesis // interface TaggedMutationSet { // tag: Mutation["tag"]; // stmts: SubStmt[]; // } // export const synthesizeConfig = (examples: SynthesizedSubstance[]) => { // // ): SynthesizerSetting => { // const ops: Mutation[] = examples // .map((ex: SynthesizedSubstance) => ex.ops) // .flat(); // const grouped = groupBy(ops, "tag"); // const taggedMutations: TaggedMutationSet[] = map( // grouped, // (value: Mutation[], key: Mutation["tag"]): TaggedMutationSet => { // const set: TaggedMutationSet = { // tag: key, // stmts: value.map(editedStmt), // }; // return set; // } // ) as any; // TODO: resolve types: why is it `boolean[]`? // // console.log(showMutationSets(taggedMutations)); // // TODO: finish this function // return {} as any; // }; // const showMutationSets = (sets: TaggedMutationSet[]): string => // sets.map(showMutationSet).join("\n\n"); // const showMutationSet = (set: TaggedMutationSet): string => // `${set.tag}:\n${set.stmts.map(prettyStmt).join("\n")}`; // const editedStmt = (mutation: Mutation): SubStmt => { // switch (mutation.tag) { // case "Replace": // return mutation.old; // case "Add": // case "Delete": // // case "Swap": // // case "ReplaceName": // case "TypeChange": // return mutation.stmt; // } // }; //#endregion
the_stack
import { expect } from 'chai'; import { ChildrenNode } from '../src/core/snap/ChildrenNode'; import { NAME_COMPARATOR } from '../src/core/snap/comparators'; import { PRIORITY_INDEX } from '../src/core/snap/indexes/PriorityIndex'; import { IndexMap } from '../src/core/snap/IndexMap'; import { LeafNode } from '../src/core/snap/LeafNode'; import { Node } from '../src/core/snap/Node'; import { nodeFromJSON } from '../src/core/snap/nodeFromJSON'; import { newEmptyPath, Path } from '../src/core/util/Path'; import { SortedMap } from '../src/core/util/SortedMap'; describe('Node Tests', () => { const DEFAULT_INDEX = PRIORITY_INDEX; it('Create leaf nodes of various types.', () => { let x = new LeafNode(5, new LeafNode(42)); expect(x.getValue()).to.equal(5); expect(x.getPriority().val()).to.equal(42); expect(x.isLeafNode()).to.equal(true); x = new LeafNode('test'); expect(x.getValue()).to.equal('test'); x = new LeafNode(true); expect(x.getValue()).to.equal(true); }); it('LeafNode.updatePriority returns a new leaf node without changing the old.', () => { const x = new LeafNode('test', new LeafNode(42)); const y = x.updatePriority(new LeafNode(187)); // old node is the same. expect(x.getValue()).to.equal('test'); expect(x.getPriority().val()).to.equal(42); // new node has the new priority but the old value. expect((y as any).getValue()).to.equal('test'); expect(y.getPriority().val()).to.equal(187); }); it('LeafNode.updateImmediateChild returns a new children node.', () => { const x = new LeafNode('test', new LeafNode(42)); const y = x.updateImmediateChild('test', new LeafNode('foo')); expect(y.isLeafNode()).to.equal(false); expect(y.getPriority().val()).to.equal(42); expect((y.getImmediateChild('test') as LeafNode).getValue()).to.equal( 'foo' ); }); it('LeafNode.getImmediateChild returns an empty node.', () => { const x = new LeafNode('test'); expect(x.getImmediateChild('foo')).to.equal(ChildrenNode.EMPTY_NODE); }); it('LeafNode.getChild returns an empty node.', () => { const x = new LeafNode('test'); expect(x.getChild(new Path('foo/bar'))).to.equal(ChildrenNode.EMPTY_NODE); }); it('ChildrenNode.updatePriority returns a new internal node without changing the old.', () => { const x = ChildrenNode.EMPTY_NODE.updateImmediateChild( 'child', new LeafNode(5) ); const children = (x as any).children_; const y = x.updatePriority(new LeafNode(17)); expect((y as any).children_).to.equal((x as any).children_); expect((x as any).children_).to.equal(children); expect(x.getPriority().val()).to.equal(null); expect(y.getPriority().val()).to.equal(17); }); it('ChildrenNode.updateImmediateChild returns a new internal node with the new child, without changing the old.', () => { const children = new SortedMap<string, Node>(NAME_COMPARATOR); const x = new ChildrenNode( children, ChildrenNode.EMPTY_NODE, IndexMap.Default ); const newValue = new LeafNode('new value'); const y = x.updateImmediateChild('test', newValue); expect((x as any).children_).to.equal(children); expect((y as any).children_.get('test')).to.equal(newValue); }); it('ChildrenNode.updateChild returns a new internal node with the new child, without changing the old.', () => { const children = new SortedMap<string, Node>(NAME_COMPARATOR); const x = new ChildrenNode( children, ChildrenNode.EMPTY_NODE, IndexMap.Default ); const newValue = new LeafNode('new value'); const y = x.updateChild(new Path('test/foo'), newValue); expect((x as any).children_).to.equal(children); expect(y.getChild(new Path('test/foo'))).to.equal(newValue); }); it('Node.hash() works correctly.', () => { const node = nodeFromJSON({ intNode: 4, doubleNode: 4.5623, stringNode: 'hey guys', boolNode: true }); // !!!NOTE!!! These hashes must match what the server generates. If you change anything so these hashes change, // make sure you change the corresponding server code. expect(node.getImmediateChild('intNode').hash()).to.equal( 'eVih19a6ZDz3NL32uVBtg9KSgQY=' ); expect(node.getImmediateChild('doubleNode').hash()).to.equal( 'vf1CL0tIRwXXunHcG/irRECk3lY=' ); expect(node.getImmediateChild('stringNode').hash()).to.equal( 'CUNLXWpCVoJE6z7z1vE57lGaKAU=' ); expect(node.getImmediateChild('boolNode').hash()).to.equal( 'E5z61QM0lN/U2WsOnusszCTkR8M=' ); expect(node.hash()).to.equal('6Mc4jFmNdrLVIlJJjz2/MakTK9I='); }); it('Node.hash() works correctly with priorities.', () => { const node = nodeFromJSON({ root: { c: { '.value': 99, '.priority': 'abc' }, '.priority': 'def' } }); expect(node.hash()).to.equal('Fm6tzN4CVEu5WxFDZUdTtqbTVaA='); }); it('Node.hash() works correctly with number priorities.', () => { const node = nodeFromJSON({ root: { c: { '.value': 99, '.priority': 42 }, '.priority': 3.14 } }); expect(node.hash()).to.equal('B15QCqrzCxrI5zz1y00arWqFRFg='); }); it('Node.hash() stress...', () => { const node = nodeFromJSON({ a: -1.7976931348623157e308, b: 1.7976931348623157e308, c: 'unicode ✔ 🐵 🌴 x͢', d: 3.1415926535897932384626433832795, e: { '.value': 12345678901234568, '.priority': '🐵' }, '✔': 'foo', '.priority': '✔' }); expect(node.getImmediateChild('a').hash()).to.equal( '7HxgOBDEC92uQwhCuuvKA2rbXDA=' ); expect(node.getImmediateChild('b').hash()).to.equal( '8R+ekVQmxs6ZWP0fdzFHxVeGnWo=' ); expect(node.getImmediateChild('c').hash()).to.equal( 'JoKoFUnbmg3/DlY70KaDWslfYPk=' ); expect(node.getImmediateChild('d').hash()).to.equal( 'Y41iC5+92GIqXfabOm33EanRI8s=' ); expect(node.getImmediateChild('e').hash()).to.equal( '+E+Mxlqh5MhT+On05bjsZ6JaaxI=' ); expect(node.getImmediateChild('✔').hash()).to.equal( 'MRRL/+aA/uibaL//jghUpxXS/uY=' ); expect(node.hash()).to.equal('CyC0OU8GSkOAKnsPjheWtWC0Yxo='); }); it('ChildrenNode.getPredecessorChild works correctly.', () => { const node = nodeFromJSON({ d: true, a: true, g: true, c: true, e: true }); // HACK: Pass null instead of the actual childNode, since it's not actually needed. expect(node.getPredecessorChildName('a', null, DEFAULT_INDEX)).to.equal( null ); expect(node.getPredecessorChildName('c', null, DEFAULT_INDEX)).to.equal( 'a' ); expect(node.getPredecessorChildName('d', null, DEFAULT_INDEX)).to.equal( 'c' ); expect(node.getPredecessorChildName('e', null, DEFAULT_INDEX)).to.equal( 'd' ); expect(node.getPredecessorChildName('g', null, DEFAULT_INDEX)).to.equal( 'e' ); }); it('SortedChildrenNode.getPredecessorChild works correctly.', () => { const node = nodeFromJSON({ d: { '.value': true, '.priority': 22 }, a: { '.value': true, '.priority': 25 }, g: { '.value': true, '.priority': 19 }, c: { '.value': true, '.priority': 23 }, e: { '.value': true, '.priority': 21 } }); expect( node.getPredecessorChildName( 'a', node.getImmediateChild('a'), DEFAULT_INDEX ) ).to.equal('c'); expect( node.getPredecessorChildName( 'c', node.getImmediateChild('c'), DEFAULT_INDEX ) ).to.equal('d'); expect( node.getPredecessorChildName( 'd', node.getImmediateChild('d'), DEFAULT_INDEX ) ).to.equal('e'); expect( node.getPredecessorChildName( 'e', node.getImmediateChild('e'), DEFAULT_INDEX ) ).to.equal('g'); expect( node.getPredecessorChildName( 'g', node.getImmediateChild('g'), DEFAULT_INDEX ) ).to.equal(null); }); it('SortedChildrenNode.updateImmediateChild works correctly.', () => { let node = nodeFromJSON({ d: { '.value': true, '.priority': 22 }, a: { '.value': true, '.priority': 25 }, g: { '.value': true, '.priority': 19 }, c: { '.value': true, '.priority': 23 }, e: { '.value': true, '.priority': 21 }, '.priority': 1000 }); node = node.updateImmediateChild('c', nodeFromJSON(false)); expect((node.getImmediateChild('c') as LeafNode).getValue()).to.equal( false ); expect(node.getImmediateChild('c').getPriority().val()).to.equal(null); expect(node.getPriority().val()).to.equal(1000); }); it('removing nodes correctly removes intermediate nodes with no remaining children', () => { const json = { a: { b: { c: 1 } } }; const node = nodeFromJSON(json); const newNode = node.updateChild( new Path('a/b/c'), ChildrenNode.EMPTY_NODE ); expect(newNode.isEmpty()).to.equal(true); }); it('removing nodes leaves intermediate nodes with other children', () => { const json = { a: { b: { c: 1 }, d: 2 } }; const node = nodeFromJSON(json); const newNode = node.updateChild( new Path('a/b/c'), ChildrenNode.EMPTY_NODE ); expect(newNode.isEmpty()).to.equal(false); expect(newNode.getChild(new Path('a/b/c')).isEmpty()).to.equal(true); expect(newNode.getChild(new Path('a/d')).val()).to.equal(2); }); it('removing nodes leaves other leaf nodes', () => { const json = { a: { b: { c: 1, d: 2 } } }; const node = nodeFromJSON(json); const newNode = node.updateChild( new Path('a/b/c'), ChildrenNode.EMPTY_NODE ); expect(newNode.isEmpty()).to.equal(false); expect(newNode.getChild(new Path('a/b/c')).isEmpty()).to.equal(true); expect(newNode.getChild(new Path('a/b/d')).val()).to.equal(2); }); it('removing nodes correctly removes the root', () => { let json = null; let node = nodeFromJSON(json); let newNode = node.updateChild(newEmptyPath(), ChildrenNode.EMPTY_NODE); expect(newNode.isEmpty()).to.equal(true); json = { a: 1 }; node = nodeFromJSON(json); newNode = node.updateChild(new Path('a'), ChildrenNode.EMPTY_NODE); expect(newNode.isEmpty()).to.equal(true); }); it('ignores null values', () => { const json = { a: 1, b: null }; const node = nodeFromJSON(json); expect((node as any).children_.get('b')).to.equal(null); }); it('Leading zeroes in path are handled properly', () => { const json = { '1': 1, '01': 2, '001': 3 }; const tree = nodeFromJSON(json); expect(tree.getChild(new Path('1')).val()).to.equal(1); expect(tree.getChild(new Path('01')).val()).to.equal(2); expect(tree.getChild(new Path('001')).val()).to.equal(3); }); it('Treats leading zeroes as objects, not array', () => { const json = { '3': 1, '03': 2 }; const tree = nodeFromJSON(json); const val = tree.val(); expect(val).to.deep.equal(json); }); it("Updating empty children doesn't overwrite leaf node", () => { const empty = ChildrenNode.EMPTY_NODE; const node = nodeFromJSON('value'); expect(node).to.deep.equal(node.updateChild(new Path('.priority'), empty)); expect(node).to.deep.equal(node.updateChild(new Path('child'), empty)); expect(node).to.deep.equal( node.updateChild(new Path('child/.priority'), empty) ); expect(node).to.deep.equal(node.updateImmediateChild('child', empty)); expect(node).to.deep.equal(node.updateImmediateChild('.priority', empty)); }); });
the_stack
import { ObjectExt, Dom, Vector, Point, View } from '@antv/x6' // need: <meta http-equiv="x-ua-compatible" content="IE=Edge" /> export class PathDrawer extends View { public readonly options: PathDrawer.Options protected action: PathDrawer.Action protected pathElement: SVGPathElement protected pathTemplate: SVGPathElement protected controlElement: SVGPathElement protected startPointElement: SVGElement protected timeStamp: number | null protected readonly MOVEMENT_DETECTION_THRESHOLD = 150 protected get vel() { return Vector.create(this.container as SVGGElement) } constructor( options: Partial<PathDrawer.Options> & { target: SVGSVGElement }, ) { super() this.options = ObjectExt.merge( {}, PathDrawer.defaultOptions, options, ) as PathDrawer.Options this.action = 'awaiting-input' this.render() this.startListening() } protected render() { const options = this.options this.container = Dom.createSvgElement<SVGGElement>('g') Dom.addClass(this.container, this.prefixClassName('path-drawer')) this.pathTemplate = Dom.createSvgElement<SVGPathElement>('path') Dom.attr(this.pathTemplate, options.pathAttributes) this.startPointElement = Vector.create(options.startPointMarkup).addClass( 'start-point', ).node as SVGElement this.controlElement = Dom.createSvgElement<SVGPathElement>('path') Dom.addClass(this.controlElement, 'control-path') Vector.create('rect', { x: 0, y: 0, width: '100%', height: '100%', fill: 'transparent', stroke: 'none', }).appendTo(this.container) this.options.target.appendChild(this.container) return this } protected onRemove() { this.remove(this.pathElement) this.clear() this.stopListening() } protected startListening() { this.delegateEvents({ mousedown: 'onMouseDown', touchstart: 'onMouseDown', dblclick: 'onDoubleClick', contextmenu: 'onContextMenu', 'mousedown .start-point': 'onStartPointMouseDown', 'touchstart .start-point': 'onStartPointMouseDown', }) } protected stopListening() { this.undelegateEvents() } clear() { const path = this.pathElement if (path && path.pathSegList.numberOfItems <= 1) { this.remove(path) } this.startPointElement.remove() this.controlElement.remove() this.undelegateDocumentEvents() this.action = 'awaiting-input' this.emit('clear') } createPath(x: number, y: number) { this.pathElement = this.pathTemplate.cloneNode(true) as SVGPathElement this.addMoveSegment(x, y) Dom.translate(this.startPointElement, x, y, { absolute: true, }) this.vel.before(this.pathElement) this.vel.append(this.startPointElement) this.emit('path:create', { path: this.pathElement }) } closePath() { const path = this.pathElement const first = this.getPathSeg(path, 0) const last = this.getPathSeg(path, -1) if (last.pathSegType === SVGPathSeg.PATHSEG_LINETO_ABS) { path.pathSegList.replaceItem( path.createSVGPathSegClosePath(), path.pathSegList.numberOfItems - 1, ) } else { last.x = first.x last.y = first.y path.pathSegList.appendItem(path.createSVGPathSegClosePath()) } this.finishPath('path:close') } finishPath(name: string) { const path = this.pathElement if (path && this.numberOfVisibleSegments() > 0) { this.emit('path:finish', { path }) this.trigger(name, { path }) } else { this.emit('path:abort', { path }) } this.clear() } numberOfVisibleSegments() { const path = this.pathElement let remaining = path.pathSegList.numberOfItems remaining -= 1 const last = this.getPathSeg(path, -1) if (last.pathSegType === SVGPathSeg.PATHSEG_CLOSEPATH) { remaining -= 1 } return remaining } addMoveSegment(x: number, y: number) { const path = this.pathElement const seg = path.createSVGPathSegMovetoAbs(x, y) path.pathSegList.appendItem(seg) this.emit('path:segment:add', { path }) this.emit('path:move-segment:add', { path }) } addLineSegment(x: number, y: number) { const path = this.pathElement const seg = path.createSVGPathSegLinetoAbs(x, y) path.pathSegList.appendItem(seg) this.emit('path:segment:add', { path }) this.emit('path:line-segment:add', { path }) } addCurveSegment( x: number, y: number, x1: number, y1: number, x2?: number, y2?: number, ) { const path = this.pathElement const seg = path.createSVGPathSegCurvetoCubicAbs( x, y, x1, y1, x2 || x, y2 || y, ) path.pathSegList.appendItem(seg) this.emit('path:segment:add', { path }) this.emit('path:curve-segment:add', { path }) } adjustLastSegment( x: number | null, y: number | null, x1?: number | null, y1?: number | null, x2?: number, y2?: number, ) { const path = this.pathElement const snapRadius = this.options.snapRadius if (snapRadius && x != null && y != null) { const snaped = this.snapLastSegmentCoordinates(x, y, snapRadius) x = snaped.x // eslint-disable-line y = snaped.y // eslint-disable-line } const seg = this.getPathSeg(path, -1) if (x != null) { seg.x = x } if (y != null) { seg.y = y } if (x1 != null) { seg.x1 = x1 } if (y1 != null) { seg.y1 = y1 } if (x2 != null) { seg.x2 = x2 } if (y2 != null) { seg.y2 = y2 } this.emit('path:edit', { path }) this.emit('path:last-segment:adjust', { path }) } snapLastSegmentCoordinates(x: number, y: number, snapRadius: number) { const path = this.pathElement let xSnaped = false let ySnaped = false let targetX = x let targetY = y for ( let i = path.pathSegList.numberOfItems - 2; i >= 0 && (!xSnaped || !ySnaped); i -= 1 ) { const seg = this.getPathSeg(path, i) if (!xSnaped && Math.abs(seg.x - x) < snapRadius) { targetX = seg.x xSnaped = true } if (!ySnaped && Math.abs(seg.y - y) < snapRadius) { targetY = seg.y ySnaped = true } } return new Point(targetX, targetY) } removeLastSegment() { const path = this.pathElement path.pathSegList.removeItem(path.pathSegList.numberOfItems - 1) this.emit('path:edit', { path }) this.emit('path:last-segment:remove', { path }) } findControlPoint(x: number, y: number) { const path = this.pathElement const seg = this.getPathSeg(path, -1) return new Point(x, y).reflection(seg) } replaceLastSegmentWithCurve() { const path = this.pathElement const last = this.getPathSeg(path, -1) const prev = this.getPathSeg(path, -2) const seg = path.createSVGPathSegCurvetoCubicAbs( last.x, last.y, prev.x, prev.y, last.x, last.y, ) path.pathSegList.replaceItem(seg, path.pathSegList.numberOfItems - 1) this.emit('path:edit', { path }) this.emit('path:last-segment:replace-with-curve', { path }) } adjustControlPath(x1: number, y1: number, x2: number, y2: number) { const controlPathElement = this.controlElement controlPathElement.pathSegList.initialize( controlPathElement.createSVGPathSegMovetoAbs(x1, y1), ) controlPathElement.pathSegList.appendItem( controlPathElement.createSVGPathSegLinetoAbs(x2, y2), ) this.vel.append(controlPathElement) const path = this.pathElement this.emit('path:interact', { path }) this.emit('path:control:adjust', { path }) } removeControlPath() { const path = this.pathElement const svgControl = this.controlElement svgControl.pathSegList.clear() this.vel.append(svgControl) this.emit('path:interact', { path }) this.emit('path:control:remove', { path }) } protected getPathSeg(path: SVGPathElement, index: number) { const i = index < 0 ? path.pathSegList.numberOfItems + index : index return path.pathSegList.getItem(i) as SVGPathSegCurvetoCubicAbs } protected onMouseDown(evt: JQuery.MouseDownEvent) { const e = this.normalizeEvent(evt) e.stopPropagation() if ( this.isLeftMouseDown(e) && this.isSamePositionEvent(e) && this.container.parentNode ) { const local = this.vel.toLocalPoint(e.clientX, e.clientY) switch (this.action) { case 'awaiting-input': this.createPath(local.x, local.y) this.action = 'path-created' this.delegateDocumentEvents(PathDrawer.documentEvents) break case 'adjusting-line-end': this.action = 'awaiting-line-end' break case 'adjusting-curve-end': this.action = 'awaiting-curve-control-2' break default: break } this.timeStamp = e.timeStamp } } protected onMouseMove(evt: JQuery.MouseMoveEvent) { const e = this.normalizeEvent(evt) e.stopPropagation() if (this.action !== 'awaiting-input') { const local = this.vel.toLocalPoint(e.clientX, e.clientY) const timeStamp = this.timeStamp if (timeStamp) { if (e.timeStamp - timeStamp < this.MOVEMENT_DETECTION_THRESHOLD) { switch (this.action) { case 'path-created': { const translate = Dom.translate(this.startPointElement) this.adjustControlPath( translate.tx, translate.ty, local.x, local.y, ) break } case 'awaiting-line-end': case 'adjusting-curve-control-1': { this.adjustLastSegment(local.x, local.y) break } case 'awaiting-curve-control-2': { this.adjustLastSegment( local.x, local.y, null, null, local.x, local.y, ) break } default: break } } else { switch (this.action) { case 'path-created': this.action = 'adjusting-curve-control-1' break case 'awaiting-line-end': this.replaceLastSegmentWithCurve() this.action = 'adjusting-curve-control-2' break case 'awaiting-curve-control-2': this.action = 'adjusting-curve-control-2' break case 'adjusting-curve-control-1': { const translate = Dom.translate(this.startPointElement) this.adjustControlPath( translate.tx, translate.ty, local.x, local.y, ) break } case 'adjusting-curve-control-2': { const controlPoint = this.findControlPoint(local.x, local.y) this.adjustLastSegment( null, null, null, null, controlPoint.x, controlPoint.y, ) this.adjustControlPath( controlPoint.x, controlPoint.y, local.x, local.y, ) break } default: break } } } else { switch (this.action) { case 'adjusting-line-end': this.adjustLastSegment(local.x, local.y) break case 'adjusting-curve-end': this.adjustLastSegment( local.x, local.y, null, null, local.x, local.y, ) break default: break } } } } protected onPointerUp(evt: JQuery.MouseUpEvent) { this.timeStamp = null const e = this.normalizeEvent(evt) e.stopPropagation() if (this.isLeftMouseDown(e) && this.isSamePositionEvent(e)) { const local = this.vel.toLocalPoint(e.clientX, e.clientY) switch (this.action) { case 'path-created': case 'awaiting-line-end': this.addLineSegment(local.x, local.y) this.action = 'adjusting-line-end' break case 'awaiting-curve-control-2': this.removeControlPath() this.addLineSegment(local.x, local.y) this.action = 'adjusting-line-end' break case 'adjusting-curve-control-1': case 'adjusting-curve-control-2': this.addCurveSegment(local.x, local.y, local.x, local.y) this.action = 'adjusting-curve-end' break default: break } } } protected onStartPointMouseDown(evt: JQuery.MouseDownEvent) { const e = this.normalizeEvent(evt) e.stopPropagation() if (this.isLeftMouseDown(e) && this.isSamePositionEvent(e)) { this.closePath() } } protected onDoubleClick(evt: JQuery.DoubleClickEvent) { const e = this.normalizeEvent(evt) e.preventDefault() e.stopPropagation() if (this.isLeftMouseDown(e)) { if (this.pathElement && this.numberOfVisibleSegments() > 0) { this.removeLastSegment() this.finishPath('path:stop') } } } protected onContextMenu(evt: JQuery.ContextMenuEvent) { const e = this.normalizeEvent(evt) e.preventDefault() e.stopPropagation() if (this.isSamePositionEvent(e)) { if (this.pathElement && this.numberOfVisibleSegments() > 0) { this.removeLastSegment() this.finishPath('path:stop') } } } protected isLeftMouseDown(e: JQuery.TriggeredEvent) { return (e.which || 0) <= 1 } protected isSamePositionEvent( e: JQuery.ContextMenuEvent | JQuery.MouseDownEvent | JQuery.MouseUpEvent, ) { const originalEvent = e.originalEvent return originalEvent == null || originalEvent.detail <= 1 } } // eslint-disable-next-line export namespace PathDrawer { export interface Options { /** * The drawing area. Any paths drawn by the user are appended to this * <svg> element. They are not removed when the PathDrawer is removed. */ target: SVGSVGElement /** * An object with CSS attributes of the new path. */ pathAttributes: { [name: string]: string | null | number } /** * The SVG markup of control point overlay elements. */ startPointMarkup: string /** * If set to a number greater than zero, the endpoint of the current * segment snaps to the x- and y-values of previously drawn segment * endpoints. The number determines the distance for snapping. */ snapRadius: number } export type Action = | 'awaiting-input' | 'path-created' | 'awaiting-line-end' | 'adjusting-line-end' | 'adjusting-curve-end' | 'awaiting-curve-control-1' | 'awaiting-curve-control-2' | 'adjusting-curve-control-1' | 'adjusting-curve-control-2' interface CommonEventArgs { path: SVGPathElement } export interface EventArgs { clear?: null 'path:create': CommonEventArgs 'path:close': CommonEventArgs 'path:stop': CommonEventArgs 'path:finish': CommonEventArgs 'path:abort': CommonEventArgs 'path:segment:add': CommonEventArgs 'path:move-segment:add': CommonEventArgs 'path:line-segment:add': CommonEventArgs 'path:curve-segment:add': CommonEventArgs 'path:edit': CommonEventArgs 'path:last-segment:adjust': CommonEventArgs 'path:last-segment:remove': CommonEventArgs 'path:last-segment:replace-with-curve': CommonEventArgs 'path:interact': CommonEventArgs 'path:control:adjust': CommonEventArgs 'path:control:remove': CommonEventArgs } export const defaultOptions: Partial<Options> = { pathAttributes: { class: null, fill: '#ffffff', stroke: '#000000', 'stroke-width': 1, 'pointer-events': 'none', }, startPointMarkup: '<circle r="5"/>', snapRadius: 0, } export const documentEvents = { mousemove: 'onMouseMove', touchmove: 'onMouseMove', mouseup: 'onMouseUp', touchend: 'onMouseUp', touchcancel: 'onMouseUp', } }
the_stack
import { CONFLICT_REASON_STRINGS, IMessageMetadata, INDEXATION_PAYLOAD_TYPE, MILESTONE_PAYLOAD_TYPE, serializeMessage, TRANSACTION_PAYLOAD_TYPE } from "@iota/iota.js"; import { WriteStream } from "@iota/util.js"; import classNames from "classnames"; import React, { ReactNode } from "react"; import { FaFileDownload } from "react-icons/fa"; import { Link, RouteComponentProps } from "react-router-dom"; import chevronDownGray from "../../../assets/chevron-down-gray.svg"; import { ServiceFactory } from "../../../factories/serviceFactory"; import { ClipboardHelper } from "../../../helpers/clipboardHelper"; import { DownloadHelper } from "../../../helpers/downloadHelper"; import { MessageTangleStatus } from "../../../models/messageTangleStatus"; import { SettingsService } from "../../../services/settingsService"; import { TangleCacheService } from "../../../services/tangleCacheService"; import AsyncComponent from "../../components/AsyncComponent"; import IndexationPayload from "../../components/chrysalis/IndexationPayload"; import MilestonePayload from "../../components/chrysalis/MilestonePayload"; import ReceiptPayload from "../../components/chrysalis/ReceiptPayload"; import TransactionPayload from "../../components/chrysalis/TransactionPayload"; import InclusionState from "../../components/InclusionState"; import MessageButton from "../../components/MessageButton"; import MessageTangleState from "../../components/MessageTangleState"; import SidePanel from "../../components/SidePanel"; import Spinner from "../../components/Spinner"; import ToolsPanel from "../../components/ToolsPanel"; import "./Message.scss"; import { MessageRouteProps } from "./MessageRouteProps"; import { MessageState } from "./MessageState"; /** * Component which will show the message page. */ class Message extends AsyncComponent<RouteComponentProps<MessageRouteProps>, MessageState> { /** * API Client for tangle requests. */ private readonly _tangleCacheService: TangleCacheService; /** * Settings service. */ private readonly _settingsService: SettingsService; /** * Timer to check to state update. */ private _timerId?: NodeJS.Timer; /** * Create a new instance of Message. * @param props The props. */ constructor(props: RouteComponentProps<MessageRouteProps>) { super(props); this._tangleCacheService = ServiceFactory.get<TangleCacheService>("tangle-cache"); this._settingsService = ServiceFactory.get<SettingsService>("settings"); this.state = { messageTangleStatus: "pending", childrenBusy: true, dataUrls: {}, selectedDataUrl: "json", advancedMode: this._settingsService.get().advancedMode ?? false }; } /** * The component mounted. */ public async componentDidMount(): Promise<void> { super.componentDidMount(); const result = await this._tangleCacheService.search( this.props.match.params.network, this.props.match.params.messageId); if (result?.message) { window.scrollTo({ left: 0, top: 0, behavior: "smooth" }); const writeStream = new WriteStream(); serializeMessage(writeStream, result.message); const finalBytes = writeStream.finalBytes(); const dataUrls = { json: DownloadHelper.createJsonDataUrl(result.message), bin: DownloadHelper.createBinaryDataUrl(finalBytes), base64: DownloadHelper.createBase64DataUrl(finalBytes), hex: DownloadHelper.createHexDataUrl(finalBytes) }; window.history.replaceState(undefined, window.document.title, `/${this.props.match.params.network }/message/${result.includedMessageId ?? this.props.match.params.messageId}`); this.setState({ paramMessageId: this.props.match.params.messageId, actualMessageId: result.includedMessageId ?? this.props.match.params.messageId, message: result.message, dataUrls }, async () => { await this.updateMessageDetails(); }); } else { this.props.history.replace(`/${this.props.match.params.network }/search/${this.props.match.params.messageId}`); } } /** * The component will unmount so update flag. */ public componentWillUnmount(): void { super.componentWillUnmount(); if (this._timerId) { clearTimeout(this._timerId); this._timerId = undefined; } } /** * Render the component. * @returns The node to render. */ public render(): ReactNode { return ( <div className="message"> <div className="wrapper"> <div className="inner"> <h1> Message </h1> <div className="row top"> <div className="cards"> <div className="card"> <div className={classNames( "card--header", "card--header__space-between", "card--header__tablet-responsive" )} > <h2> General </h2> <MessageTangleState network={this.props.match.params.network} status={this.state.messageTangleStatus} milestoneIndex={this.state.metadata?.referencedByMilestoneIndex ?? this.state.metadata?.milestoneIndex} onClick={this.state.metadata?.referencedByMilestoneIndex ? () => this.props.history.push( `/${this.props.match.params.network }/search/${this.state.metadata?.referencedByMilestoneIndex}`) : undefined} /> </div> <div className="card--content"> <div className="card--label"> Message Id </div> <div className="card--value row middle"> <span className="margin-r-t">{this.state.actualMessageId}</span> <MessageButton onClick={() => ClipboardHelper.copy( this.state.actualMessageId )} buttonType="copy" labelPosition="top" /> </div> {this.state.paramMessageId !== this.state.actualMessageId && ( <React.Fragment> <div className="card--label"> Transaction Id </div> <div className="card--value card--value__secondary row middle"> <span className="margin-r-t">{this.state.paramMessageId}</span> <MessageButton onClick={() => ClipboardHelper.copy( this.state.paramMessageId )} buttonType="copy" labelPosition="top" /> </div> </React.Fragment> )} {this.state.advancedMode && this.state.message?.parentMessageIds?.map((parent, idx) => ( <React.Fragment key={idx}> <div className="card--label"> Parent Message {idx + 1} </div> <div className="card--value row middle"> {parent !== "0".repeat(64) && ( <React.Fragment> <Link className="margin-r-t" to={ `/${this.props.match.params.network }/message/${parent}` } > {parent} </Link> <MessageButton onClick={() => ClipboardHelper.copy( parent )} buttonType="copy" labelPosition="top" /> </React.Fragment> )} {parent === "0".repeat(64) && ( <span>Genesis</span> )} </div> </React.Fragment> ) )} {this.state.advancedMode && ( <React.Fragment> <div className="card--label"> Nonce </div> <div className="card--value row middle"> <span className="margin-r-t">{this.state.message?.nonce}</span> </div> </React.Fragment> )} {!this.state.advancedMode && ( <React.Fragment> <div className="card--label"> Ledger Inclusion </div> <div className="card--value row middle"> <InclusionState state={this.state.metadata?.ledgerInclusionState} /> </div> {this.state.conflictReason && ( <React.Fragment> <div className="card--label"> Conflict Reason </div> <div className="card--value"> {this.state.conflictReason} </div> </React.Fragment> )} </React.Fragment> )} </div> </div> {this.state.advancedMode && ( <div className="card"> <div className="card--header card--header__space-between"> <h2> Metadata </h2> </div> <div className="card--content"> {!this.state.metadata && !this.state.metadataError && ( <Spinner /> )} {this.state.metadataError && ( <p className="danger"> Failed to retrieve metadata. {this.state.metadataError} </p> )} {this.state.metadata && !this.state.metadataError && ( <React.Fragment> <div className="card--label"> Is Solid </div> <div className="card--value row middle"> <span className="margin-r-t"> {this.state.metadata?.isSolid ? "Yes" : "No"} </span> </div> <div className="card--label"> Ledger Inclusion </div> <div className="card--value row middle"> <InclusionState state={this.state.metadata?.ledgerInclusionState} /> </div> {this.state.conflictReason && ( <React.Fragment> <div className="card--label"> Conflict Reason </div> <div className="card--value"> {this.state.conflictReason} </div> </React.Fragment> )} </React.Fragment> )} </div> </div> )} {this.state.message?.payload && ( <React.Fragment> {this.state.message.payload.type === TRANSACTION_PAYLOAD_TYPE && ( <React.Fragment> <div className="transaction-payload-wrapper"> <TransactionPayload network={this.props.match.params.network} history={this.props.history} payload={this.state.message.payload} advancedMode={this.state.advancedMode} /> </div> {this.state.message.payload.essence.payload && ( <div className="card"> <IndexationPayload network={this.props.match.params.network} history={this.props.history} payload={this.state.message.payload.essence.payload} advancedMode={this.state.advancedMode} /> </div> )} </React.Fragment> )} {this.state.message.payload.type === MILESTONE_PAYLOAD_TYPE && ( <React.Fragment> <div className="card"> <MilestonePayload network={this.props.match.params.network} history={this.props.history} payload={this.state.message.payload} advancedMode={this.state.advancedMode} /> </div> {this.state.message.payload.receipt && ( <div className="card"> <ReceiptPayload network={this.props.match.params.network} history={this.props.history} payload={this.state.message.payload.receipt} advancedMode={this.state.advancedMode} /> </div> )} </React.Fragment> )} {this.state.message.payload.type === INDEXATION_PAYLOAD_TYPE && ( <div className="card"> <IndexationPayload network={this.props.match.params.network} history={this.props.history} payload={this.state.message.payload} advancedMode={this.state.advancedMode} /> </div> )} </React.Fragment> )} {this.state.advancedMode && ( <div className="card margin-t-s"> <div className="card--header"> <h2>Child Messages</h2> {this.state.childrenIds !== undefined && ( <span className="card--header-count"> {this.state.childrenIds.length} </span> )} </div> <div className="card--content children-container"> {this.state.childrenBusy && (<Spinner />)} {this.state.childrenIds?.map(childId => ( <div className="card--value" key={childId}> <Link to={ `/${this.props.match.params.network }/message/${childId}` } > {childId} </Link> </div> ))} {!this.state.childrenBusy && this.state.childrenIds && this.state.childrenIds.length === 0 && ( <p>There are no children for this message.</p> )} </div> </div> )} </div> <div className="side-panel-container"> <SidePanel {...this.props} /> <ToolsPanel> <div className="card--section"> <div className="card--label margin-t-t margin-b-t"> <span>Advanced View</span> <input type="checkbox" checked={this.state.advancedMode} className="margin-l-t" onChange={e => this.setState( { advancedMode: e.target.checked }, () => this._settingsService.saveSingle( "advancedMode", this.state.advancedMode))} /> </div> <div className="card--label card--label__underline"> Export Message </div> <div className="card--value row"> <div className="select-wrapper"> <select value={this.state.selectedDataUrl} onChange={e => this.setState( { selectedDataUrl: e.target.value })} > <option value="json">JSON</option> <option value="bin">Binary</option> <option value="hex">Hex</option> <option value="base64">Base64</option> </select> <img src={chevronDownGray} alt="expand" /> </div> <a className="card--action card--action-icon" href={this.state.dataUrls[this.state.selectedDataUrl]} download={DownloadHelper.filename( this.state.actualMessageId ?? "", this.state.selectedDataUrl)} role="button" > <FaFileDownload /> </a> </div> </div> </ToolsPanel> </div> </div> </div> </div> </div> ); } /** * Update the message details. */ private async updateMessageDetails(): Promise<void> { const details = await this._tangleCacheService.messageDetails( this.props.match.params.network, this.state.actualMessageId ?? ""); this.setState({ metadata: details?.metadata, metadataError: details?.error, conflictReason: this.calculateConflictReason(details?.metadata), childrenIds: details?.childrenIds && details?.childrenIds.length > 0 ? details?.childrenIds : (this.state.childrenIds ?? []), messageTangleStatus: this.calculateStatus(details?.metadata), childrenBusy: false }); if (!details?.metadata?.referencedByMilestoneIndex) { this._timerId = setTimeout(async () => { await this.updateMessageDetails(); }, 10000); } } /** * Calculate the status for the message. * @param metadata The metadata to calculate the status from. * @returns The message status. */ private calculateStatus(metadata?: IMessageMetadata): MessageTangleStatus { let messageTangleStatus: MessageTangleStatus = "unknown"; if (metadata) { if (metadata.milestoneIndex) { messageTangleStatus = "milestone"; } else if (metadata.referencedByMilestoneIndex) { messageTangleStatus = "referenced"; } else { messageTangleStatus = "pending"; } } return messageTangleStatus; } /** * Calculate the conflict reason for the message. * @param metadata The metadata to calculate the conflict reason from. * @returns The conflict reason. */ private calculateConflictReason(metadata?: IMessageMetadata): string { let conflictReason: string = ""; if (metadata?.ledgerInclusionState === "conflicting") { conflictReason = metadata.conflictReason && CONFLICT_REASON_STRINGS[metadata.conflictReason] ? CONFLICT_REASON_STRINGS[metadata.conflictReason] : "The reason for the conflict is unknown"; } return conflictReason; } } export default Message;
the_stack
'use strict'; import { Color, ColorInformation, ColorPresentation, DocumentHighlight, DocumentHighlightKind, DocumentLink, Location, Position, Range, SymbolInformation, SymbolKind, TextEdit, WorkspaceEdit, TextDocument, DocumentContext, FileSystemProvider, FileType } from '../cssLanguageTypes'; import * as nls from 'vscode-nls'; import * as nodes from '../parser/cssNodes'; import { Symbols } from '../parser/cssSymbolScope'; import { getColorValue, hslFromColor, hwbFromColor } from '../languageFacts/facts'; import { startsWith } from '../utils/strings'; import { dirname, joinPath } from '../utils/resources'; const localize = nls.loadMessageBundle(); type UnresolvedLinkData = { link: DocumentLink, isRawLink: boolean }; const startsWithSchemeRegex = /^\w+:\/\//; const startsWithData = /^data:/; export class CSSNavigation { constructor(protected fileSystemProvider: FileSystemProvider | undefined, private readonly resolveModuleReferences: boolean) { } public findDefinition(document: TextDocument, position: Position, stylesheet: nodes.Node): Location | null { const symbols = new Symbols(stylesheet); const offset = document.offsetAt(position); const node = nodes.getNodeAtOffset(stylesheet, offset); if (!node) { return null; } const symbol = symbols.findSymbolFromNode(node); if (!symbol) { return null; } return { uri: document.uri, range: getRange(symbol.node, document) }; } public findReferences(document: TextDocument, position: Position, stylesheet: nodes.Stylesheet): Location[] { const highlights = this.findDocumentHighlights(document, position, stylesheet); return highlights.map(h => { return { uri: document.uri, range: h.range }; }); } public findDocumentHighlights(document: TextDocument, position: Position, stylesheet: nodes.Stylesheet): DocumentHighlight[] { const result: DocumentHighlight[] = []; const offset = document.offsetAt(position); let node = nodes.getNodeAtOffset(stylesheet, offset); if (!node || node.type === nodes.NodeType.Stylesheet || node.type === nodes.NodeType.Declarations) { return result; } if (node.type === nodes.NodeType.Identifier && node.parent && node.parent.type === nodes.NodeType.ClassSelector) { node = node.parent; } const symbols = new Symbols(stylesheet); const symbol = symbols.findSymbolFromNode(node); const name = node.getText(); stylesheet.accept(candidate => { if (symbol) { if (symbols.matchesSymbol(candidate, symbol)) { result.push({ kind: getHighlightKind(candidate), range: getRange(candidate, document) }); return false; } } else if (node && node.type === candidate.type && candidate.matches(name)) { // Same node type and data result.push({ kind: getHighlightKind(candidate), range: getRange(candidate, document) }); } return true; }); return result; } protected isRawStringDocumentLinkNode(node: nodes.Node): boolean { return node.type === nodes.NodeType.Import; } public findDocumentLinks(document: TextDocument, stylesheet: nodes.Stylesheet, documentContext: DocumentContext): DocumentLink[] { const linkData = this.findUnresolvedLinks(document, stylesheet); const resolvedLinks: DocumentLink[] = []; for (let data of linkData) { const link = data.link; const target = link.target; if (!target || startsWithData.test(target)) { // no links for data: } else if (startsWithSchemeRegex.test(target)) { resolvedLinks.push(link); } else { const resolved = documentContext.resolveReference(target, document.uri); if (resolved) { link.target = resolved; } resolvedLinks.push(link); } } return resolvedLinks; } public async findDocumentLinks2(document: TextDocument, stylesheet: nodes.Stylesheet, documentContext: DocumentContext): Promise<DocumentLink[]> { const linkData = this.findUnresolvedLinks(document, stylesheet); const resolvedLinks: DocumentLink[] = []; for (let data of linkData) { const link = data.link; const target = link.target; if (!target || startsWithData.test(target)) { // no links for data: } else if (startsWithSchemeRegex.test(target)) { resolvedLinks.push(link); } else { const resolvedTarget = await this.resolveRelativeReference(target, document.uri, documentContext, data.isRawLink); if (resolvedTarget !== undefined) { link.target = resolvedTarget; resolvedLinks.push(link); } } } return resolvedLinks; } private findUnresolvedLinks(document: TextDocument, stylesheet: nodes.Stylesheet): UnresolvedLinkData[] { const result: UnresolvedLinkData[] = []; const collect = (uriStringNode: nodes.Node) => { let rawUri = uriStringNode.getText(); const range = getRange(uriStringNode, document); // Make sure the range is not empty if (range.start.line === range.end.line && range.start.character === range.end.character) { return; } if (startsWith(rawUri, `'`) || startsWith(rawUri, `"`)) { rawUri = rawUri.slice(1, -1); } const isRawLink = uriStringNode.parent ? this.isRawStringDocumentLinkNode(uriStringNode.parent) : false; result.push({ link: { target: rawUri, range }, isRawLink }); }; stylesheet.accept(candidate => { if (candidate.type === nodes.NodeType.URILiteral) { const first = candidate.getChild(0); if (first) { collect(first); } return false; } /** * In @import, it is possible to include links that do not use `url()` * For example, `@import 'foo.css';` */ if (candidate.parent && this.isRawStringDocumentLinkNode(candidate.parent)) { const rawText = candidate.getText(); if (startsWith(rawText, `'`) || startsWith(rawText, `"`)) { collect(candidate); } return false; } return true; }); return result; } public findDocumentSymbols(document: TextDocument, stylesheet: nodes.Stylesheet): SymbolInformation[] { const result: SymbolInformation[] = []; stylesheet.accept((node) => { const entry: SymbolInformation = { name: null!, kind: SymbolKind.Class, // TODO@Martin: find a good SymbolKind location: null! }; let locationNode: nodes.Node | null = node; if (node instanceof nodes.Selector) { entry.name = node.getText(); locationNode = node.findAParent(nodes.NodeType.Ruleset, nodes.NodeType.ExtendsReference); if (locationNode) { entry.location = Location.create(document.uri, getRange(locationNode, document)); result.push(entry); } return false; } else if (node instanceof nodes.VariableDeclaration) { entry.name = (<nodes.VariableDeclaration>node).getName(); entry.kind = SymbolKind.Variable; } else if (node instanceof nodes.MixinDeclaration) { entry.name = (<nodes.MixinDeclaration>node).getName(); entry.kind = SymbolKind.Method; } else if (node instanceof nodes.FunctionDeclaration) { entry.name = (<nodes.FunctionDeclaration>node).getName(); entry.kind = SymbolKind.Function; } else if (node instanceof nodes.Keyframe) { entry.name = localize('literal.keyframes', "@keyframes {0}", (<nodes.Keyframe>node).getName()); } else if (node instanceof nodes.FontFace) { entry.name = localize('literal.fontface', "@font-face"); } else if (node instanceof nodes.Media) { const mediaList = node.getChild(0); if (mediaList instanceof nodes.Medialist) { entry.name = '@media ' + mediaList.getText(); entry.kind = SymbolKind.Module; } } if (entry.name) { entry.location = Location.create(document.uri, getRange(locationNode, document)); result.push(entry); } return true; }); return result; } public findDocumentColors(document: TextDocument, stylesheet: nodes.Stylesheet): ColorInformation[] { const result: ColorInformation[] = []; stylesheet.accept((node) => { const colorInfo = getColorInformation(node, document); if (colorInfo) { result.push(colorInfo); } return true; }); return result; } public getColorPresentations(document: TextDocument, stylesheet: nodes.Stylesheet, color: Color, range: Range): ColorPresentation[] { const result: ColorPresentation[] = []; const red256 = Math.round(color.red * 255), green256 = Math.round(color.green * 255), blue256 = Math.round(color.blue * 255); let label; if (color.alpha === 1) { label = `rgb(${red256}, ${green256}, ${blue256})`; } else { label = `rgba(${red256}, ${green256}, ${blue256}, ${color.alpha})`; } result.push({ label: label, textEdit: TextEdit.replace(range, label) }); if (color.alpha === 1) { label = `#${toTwoDigitHex(red256)}${toTwoDigitHex(green256)}${toTwoDigitHex(blue256)}`; } else { label = `#${toTwoDigitHex(red256)}${toTwoDigitHex(green256)}${toTwoDigitHex(blue256)}${toTwoDigitHex(Math.round(color.alpha * 255))}`; } result.push({ label: label, textEdit: TextEdit.replace(range, label) }); const hsl = hslFromColor(color); if (hsl.a === 1) { label = `hsl(${hsl.h}, ${Math.round(hsl.s * 100)}%, ${Math.round(hsl.l * 100)}%)`; } else { label = `hsla(${hsl.h}, ${Math.round(hsl.s * 100)}%, ${Math.round(hsl.l * 100)}%, ${hsl.a})`; } result.push({ label: label, textEdit: TextEdit.replace(range, label) }); const hwb = hwbFromColor(color); if (hwb.a === 1) { label = `hwb(${hwb.h} ${Math.round(hwb.w * 100)}% ${Math.round(hwb.b * 100)}%)`; } else { label = `hwb(${hwb.h} ${Math.round(hwb.w * 100)}% ${Math.round(hwb.b * 100)}% / ${hwb.a})`; } result.push({ label: label, textEdit: TextEdit.replace(range, label) }); return result; } public doRename(document: TextDocument, position: Position, newName: string, stylesheet: nodes.Stylesheet): WorkspaceEdit { const highlights = this.findDocumentHighlights(document, position, stylesheet); const edits = highlights.map(h => TextEdit.replace(h.range, newName)); return { changes: { [document.uri]: edits } }; } protected async resolveModuleReference(ref: string, documentUri: string, documentContext: DocumentContext): Promise<string | undefined> { if (startsWith(documentUri, 'file://')) { const moduleName = getModuleNameFromPath(ref); const rootFolderUri = documentContext.resolveReference('/', documentUri); const documentFolderUri = dirname(documentUri); const modulePath = await this.resolvePathToModule(moduleName, documentFolderUri, rootFolderUri); if (modulePath) { const pathWithinModule = ref.substring(moduleName.length + 1); return joinPath(modulePath, pathWithinModule); } } return undefined; } protected async resolveRelativeReference(ref: string, documentUri: string, documentContext: DocumentContext, isRawLink?: boolean): Promise<string | undefined> { const relativeReference = documentContext.resolveReference(ref, documentUri); // Following [css-loader](https://github.com/webpack-contrib/css-loader#url) // and [sass-loader's](https://github.com/webpack-contrib/sass-loader#imports) // convention, if an import path starts with ~ then use node module resolution // *unless* it starts with "~/" as this refers to the user's home directory. if (ref[0] === '~' && ref[1] !== '/' && this.fileSystemProvider) { ref = ref.substring(1); return await this.resolveModuleReference(ref, documentUri, documentContext) || relativeReference; } // Following [less-loader](https://github.com/webpack-contrib/less-loader#imports) // and [sass-loader's](https://github.com/webpack-contrib/sass-loader#resolving-import-at-rules) // new resolving import at-rules (~ is deprecated). The loader will first try to resolve @import as a relative path. If it cannot be resolved, // then the loader will try to resolve @import inside node_modules. if (this.resolveModuleReferences) { if (relativeReference && await this.fileExists(relativeReference)) { return relativeReference; } else { return await this.resolveModuleReference(ref, documentUri, documentContext) || relativeReference; } } return relativeReference; } private async resolvePathToModule(_moduleName: string, documentFolderUri: string, rootFolderUri: string | undefined): Promise<string | undefined> { // resolve the module relative to the document. We can't use `require` here as the code is webpacked. const packPath = joinPath(documentFolderUri, 'node_modules', _moduleName, 'package.json'); if (await this.fileExists(packPath)) { return dirname(packPath); } else if (rootFolderUri && documentFolderUri.startsWith(rootFolderUri) && (documentFolderUri.length !== rootFolderUri.length)) { return this.resolvePathToModule(_moduleName, dirname(documentFolderUri), rootFolderUri); } return undefined; } protected async fileExists(uri: string): Promise<boolean> { if (!this.fileSystemProvider) { return false; } try { const stat = await this.fileSystemProvider.stat(uri); if (stat.type === FileType.Unknown && stat.size === -1) { return false; } return true; } catch (err) { return false; } } } function getColorInformation(node: nodes.Node, document: TextDocument): ColorInformation | null { const color = getColorValue(node); if (color) { const range = getRange(node, document); return { color, range }; } return null; } function getRange(node: nodes.Node, document: TextDocument): Range { return Range.create(document.positionAt(node.offset), document.positionAt(node.end)); } function getHighlightKind(node: nodes.Node): DocumentHighlightKind { if (node.type === nodes.NodeType.Selector) { return DocumentHighlightKind.Write; } if (node instanceof nodes.Identifier) { if (node.parent && node.parent instanceof nodes.Property) { if (node.isCustomProperty) { return DocumentHighlightKind.Write; } } } if (node.parent) { switch (node.parent.type) { case nodes.NodeType.FunctionDeclaration: case nodes.NodeType.MixinDeclaration: case nodes.NodeType.Keyframe: case nodes.NodeType.VariableDeclaration: case nodes.NodeType.FunctionParameter: return DocumentHighlightKind.Write; } } return DocumentHighlightKind.Read; } function toTwoDigitHex(n: number): string { const r = n.toString(16); return r.length !== 2 ? '0' + r : r; } function getModuleNameFromPath(path: string) { // If a scoped module (starts with @) then get up until second instance of '/', otherwise get until first instance of '/' if (path[0] === '@') { return path.substring(0, path.indexOf('/', path.indexOf('/') + 1)); } return path.substring(0, path.indexOf('/')); }
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * Cluster node details. */ export interface ClusterNode { /** * Name of the cluster node. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Id of the node in the cluster. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: number; /** * Manufacturer of the cluster node hardware. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly manufacturer?: string; /** * Model name of the cluster node hardware. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly model?: string; /** * Operating system running on the cluster node. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly osName?: string; /** * Version of the operating system running on the cluster node. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly osVersion?: string; /** * Immutable id of the cluster node. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly serialNumber?: string; /** * Number of physical cores on the cluster node. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly coreCount?: number; /** * Total available memory on the cluster node (in GiB). * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly memoryInGiB?: number; } /** * Properties reported by cluster agent. */ export interface ClusterReportedProperties { /** * Name of the on-prem cluster connected to this resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly clusterName?: string; /** * Unique id generated by the on-prem cluster. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly clusterId?: string; /** * Version of the cluster software. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly clusterVersion?: string; /** * List of nodes reported by the cluster. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nodes?: ClusterNode[]; /** * Last time the cluster reported the data. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly lastUpdated?: Date; } /** * An interface representing Resource. */ export interface Resource extends BaseResource { /** * Fully qualified resource Id for the resource. Ex - * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The name of the resource * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The type of the resource. Ex- Microsoft.Compute/virtualMachines or * Microsoft.Storage/storageAccounts. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * The resource model definition for a ARM tracked top level resource */ export interface TrackedResource extends Resource { /** * Resource tags. */ tags?: { [propertyName: string]: string }; /** * The geo-location where the resource lives */ location: string; } /** * Cluster details. */ export interface Cluster extends TrackedResource { /** * Provisioning state. Possible values include: 'Succeeded', 'Failed', 'Canceled', 'Accepted', * 'Provisioning' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: ProvisioningState; /** * Status of the cluster agent. Possible values include: 'NotYetRegistered', 'ConnectedRecently', * 'NotConnectedRecently', 'Disconnected', 'Error' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly status?: Status; /** * Unique, immutable resource id. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly cloudId?: string; /** * App id of cluster AAD identity. */ aadClientId: string; /** * Tenant id of cluster AAD identity. */ aadTenantId: string; /** * Properties reported by cluster agent. */ reportedProperties?: ClusterReportedProperties; /** * Number of days remaining in the trial period. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly trialDaysRemaining?: number; /** * Type of billing applied to the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly billingModel?: string; /** * First cluster sync timestamp. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly registrationTimestamp?: Date; /** * Most recent cluster sync timestamp. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly lastSyncTimestamp?: Date; /** * Most recent billing meter timestamp. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly lastBillingTimestamp?: Date; } /** * Cluster details to update. */ export interface ClusterUpdate { /** * Resource tags. */ tags?: { [propertyName: string]: string }; } /** * Operation display payload */ export interface OperationDisplay { /** * Resource provider of the operation */ provider?: string; /** * Resource of the operation */ resource?: string; /** * Localized friendly name for the operation */ operation?: string; /** * Localized friendly description for the operation */ description?: string; } /** * Operation detail payload */ export interface OperationDetail { /** * Name of the operation */ name?: string; /** * Indicates whether the operation is a data action */ isDataAction?: boolean; /** * Display of the operation */ display?: OperationDisplay; /** * Origin of the operation */ origin?: string; /** * Properties of the operation */ properties?: any; } /** * Available operations of the service */ export interface AvailableOperations { /** * Collection of available operation details */ value?: OperationDetail[]; /** * URL client should use to fetch the next page (per server side paging). * It's null for now, added for future use. */ nextLink?: string; } /** * The resource model definition for a ARM proxy resource. It will have everything other than * required location and tags */ export interface ProxyResource extends Resource { } /** * The resource model definition for a Azure Resource Manager resource with an etag. */ export interface AzureEntityResource extends Resource { /** * Resource Etag. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly etag?: string; } /** * The resource management error additional info. */ export interface ErrorAdditionalInfo { /** * The additional info type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * The additional info. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly info?: any; } /** * The error object. */ export interface ErrorResponseError { /** * The error code. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly code?: string; /** * The error message. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly message?: string; /** * The error target. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly target?: string; /** * The error details. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly details?: ErrorResponse[]; /** * The error additional info. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly additionalInfo?: ErrorAdditionalInfo[]; } /** * The resource management error response. */ export interface ErrorResponse { /** * The error object. */ error?: ErrorResponseError; } /** * Optional Parameters. */ export interface ClustersUpdateOptionalParams extends msRest.RequestOptionsBase { /** * Resource tags. */ tags?: { [propertyName: string]: string }; } /** * An interface representing AzureStackHCIClientOptions. */ export interface AzureStackHCIClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * @interface * List of clusters. * @extends Array<Cluster> */ export interface ClusterList extends Array<Cluster> { /** * Link to the next set of results. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * Defines values for ProvisioningState. * Possible values include: 'Succeeded', 'Failed', 'Canceled', 'Accepted', 'Provisioning' * @readonly * @enum {string} */ export type ProvisioningState = 'Succeeded' | 'Failed' | 'Canceled' | 'Accepted' | 'Provisioning'; /** * Defines values for Status. * Possible values include: 'NotYetRegistered', 'ConnectedRecently', 'NotConnectedRecently', * 'Disconnected', 'Error' * @readonly * @enum {string} */ export type Status = 'NotYetRegistered' | 'ConnectedRecently' | 'NotConnectedRecently' | 'Disconnected' | 'Error'; /** * Contains response data for the list operation. */ export type OperationsListResponse = AvailableOperations & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: AvailableOperations; }; }; /** * Contains response data for the list operation. */ export type ClustersListResponse = ClusterList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ClusterList; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type ClustersListByResourceGroupResponse = ClusterList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ClusterList; }; }; /** * Contains response data for the get operation. */ export type ClustersGetResponse = Cluster & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Cluster; }; }; /** * Contains response data for the create operation. */ export type ClustersCreateResponse = Cluster & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Cluster; }; }; /** * Contains response data for the update operation. */ export type ClustersUpdateResponse = Cluster & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Cluster; }; }; /** * Contains response data for the listNext operation. */ export type ClustersListNextResponse = ClusterList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ClusterList; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type ClustersListByResourceGroupNextResponse = ClusterList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ClusterList; }; };
the_stack
import React, { createContext, useContext, useEffect, useRef, useState, forwardRef } from 'react'; import { observer, useField, useFieldSchema, RecursionField, Schema } from '@formily/react'; import { Menu as AntdMenu, Dropdown, Modal, Button, Space } from 'antd'; import { uid } from '@formily/shared'; import cls from 'classnames'; import { SchemaField, SchemaRenderer, useDesignable } from '../../components/schema-renderer'; import { MenuOutlined, PlusOutlined, GroupOutlined, LinkOutlined, DeleteOutlined, EditOutlined, ArrowUpOutlined, ArrowDownOutlined, ArrowRightOutlined, DragOutlined, } from '@ant-design/icons'; import { IconPicker } from '../../components/icon-picker'; import { useDefaultAction } from '..'; import { useMount } from 'ahooks'; import './style.less'; import { findPropertyByPath, getSchemaPath, useSchemaPath } from '../../'; import { generateDefaultSchema } from './defaultSchemas'; import _, { cloneDeep, get, isNull } from 'lodash'; import { FormDialog, FormItem, FormLayout, Input } from '@formily/antd'; import deepmerge from 'deepmerge'; import { onFieldChange } from '@formily/core'; import { VisibleContext } from '../../context'; import { DragHandle, SortableItem, SortableItemContext } from '../../components/Sortable'; import { DndContext, DragOverlay } from '@dnd-kit/core'; import { createPortal } from 'react-dom'; import { useClient } from '../../constate'; import { useTranslation } from 'react-i18next'; import { useCompile } from '../../hooks/useCompile'; export interface MenuContextProps { schema?: Schema; onRemove?: any; } export const MenuModeContext = createContext(null); export const MenuContext = createContext<MenuContextProps>(null); const SideMenu = (props: any) => { const { selectedKey, defaultSelectedKeys, onSelect, path } = props; const { t } = useTranslation(); const { schema } = useDesignable(); const [selectedKeys, setSelectedKeys] = useState(defaultSelectedKeys); useEffect(() => { setSelectedKeys(defaultSelectedKeys); }, [defaultSelectedKeys]); if (!selectedKey) { return null; } const child = schema.properties && schema.properties[selectedKey]; if (!child || child['x-component'] !== 'Menu.SubMenu') { return null; } return ( <MenuModeContext.Provider value={'inline'}> <AntdMenu mode={'inline'} onSelect={onSelect} onOpenChange={(openKeys) => { setSelectedKeys(openKeys); }} openKeys={selectedKeys} selectedKeys={selectedKeys} > <RecursionField schema={child} onlyRenderProperties /> <Menu.AddNew key={uid()} path={[...path, selectedKey]}> <Button // block type={'dashed'} icon={<PlusOutlined />} className={`nb-add-new-menu-item menu-mode-inline designable-btn designable-btn-dash`} > {t('Add menu item')} </Button> </Menu.AddNew> </AntdMenu> </MenuModeContext.Provider> ); }; export const MenuSelectedKeysContext = createContext<any>([]); export const Menu: any = observer((props: any) => { const { mode, onSelect, sideMenuRef, defaultSelectedKeys: keys, getSelectedKeys, onRemove, ...others } = props; const defaultSelectedKeys = useContext(MenuSelectedKeysContext); const { root, schema, insertAfter, remove } = useDesignable(); const moveToAfter = (path1, path2) => { if (!path1 || !path2) { return; } if (path1.join('.') === path2.join('.')) { return; } const data = findPropertyByPath(root, path1); if (!data) { return; } remove(path1); return insertAfter(data.toJSON(), path2); }; const fieldSchema = useFieldSchema(); console.log('Menu.schema', schema, fieldSchema); const [selectedKey, setSelectedKey] = useState(defaultSelectedKeys[0] || null); const path = useSchemaPath(); const child = schema.properties && schema.properties[selectedKey]; const isSubMenu = child && child['x-component'] === 'Menu.SubMenu'; const { updateSchema } = useClient(); const { t } = useTranslation(); useEffect(() => { const sideMenuElement = sideMenuRef?.current as HTMLElement; if (!sideMenuElement) { return; } sideMenuElement.style.display = isSubMenu ? 'block' : 'none'; }, [selectedKey, sideMenuRef]); const [dragOverlayContent, setDragOverlayContent] = useState(''); // console.log('defaultSelectedKeys', defaultSelectedKeys, getSelectedKeys); return ( <MenuContext.Provider value={{ schema, onRemove }}> <DndContext onDragStart={(event) => { console.log({ event }); setDragOverlayContent(event.active.data?.current?.title || ''); }} onDragEnd={async (event) => { console.log({ event }); const path1 = event.active?.data?.current?.path; const path2 = event.over?.data?.current?.path; const data = moveToAfter(path1, path2); await updateSchema(data); }} > {createPortal( <DragOverlay style={{ pointerEvents: 'none', whiteSpace: 'nowrap' }} dropAnimation={{ duration: 10, easing: 'cubic-bezier(0.18, 0.67, 0.6, 1.22)', }} > {dragOverlayContent} </DragOverlay>, document.body, )} <MenuModeContext.Provider value={mode}> <AntdMenu defaultOpenKeys={defaultSelectedKeys} defaultSelectedKeys={defaultSelectedKeys} selectedKeys={[selectedKey]} {...others} mode={mode === 'mix' ? 'horizontal' : mode} onSelect={(info) => { console.log('onSelect', defaultSelectedKeys); const selectedSchema = schema.properties[info.key]; if (selectedSchema?.['x-component'] === 'Menu.URL') { setSelectedKey(selectedKey); return; } if (mode === 'mix') { setSelectedKey(info.key); } console.log({ selectedSchema }); onSelect?.({ ...info, schema: selectedSchema }); }} > <RecursionField schema={schema} onlyRenderProperties /> <Menu.AddNew key={uid()} path={path}> {/* <PlusOutlined className={'nb-add-new-icon'} /> */} <Button className={`designable-btn designable-btn-dash nb-add-new-menu-item designable menu-mode-${ mode === 'mix' ? 'horizontal' : mode }`} block icon={<PlusOutlined />} type={mode == 'inline' ? 'dashed' : 'primary'} > {t('Add menu item')} </Button> </Menu.AddNew> </AntdMenu> {mode === 'mix' && sideMenuRef.current?.firstChild && createPortal( <SideMenu path={path} onSelect={(info) => { const keyPath = [selectedKey, ...[...info.keyPath].reverse()]; const selectedSchema = findPropertyByPath(schema, keyPath); console.log('keyPath', keyPath, selectedSchema); if (selectedSchema?.['x-component'] === 'Menu.URL') { setSelectedKey(selectedKey); } else { onSelect?.({ ...info, keyPath, schema: selectedSchema }); } }} defaultSelectedKeys={defaultSelectedKeys || []} selectedKey={selectedKey} sideMenuRef={sideMenuRef} />, sideMenuRef.current.firstChild, )} </MenuModeContext.Provider> </DndContext> </MenuContext.Provider> ); }); Menu.Divider = observer(AntdMenu.Divider); Menu.Item = observer((props: any) => { const { icon } = props; const { schema, DesignableBar } = useDesignable(); const compile = useCompile(); const title = compile(schema.title); return ( <AntdMenu.Item {...props} icon={null} eventKey={schema.name} key={schema.name}> <SortableItem id={schema.name} data={{ title, path: getSchemaPath(schema), }} > {icon && ( <span style={{ marginRight: 10 }}> <IconPicker type={icon} /> </span> )} {title} <DesignableBar /> </SortableItem> </AntdMenu.Item> ); }); Menu.Link = observer((props: any) => { const { icon } = props; const { schema, DesignableBar } = useDesignable(); const compile = useCompile(); const title = compile(schema.title); return ( <AntdMenu.Item {...props} icon={null} eventKey={schema.name} key={schema.name}> <SortableItem id={schema.name} data={{ title, path: getSchemaPath(schema), }} > {icon && ( <span style={{ marginRight: 10 }}> <IconPicker type={icon} /> </span> )} {title} <DesignableBar /> </SortableItem> {/* <Link to={props.to || schema.name}>{schema.title}</Link> */} <DesignableBar /> </AntdMenu.Item> ); }); Menu.URL = observer((props: any) => { const { icon } = props; const { schema, DesignableBar } = useDesignable(); const compile = useCompile(); const title = compile(schema.title); return ( <AntdMenu.Item {...props} icon={null} eventKey={schema.name} key={schema.name} onClick={(info) => { window.open(props.href); }} > <SortableItem id={schema.name} data={{ title, path: getSchemaPath(schema), }} > {icon && ( <span style={{ marginRight: 10 }}> <IconPicker type={icon} /> </span> )} {title} <DesignableBar /> </SortableItem> <DesignableBar /> </AntdMenu.Item> ); }); Menu.Action = observer((props: any) => { const { icon, useAction = useDefaultAction, ...others } = props; const { schema, DesignableBar } = useDesignable(); const field = useField(); const [visible, setVisible] = useState(false); const { run } = useAction(); const compile = useCompile(); const title = compile(schema.title); return ( <VisibleContext.Provider value={[visible, setVisible]}> <AntdMenu.Item {...others} key={schema.name} eventKey={schema.name} icon={<IconPicker type={icon} />} onClick={async () => { await run(); setVisible(true); }} > <SortableItem id={schema.name} data={{ title, path: getSchemaPath(schema), }} > {title} <DesignableBar /> </SortableItem> </AntdMenu.Item> {props.children} {/* <RecursionField schema={schema} onlyRenderProperties /> */} </VisibleContext.Provider> ); }); Menu.SubMenu = observer((props: any) => { const { icon } = props; const { schema, DesignableBar } = useDesignable(); const mode = useContext(MenuModeContext); const compile = useCompile(); const title = compile(schema.title); return mode === 'mix' ? ( <Menu.Item {...props} /> ) : ( <AntdMenu.SubMenu {...props} icon={null} // icon={<IconPicker type={icon} />} title={ <SortableItem id={schema.name} data={{ title, path: getSchemaPath(schema), }} > {icon && ( <span style={{ marginRight: 10 }}> <IconPicker type={icon} /> </span> )} {title} <DesignableBar /> </SortableItem> // <> // {schema.title} <DesignableBar /> // </> } eventKey={schema.name} key={schema.name} > <RecursionField schema={schema} onlyRenderProperties /> </AntdMenu.SubMenu> ); }); Menu.AddNew = observer((props: any) => { const { designable, appendChild } = useDesignable(props.path); const { createSchema, removeSchema, updateSchema } = useClient(); const { t } = useTranslation(); if (!designable) { return null; } const schemas = { 'Menu.Link': { icon: <MenuOutlined />, title: t('Add page'), schema: { type: 'object', properties: { title: { type: 'string', title: t('Name'), required: true, 'x-decorator': 'FormItem', 'x-component': 'Input', }, 'x-component-props.icon': { type: 'string', title: t('Icon'), 'x-decorator': 'FormItem', 'x-component': 'IconPicker', }, }, }, }, 'Menu.SubMenu': { icon: <GroupOutlined />, title: t('Add group'), schema: { type: 'object', properties: { title: { type: 'string', title: t('Name'), required: true, 'x-decorator': 'FormItem', 'x-component': 'Input', }, 'x-component-props.icon': { type: 'string', title: t('Icon'), 'x-decorator': 'FormItem', 'x-component': 'IconPicker', }, }, }, }, 'Menu.URL': { icon: <LinkOutlined />, title: t('Add link'), schema: { type: 'object', properties: { title: { type: 'string', title: t('Name'), required: true, 'x-decorator': 'FormItem', 'x-component': 'Input', }, 'x-component-props.icon': { type: 'string', title: t('Icon'), 'x-decorator': 'FormItem', 'x-component': 'IconPicker', }, 'x-component-props.href': { type: 'string', title: t('Link'), required: true, 'x-decorator': 'FormItem', 'x-component': 'Input', }, }, }, }, }; return ( <AntdMenu.ItemGroup className={'nb-menu-add-new'} title={ <Dropdown // trigger={['click']} overlay={ <AntdMenu onClick={async (info) => { console.log({ info }); const values = await FormDialog(schemas[info.key].title, () => { return ( <FormLayout layout={'vertical'}> <SchemaField schema={schemas[info.key].schema} /> </FormLayout> ); }).open(); const defaults = generateDefaultSchema(info.key); const data = appendChild(deepmerge(defaults, values)); await createSchema(data); }} > <AntdMenu.Item key={'Menu.SubMenu'} icon={<GroupOutlined />}> {t('Group')} </AntdMenu.Item> <AntdMenu.Item key={'Menu.Link'} icon={<MenuOutlined />}> {t('Page')} </AntdMenu.Item> <AntdMenu.Item key={'Menu.URL'} icon={<LinkOutlined />}> {t('Link')} </AntdMenu.Item> </AntdMenu> } > {props.children} </Dropdown> } /> ); }); Menu.DesignableBar = (props) => { const { t } = useTranslation(); const schemas = { 'Menu.Action': { icon: <MenuOutlined />, title: t('Page'), schema: { type: 'object', properties: { title: { type: 'string', title: t('Name'), required: true, 'x-decorator': 'FormItem', 'x-component': 'Input', }, 'x-component-props.icon': { type: 'string', title: t('Icon'), 'x-decorator': 'FormItem', 'x-component': 'IconPicker', }, }, }, }, 'Menu.Item': { icon: <MenuOutlined />, title: t('Page'), schema: { type: 'object', properties: { title: { type: 'string', title: t('Name'), required: true, 'x-decorator': 'FormItem', 'x-component': 'Input', }, 'x-component-props.icon': { type: 'string', title: t('Icon'), 'x-decorator': 'FormItem', 'x-component': 'IconPicker', }, }, }, }, 'Menu.Link': { icon: <MenuOutlined />, title: t('Page'), schema: { type: 'object', properties: { title: { type: 'string', title: t('Name'), required: true, 'x-decorator': 'FormItem', 'x-component': 'Input', }, 'x-component-props.icon': { type: 'string', title: t('Icon'), 'x-decorator': 'FormItem', 'x-component': 'IconPicker', }, }, }, }, 'Menu.SubMenu': { icon: <GroupOutlined />, title: t('Group'), schema: { type: 'object', properties: { title: { type: 'string', title: t('Name'), required: true, 'x-decorator': 'FormItem', 'x-component': 'Input', }, 'x-component-props.icon': { type: 'string', title: t('Icon'), 'x-decorator': 'FormItem', 'x-component': 'IconPicker', }, }, }, }, 'Menu.URL': { icon: <LinkOutlined />, title: 'Link', schema: { type: 'object', properties: { title: { type: 'string', title: t('Name'), required: true, 'x-decorator': 'FormItem', 'x-component': 'Input', }, 'x-component-props.icon': { type: 'string', title: t('Icon'), 'x-decorator': 'FormItem', 'x-component': 'IconPicker', }, 'x-component-props.href': { type: 'string', title: t('Link'), required: true, 'x-decorator': 'FormItem', 'x-component': 'Input', }, }, }, }, }; const field = useField(); const [visible, setVisible] = useState(false); const { designable, schema, remove, refresh, insertAfter, insertBefore, appendChild } = useDesignable(); const formConfig = schemas[schema['x-component']]; const isSubMenu = schema['x-component'] === 'Menu.SubMenu'; const ctx = useContext(MenuContext); const mode = useContext(MenuModeContext); const { createSchema, removeSchema, updateSchema } = useClient(); return ( <div className={cls('designable-bar', { active: visible })}> <div onClick={(e) => { e.stopPropagation(); e.preventDefault(); }} className={'designable-bar-actions'} > <Space size={2}> <DragHandle /> <Dropdown overlayStyle={{ minWidth: 150, }} trigger={['hover']} overlay={ <AntdMenu onClick={async (info) => { if (['update', 'move', 'delete'].includes(info.key)) { return; } const methodLabels = { insertBefore: 'before', insertAfter: 'after', appendChild: 'in', }; const keys = info.key.split('.'); const method = keys.shift(); const type = keys.join('.'); const config = schemas[type]; if (!config) { return; } const values = await FormDialog( t(`Add {{type}} ${methodLabels[method]} "{{title}}"`, { type: (config.title as string).toLowerCase(), title: schema.title, }), // `在「${schema.title}」${methodLabels[method]}插入${config.title}`, () => { return ( <FormLayout layout={'vertical'}> <SchemaField schema={config.schema} /> </FormLayout> ); }, ).open(); const methods = { insertAfter, insertBefore, appendChild, }; const defaults = generateDefaultSchema(type); const data = methods[method](deepmerge(defaults, values)); await createSchema(data); }} > <AntdMenu.Item key={'update'} onClick={async () => { const initialValues = {}; Object.keys(formConfig.schema.properties).forEach((name) => { _.set(initialValues, name, get(schema, name)); }); const values = await FormDialog(t('Edit menu item'), () => { return ( <FormLayout layout={'vertical'}> <SchemaField schema={formConfig.schema} /> </FormLayout> ); }).open({ initialValues, }); if (values.title) { schema.title = values.title; } const icon = _.get(values, 'x-component-props.icon') || null; schema['x-component-props'] = schema['x-component-props'] || {}; schema['x-component-props']['icon'] = icon; field.componentProps['icon'] = icon; refresh(); await updateSchema(schema); }} > <EditOutlined /> {t('Edit')} </AntdMenu.Item> <AntdMenu.Item key={'move'} onClick={async () => { let menuSchema: Schema; let parent = schema.parent; while (parent) { if (parent['x-component'] === 'Menu') { menuSchema = parent; break; } parent = parent.parent; } console.log({ menuSchema }); const toTreeData = (s: Schema) => { const items = []; Object.keys(s.properties || {}).forEach((name) => { const current = s.properties[name]; if (!(current['x-component'] as string).startsWith('Menu.')) { return; } // if (current.name === schema.name) { // return; // } items.push({ key: current['key'] || current.name, label: current.title, title: current.title, value: getSchemaPath(current).join('.'), children: toTreeData(current), }); }); return items; }; const dataSource = toTreeData(menuSchema); const values = await FormDialog(t(`Move {{title}} to`, { title: schema.title }), () => { return ( <FormLayout layout={'vertical'}> <SchemaField schema={{ type: 'object', properties: { path: { type: 'string', title: t('Target position'), enum: dataSource, required: true, 'x-decorator': 'FormItem', 'x-component': 'TreeSelect', }, method: { type: 'string', default: 'insertAfter', enum: [ { label: t('After'), value: 'insertAfter', }, { label: t('Before'), value: 'insertBefore', }, ], 'x-decorator': 'FormItem', 'x-component': 'Radio.Group', }, }, }} /> </FormLayout> ); }).open({ effects(form) { onFieldChange('path', (field) => { const target = findPropertyByPath( schema.root, // @ts-ignore field.value, ); console.log({ field }); field.query('method').take((f) => { // @ts-ignore // f.value = 'insertAfter'; // @ts-ignore f.dataSource = target['x-component'] === 'Menu.SubMenu' ? [ { label: t('After'), value: 'insertAfter' }, { label: t('Before'), value: 'insertBefore', }, { label: t('Inner'), value: 'appendChild' }, ] : [ { label: t('After'), value: 'insertAfter' }, { label: t('Before'), value: 'insertBefore', }, ]; }); }); }, }); const methods = { insertAfter, insertBefore, appendChild, }; const data = schema.toJSON(); remove(); const source = methods[values.method](data, values.path); await updateSchema(source); }} > <DragOutlined /> {t('Move to')} </AntdMenu.Item> <AntdMenu.Divider /> <AntdMenu.SubMenu key={'insertBefore'} icon={<ArrowUpOutlined />} title={t(`Insert ${mode == 'inline' ? 'above' : 'left'}`)} > <AntdMenu.Item key={'insertBefore.Menu.SubMenu'} icon={<GroupOutlined />}> {t('Group')} </AntdMenu.Item> <AntdMenu.Item key={'insertBefore.Menu.Link'} icon={<MenuOutlined />}> {t('Page')} </AntdMenu.Item> <AntdMenu.Item key={'insertBefore.Menu.URL'} icon={<LinkOutlined />}> {t('Link')} </AntdMenu.Item> </AntdMenu.SubMenu> <AntdMenu.SubMenu key={'insertAfter'} icon={<ArrowDownOutlined />} title={t(`Insert ${mode == 'inline' ? 'below' : 'right'}`)} > <AntdMenu.Item key={'insertAfter.Menu.SubMenu'} icon={<GroupOutlined />}> {t('Group')} </AntdMenu.Item> <AntdMenu.Item key={'insertAfter.Menu.Link'} icon={<MenuOutlined />}> {t('Page')} </AntdMenu.Item> <AntdMenu.Item key={'insertAfter.Menu.URL'} icon={<LinkOutlined />}> {t('Link')} </AntdMenu.Item> </AntdMenu.SubMenu> {isSubMenu && ( <AntdMenu.SubMenu key={'appendChild'} icon={<ArrowRightOutlined />} title={t('Insert inner')}> <AntdMenu.Item key={'appendChild.Menu.SubMenu'} icon={<GroupOutlined />}> {t('Group')} </AntdMenu.Item> <AntdMenu.Item key={'appendChild.Menu.Link'} icon={<MenuOutlined />}> {t('Page')} </AntdMenu.Item> <AntdMenu.Item key={'appendChild.Menu.URL'} icon={<LinkOutlined />}> {t('Link')} </AntdMenu.Item> </AntdMenu.SubMenu> )} {/* <AntdMenu.Divider /> <AntdMenu.Item icon={<LockOutlined />} onClick={async () => { const loadRoles = async () => { const resource = Resource.make('roles'); const data = await resource.list(); console.log('loadRoles', data); return data?.data.map((item) => ({ label: item.title, value: item.name, })); }; const resource = Resource.make({ associatedName: 'ui_schemas', associatedIndex: schema['key'], resourceName: 'roles', }); const uiSchemasRoles = await resource.list(); console.log({ uiSchemasRoles }); const values = await FormDialog(`设置权限`, () => { return ( <FormLayout layout={'vertical'}> <SchemaField scope={{ loadRoles }} schema={{ type: 'object', properties: { roles: { type: 'array', title: '允许访问的角色', 'x-reactions': [ '{{useAsyncDataSource(loadRoles)}}', ], 'x-decorator': 'FormilyFormItem', 'x-component': 'Select', 'x-component-props': { mode: 'tags', }, }, }, }} /> </FormLayout> ); }).open({ initialValues: { roles: uiSchemasRoles?.data?.map((role) => role.name), }, }); await Resource.make({ resourceName: 'ui_schemas', resourceIndex: schema['key'], }).save(values); }} > 设置权限 </AntdMenu.Item> */} <AntdMenu.Divider /> <AntdMenu.Item key={'delete'} onClick={() => { Modal.confirm({ title: t(`Delete menu item`), content: t('Are you sure you want to delete it?'), onOk: async () => { const target = remove(); await removeSchema(target); ctx.onRemove && ctx.onRemove(target); }, }); }} > <DeleteOutlined /> {t('Delete')} </AntdMenu.Item> </AntdMenu> } > <MenuOutlined /> </Dropdown> </Space> </div> </div> ); }; export default Menu;
the_stack
import { assert, expect } from "chai"; import { CheckpointConnection, IModelApp, IModelConnection, RealityDataSource, SpatialModelState, ThreeDTileFormatInterpreter, TileAdmin } from "@itwin/core-frontend"; import { TestUsers } from "@itwin/oidc-signin-tool/lib/cjs/frontend"; import { TestUtility } from "../TestUtility"; import { RealityDataFormat, RealityDataProvider, RealityDataSourceKey } from "@itwin/core-common"; import { Id64String } from "@itwin/core-bentley"; import { ITwinRealityData, RealityDataAccessClient, RealityDataClientOptions, RealityDataQueryCriteria, RealityDataResponse } from "@itwin/reality-data-client"; export interface IRealityDataModelInfo { key: RealityDataSourceKey; // The id of the reality data model in the iModel modelId: Id64String; // The realityData model url on ContextShare attachmentUrl: string; // The name of the reality data in the model name attachmentName: string; } describe("RealityDataAccess (#integration)", () => { let allProjectRealityDatas: ITwinRealityData[] | undefined; let imodel: IModelConnection; let iTwinId: string; const realityDataClientOptions: RealityDataClientOptions = { /** API Version. v1 by default */ // version?: ApiVersion; /** API Url. Used to select environment. Defaults to "https://api.bentley.com/realitydata" */ baseUrl: `https://${process.env.IMJS_URL_PREFIX}api.bentley.com/realitydata`, }; let realityDataAccess: RealityDataAccessClient; before(async () => { await TestUtility.shutdownFrontend(); realityDataAccess = new RealityDataAccessClient(realityDataClientOptions); const options = TestUtility.iModelAppOptions; options.realityDataAccess = realityDataAccess; const tileAdmin: TileAdmin.Props = {}; tileAdmin.cesiumIonKey = process.env.IMJS_CESIUM_ION_KEY; options.tileAdmin = tileAdmin; await TestUtility.startFrontend({ ...options, }); await TestUtility.initialize(TestUsers.regular); iTwinId = await TestUtility.queryITwinIdByName(TestUtility.testITwinName); const iModelId = await TestUtility.queryIModelIdByName(iTwinId, TestUtility.testIModelNames.realityDataAccess); imodel = await CheckpointConnection.openRemote(iTwinId, iModelId); }); after(async () => { if (imodel) await imodel.close(); await TestUtility.shutdownFrontend(); }); function getAttachmentURLFromModelProps(modelProps: any): {rdsUrl: string | undefined, blobFilename: string | undefined} { // Special case for OPC file if (modelProps.tilesetUrl !== undefined && modelProps.tilesetUrl.orbitGtBlob !== undefined ) { return {rdsUrl: modelProps.tilesetUrl.orbitGtBlob.rdsUrl, blobFilename: modelProps.tilesetUrl.orbitGtBlob.blobFileName}; } else if (modelProps.orbitGtBlob !== undefined && modelProps.orbitGtBlob.rdsUrl ) { return {rdsUrl: modelProps.orbitGtBlob.rdsUrl, blobFilename: modelProps.orbitGtBlob.blobFileName }; } return {rdsUrl: modelProps.tilesetUrl, blobFilename: undefined }; } async function getAttachedRealityDataModelInfoSet(iModel: IModelConnection): Promise<Set<IRealityDataModelInfo> > { // Get set of RealityDataModelInfo that are directly attached to the model. const modelRealityDataInfos = new Set<IRealityDataModelInfo>(); if (iModel) { const query = { from: SpatialModelState.classFullName, wantPrivate: false }; const iModelProps = await iModel.models.queryProps(query); for (const prop of iModelProps) { if (prop.jsonProperties !== undefined && (prop.jsonProperties.tilesetUrl || prop.jsonProperties.orbitGtBlob) && prop.id !== undefined && prop.name) { const attachmentUrl = getAttachmentURLFromModelProps(prop.jsonProperties); if (attachmentUrl !== undefined && attachmentUrl.rdsUrl !== undefined) { let fileFormat = RealityDataFormat.ThreeDTile; if (prop.jsonProperties.orbitGtBlob) fileFormat = RealityDataFormat.OPC; const key = RealityDataSource.createKeyFromUrl(attachmentUrl.rdsUrl, undefined, fileFormat); modelRealityDataInfos.add({key, modelId: prop.id, attachmentUrl: attachmentUrl.rdsUrl, attachmentName: prop.name}); } } } } return modelRealityDataInfos; } enum RealityDataType { REALITYMESH3DTILES = "REALITYMESH3DTILES", OSMBUILDINGS = "OSMBUILDINGS", OPC = "OPC", TERRAIN3DTILES = "TERRAIN3DTILES", // Terrain3DTiles OMR = "OMR", // Mapping Resource, CESIUM3DTILES = "CESIUM3DTILES", UNKNOWN = "UNKNOWN", } function isSupportedType(type: string | undefined): boolean { if (type === undefined) return false; switch (type.toUpperCase()) { case RealityDataType.REALITYMESH3DTILES: return true; case RealityDataType.CESIUM3DTILES: return true; case RealityDataType.OPC: return true; case RealityDataType.OSMBUILDINGS: return true; case RealityDataType.TERRAIN3DTILES: return true; case RealityDataType.OMR: return true; } return false; } function isSupportedDisplayType(type: string | undefined): boolean { if (type === undefined) return false; if (isSupportedType(type)) { switch (type.toUpperCase()) { case RealityDataType.OMR: return false; // this type is supported from Context Share but can only be displayed by Orbit Photo Navigation (not publicly available) default: return true; } } return false; } function createRealityDataListKeyFromITwinRealityData(iTwinRealityData: ITwinRealityData): RealityDataSourceKey { return { provider: RealityDataProvider.ContextShare, format: iTwinRealityData.type === RealityDataType.OPC ? RealityDataFormat.OPC : RealityDataFormat.ThreeDTile, id: iTwinRealityData.id, }; } function getOSMBuildingsKey(): RealityDataSourceKey { // We don't always have access to url (which is internal) for OSMBuildings, create a special key for it return {provider: RealityDataProvider.CesiumIonAsset, format: RealityDataFormat.ThreeDTile, id: "OSMBuildings"}; } async function getAllRealityDataFromProject(): Promise<ITwinRealityData[]> { // Initialize on first call and then keep the result for other calls if (allProjectRealityDatas === undefined) { allProjectRealityDatas = []; let projectRealityDatas: RealityDataResponse = {realityDatas: []}; let continuationToken: string | undefined; const top=100; const criteria: RealityDataQueryCriteria = { getFullRepresentation: true, top, continuationToken, }; do { criteria.continuationToken = projectRealityDatas.continuationToken; const accessToken = await IModelApp.getAccessToken(); projectRealityDatas = await realityDataAccess.getRealityDatas(accessToken, iTwinId, criteria); for (const rd of projectRealityDatas.realityDatas) { allProjectRealityDatas.push(rd); } } while (projectRealityDatas.continuationToken); } return allProjectRealityDatas; } it("should get RealityDataSource for all supported reality data in itwin project", async () => { const realityDatas = await getAllRealityDataFromProject(); for (const rd of realityDatas) { if (isSupportedType(rd.type)){ const keyFromInput: RealityDataSourceKey = createRealityDataListKeyFromITwinRealityData(rd); const rdSource = await RealityDataSource.fromKey(keyFromInput, iTwinId); expect(rdSource).not.undefined; expect(rdSource?.isContextShare).to.be.true; } } }); it("should be able to call getPublisherProductInfo on RealityDataSource for all supported displayable reality data in itwin project", async () => { const realityDatas = await getAllRealityDataFromProject(); for (const rd of realityDatas) { // Some types are supported and return by Context Share but required extension to be displayed (e.g: OMR) if (isSupportedDisplayType(rd.type)){ const keyFromInput: RealityDataSourceKey = createRealityDataListKeyFromITwinRealityData(rd); const rdSource = await RealityDataSource.fromKey(keyFromInput, iTwinId); expect(rdSource).not.undefined; expect(rdSource?.isContextShare).to.be.true; const pInfo = await rdSource?.getPublisherProductInfo(); // We expect to be able to return this info for all 3dTile, but it may contain empty string if (keyFromInput.format === RealityDataFormat.ThreeDTile) expect(pInfo).not.undefined; } } }); it("should be able to call getFileInfo when RealityDataSource is a 3dTile reality data", async () => { const realityDatas = await getAllRealityDataFromProject(); for (const rd of realityDatas) { // Some types are supported and return by Context Share but required extension to be displayed (e.g: OMR) if (isSupportedDisplayType(rd.type)){ const keyFromInput: RealityDataSourceKey = createRealityDataListKeyFromITwinRealityData(rd); const rdSource = await RealityDataSource.fromKey(keyFromInput, iTwinId); expect(rdSource).not.undefined; expect(rdSource?.isContextShare).to.be.true; // We expect to be able to return this info for all 3dTile if (rdSource && keyFromInput.format === RealityDataFormat.ThreeDTile) { const rootDocument = await rdSource.getRootDocument(undefined); const fileInfo = ThreeDTileFormatInterpreter.getFileInfo(rootDocument); expect(fileInfo).not.undefined; } } } }); it("should be able to call getSpatialLocationAndExtents on RealityDataSource for all supported displayable reality data in itwin project", async () => { const realityDatas = await getAllRealityDataFromProject(); for (const rd of realityDatas) { // Some types are supported and return by Context Share but required extension to be displayed (e.g: OMR) if (isSupportedDisplayType(rd.type)){ const keyFromInput: RealityDataSourceKey = createRealityDataListKeyFromITwinRealityData(rd); const rdSource = await RealityDataSource.fromKey(keyFromInput, iTwinId); expect(rdSource).not.undefined; expect(rdSource?.isContextShare).to.be.true; const spatialLocation = await rdSource?.getSpatialLocationAndExtents(); expect(spatialLocation).not.undefined; } } }); it("should get RealityDataSource for reality data attachment in iModel", async () => { assert.isTrue(imodel !== undefined); const modelRealityDataInfos = await getAttachedRealityDataModelInfoSet(imodel); expect(modelRealityDataInfos.size).to.equal(3); for (const entry of modelRealityDataInfos) { const rdSource = await RealityDataSource.fromKey(entry.key, iTwinId); expect(rdSource).not.undefined; expect(rdSource?.isContextShare).to.be.true; } }); it("should get RealityDataSource for Open Street Map Building (OSM)", async () => { assert.isTrue(imodel !== undefined); const rdSourceKey = getOSMBuildingsKey(); const rdSource = await RealityDataSource.fromKey(rdSourceKey, iTwinId); // NOTE: This test will fail if IMJS_CESIUM_ION_KEY is not defined in your .env file; const cesiumIonKey = process.env.IMJS_CESIUM_ION_KEY; assert.isDefined(cesiumIonKey, "This test will fail if IMJS_CESIUM_ION_KEY is not defined in your .env file"); if (cesiumIonKey !== undefined) { expect(rdSource).not.undefined; expect(rdSource?.isContextShare).to.be.false; } else { expect(rdSource).to.be.undefined; } }); });
the_stack
namespace Textor { export class TextController { public get isMozilla(): boolean { return this._isMozilla; } private _textEditor: TextEditor; private _canvas: HTMLCanvasElement; private _isWebKit: boolean; private _isChrome: boolean; private _isMozilla: boolean; private _isMac: boolean; private _textArea: HTMLTextAreaElement; private _scrollTimer: number; private _mouseCapture: boolean; private _pointerPosition: Point; private _keyCodeTable: any; private _canvas_mouseDownHandler: (e: MouseEvent) => void; private _window_mouseUpHandler: (e: MouseEvent) => void; private _window_mouseMoveHandler: (e: MouseEvent) => void; private _canvas_mouseWheelHandler: (e: MouseWheelEvent) => void; private _canvas_touchStartHandler: (e: TouchEvent) => void; private _canvas_touchEndHandler: (e: TouchEvent) => void; private _canvas_touchMoveHandler: (e: TouchEvent) => void; private _canvas_focusHandler: (e: FocusEvent) => void; private _textArea_keyUpHandler: (e: KeyboardEvent) => void; private _textArea_keyDownHandler: (e: KeyboardEvent) => void; private _textArea_keyPressHandler: (e: KeyboardEvent) => void; private _textArea_focusHandler: (e: FocusEvent) => void; private _textArea_blurHandler: (e: FocusEvent) => void; private _textArea_cutHandler: (e: DragEvent) => void; private _textArea_copyHandler: (e: DragEvent) => void; private _textArea_pasteHandler: (e: DragEvent) => void; private _textArea_beforeCutHandler: (e: DragEvent) => void; private _textArea_beforeCopyHandler: (e: DragEvent) => void; constructor(textEditor: TextEditor, canvas: HTMLCanvasElement) { this._textEditor = textEditor; this._canvas = canvas; this._isWebKit = typeof navigator.userAgent.split("WebKit/")[1] !== "undefined"; this._isChrome = navigator.userAgent.toLowerCase().indexOf("chrome") > -1; this._isMozilla = navigator.appVersion.indexOf("Gecko/") >= 0 || ((navigator.userAgent.indexOf("Gecko") >= 0) && !this._isWebKit && (typeof navigator.appVersion !== "undefined")); this._isMac = /Mac/.test(navigator.userAgent); this._textArea = document.createElement("textarea") as HTMLTextAreaElement; this._textArea.style.position = "absolute"; this._textArea.style.top = "0"; this._textArea.style.left = "0"; this._textArea.style.width = "0"; this._textArea.style.height = "0"; this._textArea.style.zIndex = "-99999"; this._textArea.style.margin = "0"; this._textArea.style.border = "0"; this._textArea.style.padding = "1px"; this._textArea.style.resize = "none"; this._textArea.style.outline = "none"; this._textArea.style.overflow = "hidden"; this._textArea.style.background = "none"; this._textArea.value = "."; document.body.appendChild(this._textArea); this.updateTextAreaPosition(); this._canvas_mouseDownHandler = (e: MouseEvent) => { this.canvas_mouseDown(e); }; this._canvas_mouseWheelHandler = (e: MouseWheelEvent) => { this.canvas_mouseWheel(e); }; this._canvas_touchStartHandler = (e: TouchEvent) => { this.canvas_touchStart(e); }; this._canvas_focusHandler = (e: FocusEvent) => { this.canvas_focus(e); }; this._window_mouseUpHandler = (e: MouseEvent) => { this.window_mouseUp(e); }; this._window_mouseMoveHandler = (e: MouseEvent) => { this.window_mouseMove(e); }; this._canvas_touchEndHandler = (e: TouchEvent) => { this.canvas_touchEnd(e); }; this._canvas_touchMoveHandler = (e: TouchEvent) => { this.canvas_touchMove(e); }; this._textArea_keyUpHandler = (e: KeyboardEvent) => { this.textArea_keyUp(e); }; this._textArea_keyDownHandler = (e: KeyboardEvent) => { this.textArea_keyDown(e); }; this._textArea_keyPressHandler = (e: KeyboardEvent) => { this.textArea_keyPress(e); }; this._textArea_focusHandler = (e: FocusEvent) => { this.textArea_focus(e); }; this._textArea_blurHandler = (e: FocusEvent) => { this.textArea_blur(e); }; this._textArea_cutHandler = (e: DragEvent) => { this.textArea_cut(e); }; this._textArea_copyHandler = (e: DragEvent) => { this.textArea_copy(e); }; this._textArea_pasteHandler = (e: DragEvent) => { this.textArea_paste(e); }; this._textArea_beforeCutHandler = (e: DragEvent) => { this.textArea_beforeCut(e); }; this._textArea_beforeCopyHandler = (e: DragEvent) => { this.textArea_beforeCopy(e); }; this._canvas.addEventListener("focus", this._canvas_focusHandler, false); this._canvas.addEventListener(("onmousewheel" in this._canvas) ? "mousewheel" : "DOMMouseScroll", this._canvas_mouseWheelHandler, false); this._canvas.addEventListener("touchstart", this._canvas_touchStartHandler, false); this._canvas.addEventListener("touchmove", this._canvas_touchMoveHandler, false); this._canvas.addEventListener("touchend", this._canvas_touchEndHandler, false); this._canvas.addEventListener("mousedown", this._canvas_mouseDownHandler, false); window.addEventListener("mousemove", this._window_mouseMoveHandler, false); window.addEventListener("mouseup", this._window_mouseUpHandler, false); this._textArea.addEventListener("focus", this._textArea_focusHandler, false); this._textArea.addEventListener("blur", this._textArea_blurHandler, false); this._textArea.addEventListener("cut", this._textArea_cutHandler, false); this._textArea.addEventListener("copy", this._textArea_copyHandler, false); this._textArea.addEventListener("paste", this._textArea_pasteHandler, false); this._textArea.addEventListener("beforecut", this._textArea_beforeCutHandler, false); this._textArea.addEventListener("beforecopy", this._textArea_beforeCopyHandler, false); this._textArea.addEventListener("keydown", this._textArea_keyDownHandler, false); this._textArea.addEventListener("keypress", this._textArea_keyPressHandler, false); this._textArea.addEventListener("keyup", this._textArea_keyUpHandler, false); } public dispose() { window.removeEventListener("mousemove", this._window_mouseMoveHandler); window.removeEventListener("mouseup", this._window_mouseUpHandler); this._canvas.removeEventListener("mousedown", this._canvas_mouseDownHandler); this._canvas.removeEventListener("touchend", this._canvas_touchEndHandler); this._canvas.removeEventListener("touchmove", this._canvas_touchMoveHandler); this._canvas.removeEventListener("touchstart", this._canvas_touchStartHandler); this._canvas.removeEventListener("focus", this._canvas_focusHandler); this._canvas.removeEventListener(("onmousewheel" in this._canvas) ? "mousewheel" : "DOMMouseScroll", this._canvas_mouseWheelHandler, false); this._textArea.removeEventListener("focus", this._textArea_focusHandler); this._textArea.removeEventListener("blur", this._textArea_blurHandler); this._textArea.removeEventListener("cut", this._textArea_cutHandler); this._textArea.removeEventListener("copy", this._textArea_copyHandler); this._textArea.removeEventListener("paste", this._textArea_pasteHandler); this._textArea.removeEventListener("beforecut", this._textArea_beforeCutHandler); this._textArea.removeEventListener("beforecopy", this._textArea_beforeCopyHandler); this._textArea.removeEventListener("keypress", this._textArea_keyPressHandler); this._textArea.removeEventListener("keyup", this._textArea_keyUpHandler); this._textArea.removeEventListener("keydown", this._textArea_keyDownHandler); } public isFocused() { return new RegExp("(^|\\s+)" + "focus" + "(\\s+|$)").test(this._canvas.className); } public focus() { this._textArea.focus(); } public copy(text: string) { if (this._isMozilla || this._isWebKit) { this._textArea.value = text; this._textArea.select(); } } public updateTextAreaPosition() { // hide the textarea under the canvas control const point = new Point(0, 0); let node: HTMLElement = this._canvas; while (node !== null) { point.x += node.offsetLeft; point.y += node.offsetTop; node = node.offsetParent as HTMLElement; } this._textArea.style.top = point.y + "px"; this._textArea.style.left = point.x + "px"; } private textArea_cut(e: DragEvent) { this._textEditor.cut(); } private textArea_copy(e: DragEvent) { this._textEditor.copy(); } private textArea_paste(e: DragEvent) { if (this._isMozilla) { this._textArea.value = ""; window.setTimeout(function() { const text = this._textArea.value; if (text.length > 0) { this._textEditor.paste(text); } }.bind(this), 1); } else if (this._isWebKit) { const text = e.clipboardData.getData("text/plain"); this._textEditor.paste(text); this.stopEvent(e); } } private textArea_beforeCut(e: DragEvent) { // select text in the text area so the cut event will fire. this._textEditor.copy(); } private textArea_beforeCopy(e: DragEvent) { this._textEditor.copy(); } private textArea_focus(e: FocusEvent) { if (!this.isFocused()) { this._canvas.className += " focus"; } this._textArea.select(); this._textEditor.invalidate(); this._textEditor.update(); } private textArea_blur(e: FocusEvent) { if (this.isFocused()) { this._canvas.className = this._canvas.className.replace(new RegExp(" focus\\b"), ""); } this._textEditor.invalidate(); // TODO calling update() will cause IE9 Beta1 to flicker } private canvas_focus(e: FocusEvent) { this._textEditor.focus(); } private canvas_mouseDown(e: MouseEvent) { this._textEditor.focus(); this.stopEvent(e); this.updatePointerPosition(e.pageX, e.pageY); const position = this.getTextPosition(); const clicks = ((e.detail - 1) % 3) + 1; if (clicks === 1) { if (!e.shiftKey) { this.pointerDown(); } else { this._textEditor.selectTo(position.line, position.column); } this._mouseCapture = true; this.startScrollTimer(); } else if (clicks === 2) { // select word at position this._textEditor.selectWord(position.line, position.column); this._mouseCapture = true; this.startScrollTimer(); } else if (clicks === 3) { this._textEditor.selectRange(position.line, 0, position.line + 1, 0); } this.updateMouseCursor(); } private window_mouseUp(e: MouseEvent) { e.preventDefault(); this.updatePointerPosition(e.pageX, e.pageY); this.pointerUp(); } private window_mouseMove(e: MouseEvent) { e.preventDefault(); this.updatePointerPosition(e.pageX, e.pageY); this.pointerMove(); } private canvas_mouseWheel(e: MouseWheelEvent) { e.preventDefault(); let delta: number = 0; if (!e) { delta = window.event.wheelDelta / 120; } if (e.wheelDelta) { delta = e.wheelDelta / 120; } else if (e.detail) { delta = -e.detail / 3; } if (delta !== 0) { this._textEditor.scroll(Math.floor(-delta), 0); this._textEditor.update(); } } private canvas_touchStart(e: TouchEvent) { this._textEditor.focus(); if (e.touches.length === 1) { e.preventDefault(); this.updatePointerPosition(e.touches[0].pageX, e.touches[0].pageY); this.pointerDown(); } } private canvas_touchMove(e: TouchEvent) { if (e.touches.length === 1) { e.preventDefault(); this.updatePointerPosition(e.touches[0].pageX, e.touches[0].pageY); this.pointerMove(); } } private canvas_touchEnd(e: TouchEvent) { e.preventDefault(); this.pointerUp(); } private textArea_keyUp(e: KeyboardEvent) { e.preventDefault(); } private textArea_keyDown(e: KeyboardEvent) { if (!this._isMozilla) { if (this.processKey(e.keyCode, e.shiftKey, e.ctrlKey, e.altKey, e.metaKey)) { this._textEditor.update(); this.stopEvent(e); } } } private textArea_keyPress(e: KeyboardEvent) { if (this._isMozilla) { if (!(this._keyCodeTable)) { this._keyCodeTable = []; const charCodeTable: any = { 32: " ", 48: "0", 49: "1", 50: "2", 51: "3", 52: "4", 53: "5", 54: "6", 55: "7", 56: "8", 57: "9", 59: ";", 61: "=", 65: "a", 66: "b", 67: "c", 68: "d", 69: "e", 70: "f", 71: "g", 72: "h", 73: "i", 74: "j", 75: "k", 76: "l", 77: "m", 78: "n", 79: "o", 80: "p", 81: "q", 82: "r", 83: "s", 84: "t", 85: "u", 86: "v", 87: "w", 88: "x", 89: "y", 90: "z", 107: "+", 109: "-", 110: ".", 188: ",", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: '\"', }; for (const code of Object.keys(charCodeTable)) { const key = charCodeTable[code]; this._keyCodeTable[key.charCodeAt(0)] = parseInt(code, 10); if (key.toUpperCase() !== key) { this._keyCodeTable[key.toUpperCase().charCodeAt(0)] = parseInt(code, 10); } } } const keyCode = ((e.charCode !== 0) && (this._keyCodeTable[e.charCode])) ? this._keyCodeTable[e.charCode] : e.keyCode; if (this.processKey(keyCode, e.shiftKey, e.ctrlKey, e.altKey, e.metaKey)) { this._textEditor.update(); this.stopEvent(e); return; } } // When ctrlKey and altKey both equals true, it means AltGr is pushed. So a valid combination is either false, false or true, true. if (e.ctrlKey === e.altKey && !e.metaKey && e.charCode !== 0) { this.stopEvent(e); const text: string = String.fromCharCode(e.charCode); this._textEditor.insertText(text); this._textEditor.updateScrollPosition(); this._textEditor.update(); } } private mouseScroll() { const textPosition: TextPosition = this.getTextPosition(); this._textEditor.selectTo(textPosition.line, textPosition.column); this._textEditor.updateScrollPosition(); this._textEditor.update(); } private mouseScroll_interval() { const textPosition: TextPosition = this.getTextCoordinate(); const size: TextPosition = this._textEditor.size; if ((textPosition.line < 0) || (textPosition.line >= size.line) || (textPosition.column < 0) || (textPosition.column >= size.column)) { this.mouseScroll(); } } private pointerDown() { const textPosition: TextPosition = this.getTextPosition(); this._textEditor.select(textPosition.line, textPosition.column); } private pointerMove() { if (this._mouseCapture) { this.mouseScroll(); } this.updateMouseCursor(); } private pointerUp() { this._mouseCapture = false; this.stopScrollTimer(); this.updateMouseCursor(); } private startScrollTimer() { this.stopScrollTimer(); this._scrollTimer = window.setInterval(this.mouseScroll_interval.bind(this), 75); } private stopScrollTimer() { if (this._scrollTimer !== null) { window.clearInterval(this._scrollTimer); this._scrollTimer = null; } } private stopEvent(e) { e.preventDefault(); e.stopPropagation(); } private updateMouseCursor() { this._canvas.style.cursor = "text"; } private updatePointerPosition(x, y) { const devicePixelRatio: number = this._textEditor.devicePixelRatio; this._pointerPosition = new Point(x * devicePixelRatio, y * devicePixelRatio); let node: HTMLElement = this._canvas; while (node !== null) { this._pointerPosition.x -= node.offsetLeft * devicePixelRatio; this._pointerPosition.y -= node.offsetTop * devicePixelRatio; node = node.offsetParent as HTMLElement; } } private getTextCoordinate() { const x = this._pointerPosition.x + (this._textEditor.fontSize.width / 2); const y = this._pointerPosition.y; return this._textEditor.getTextPosition(new Point(x, y)); } private getTextPosition() { const textPosition: TextPosition = this.getTextCoordinate(); textPosition.line += this._textEditor.scrollPosition.line; textPosition.column += this._textEditor.scrollPosition.column; return textPosition; } private processKey(keyCode: number, shiftKey: boolean, ctrlKey: boolean, altKey: boolean, metaKey: boolean) { if (this._isMac) { if (ctrlKey && !shiftKey && !altKey && !metaKey) { if (keyCode === 65) { ctrlKey = false; keyCode = 36; // HOME } else if (keyCode === 69) { ctrlKey = false; keyCode = 35; // END } } else if (metaKey && keyCode === 37) { metaKey = false; keyCode = 36; // HOME } else if (metaKey && keyCode === 39) { metaKey = false; keyCode = 35; // END } } return this._textEditor.processKey(keyCode, shiftKey, ctrlKey, altKey, metaKey); } } }
the_stack
import { Pulse } from './pulse'; import { Dep } from './internal'; import { copy, shallowmerge } from './utils'; import { deepmerge } from './helpers/deepmerge'; export class State<ValueType = any> { // a unique key for this State public name?: string; // internal storage for the current value public _value: ValueType = null; // getter for the current value public get value(): ValueType { if (this.instance().runtime.trackState) this.instance().runtime.foundState.add(this); return this._value; } // dependency manager class public dep: Dep; // watchers public watchers?: { [key: string]: any }; // the previous value of this State public previousState: ValueType = null; // a copy of the current value that will be used if no param is passed on State.set() public nextState: ValueType = null; // if the value has been changed from initial value public isSet: boolean = false; // should Pulse attempt to persist this State value public persistState: boolean; // if this State locked to a particular type public typeOfVal?: string; // history public enableHistory?: boolean; public history?: HistoryItem<ValueType>[]; // for extended classes to perform actions upon state change public sideEffects?: Function; public intervalId?: NodeJS.Timer | number; // // for extended classes to store a derived value, such as Group // public output?: any; // getter and setter for the State value, best for I/O binding public set mutable(value: ValueType) { this.set(value); } public get mutable(): ValueType { return this.value; } // is value truthey or falsey public get exists(): boolean { return !!this.value; } constructor(public instance: () => Pulse, public initialState?: ValueType | null, deps: Array<Dep> = []) { if (this.instance()._state.has(this)) this.instance()._state.delete(this); this.instance()._state.forEach((s) => { if (s?.name && this.name) { if (s.name === this.name) this.instance()._state.delete(s); } }) this.instance()._state.add(this); // initialize the dependency manager this.dep = new Dep(deps, () => this); // write the initial value to this State this.privateWrite(initialState === undefined ? null : initialState); } /** * Directly set state to a new value, if nothing is passed in State.nextState will be used as the next value * @param newState - The new value for this state */ public set(newState?: ValueType | SetFunc<ValueType>, options: { background?: boolean; _caller?: Function } = {}): this { // if newState not provided, just ingest update with existing value if (newState === undefined) { this.instance().runtime.ingest(this, undefined, { jobSpawnedFrom: options._caller }); return this; } // if newState is a function, run that function and supply existing value as first param if (typeof newState === 'function') newState = (newState as SetFunc<ValueType>)(this._value); // check type if set and correct otherwise exit if (this.typeOfVal && !this.isCorrectType(newState)) { console.warn(`Pulse: Error setting state: Incorrect type (${typeof newState}) was provided. Type fixed to ${this.typeOfVal}`); return this; } // ingest update using most basic mutation method if (options.background) { this.privateWrite(newState); if (this.sideEffects) this.sideEffects(); } else { this.instance().runtime.ingest(this, newState, { jobSpawnedFrom: options._caller }); } this.isSet = true; return this; } public getPublicValue(): ValueType { if (this['output'] !== undefined) return this['output']; return this._value; } public patch(targetWithChange, config: { deep?: boolean } = {}): this { if (!(typeof this._value === 'object')) return this; this.nextState = config.deep === false ? shallowmerge(this.nextState, targetWithChange) : deepmerge(this.nextState, targetWithChange); this.set(); return this; } /** * On a certain interval of milliseconds, set the state's value to the return value of a provided callback. * @param setFunc Function that returns the next value to be applied to state. * @param ms Time, in milliseconds, between individual runs of the interval. * @returns Native handle from `setInterval` that can be passed into `clearInterval`. */ public interval(setFunc: (currentValue: ValueType) => any, ms?: number): this { if (this.intervalId !== undefined) return this; this.intervalId = setInterval(() => { this.set(setFunc(this.value)); }, ms ?? 1000); return this; } public clearInterval(): void { if (this.intervalId) { clearInterval(this.intervalId as number); delete this.intervalId; } } public persist(key?: string): this { this.persistState = true; this.instance().storage.handleStatePersist(this, key); return this; } /** * @public * Create a watcher that will fire a callback then destroy itself after invoking */ public onNext(callback: (value: ValueType) => void) { if (!this.watchers) this.watchers = {}; this.watchers['_on_next_'] = () => { callback(this.getPublicValue()); delete this.watchers['_on_next_']; }; } /** * @public * Set a name for this State, required to persist */ public key(key: string): this { // if persist was attempted before, but no key was provided retry persist function if (!this.name && this.persistState) this.persist(key); this.name = key; return this; } /** * @public * Fix the type to one of 'String', 'Boolean', 'Array', 'Object' or 'Number' */ public type(type: TypeString | TypeConstructor): this { const supportedConstructors = ['String', 'Boolean', 'Array', 'Object', 'Number']; if (typeof type === 'function' && supportedConstructors.includes(type.name)) this.typeOfVal = type.name.toLowerCase(); else if (typeof type === 'string' && supportedConstructors.map(i => i.toLowerCase()).includes(type)) this.typeOfVal = type.toLowerCase(); return this; } /** * @public * Watch state for changes, run callback on each change */ public watch(callback: Callback<ValueType>): string | number; public watch(key: string | number, callback: Callback<ValueType>): this; public watch(keyOrCallback: string | number | Callback<ValueType>, callback?: Callback<ValueType>): this | string | number { if (!this.watchers) this.watchers = {}; let genKey = typeof keyOrCallback === 'function', key: string | number; if (genKey) { key = this.instance().getNonce(); callback = keyOrCallback as Callback<ValueType>; } else key = keyOrCallback as string | number; this.watchers[key] = callback; return genKey ? key : this; } /** * @public * Remove watcher by key */ public removeWatcher(key: string | number): this { if (this.watchers[key]) delete this.watchers[key]; return this; } /** * @public * Restore previous state */ public undo() { this.set(this.previousState); } /** * @public * Records all state changes */ public record(record?: boolean): this { if (!this.history) this.history = []; this.enableHistory = record === false ? false : true; return this; } /** * @public * If State is boolean, invert */ public toggle(): this { if (typeof this._value === 'boolean') { // @ts-ignore this.set(!this._value); } return this; } /** * @public * Reset the State to as declared */ public reset(): this { this.isSet = false; this.previousState = null; if (this.persistState) this.instance().storage.remove(this.name); this.instance().runtime.ingest(this, this.initialState); return this; } /** * @public * Returns a copy of the current value, objects and arrays will be cloned */ public copy(): ValueType { return copy(this.value); } /** * @public * Is the value equal to parameter */ public is(x: any) { return this.value === x; } /** * @public * Is the value not equal to parameter */ public isNot(x: any) { return this.value !== x; } /** * @internal * Write value directly to State */ public privateWrite(value: ValueType) { if (this.enableHistory) { this.history.push({ value: value, previousValue: this._value, timestamp: new Date() }); } if (this.instance().config.globalHistory) { this.instance().history.push({ value: value, previousValue: this._value, timestamp: new Date(), name: this.name }); } this._value = copy(value); this.nextState = copy(value); // If if (this.persistState) this.instance().storage.set(this.name, this.getPersistableValue()); } /** * @internal * */ private isCorrectType(value): boolean { let type: string = typeof value; if (type === 'object' && Array.isArray(value)) type = 'array'; return type === this.typeOfVal; } /** * @internal * */ public destroy(): void { this.dep.deps.clear(); this.dep.subs.clear(); } /** * @internal * */ public getPersistableValue(): any { return this.value; } } export type StateGroupDefault = { [key: string]: State | any; }; export const StateGroup = (instance: () => Pulse, stateGroup: Object): any => { let group: any = {}; for (let name in stateGroup) { group[name] = new State(instance, stateGroup[name]); group[name].name = name; } return group; }; export default State; export type SetFunc<ValueType> = (state: ValueType) => ValueType; type TypeString = 'string' | 'boolean' | 'array' | 'object' | 'number'; type TypeConstructor = StringConstructor | BooleanConstructor | ArrayConstructor | ObjectConstructor | NumberConstructor; export interface HistoryItem<ValueType = any> { previousValue: ValueType; value: ValueType; timestamp: Date; name?: string; } type Callback<T = any> = (value: T) => void;
the_stack
import * as FZ from 'fuzzaldrin' import { TextBuffer, Point, Disposable, Range, Directory } from 'atom' import { BufferInfo } from './buffer-info' import { ModuleInfo } from './module-info' import { GhcModiProcess } from '../ghc-mod' import * as Util from '../util' import * as UPI from 'atom-haskell-upi' import * as CB from 'atom-haskell-upi/completion-backend' const { handleException } = Util export class CompletionBackend implements CB.ICompletionBackend { private bufferMap: WeakMap<TextBuffer, BufferInfo> private dirMap: WeakMap<Directory, Map<string, ModuleInfo>> private modListMap: WeakMap<Directory, string[]> private languagePragmas: WeakMap<Directory, string[]> private compilerOptions: WeakMap<Directory, string[]> private isActive: boolean constructor( private process: GhcModiProcess, public upi: Promise<UPI.IUPIInstance>, ) { this.bufferMap = new WeakMap() this.dirMap = new WeakMap() this.modListMap = new WeakMap() this.languagePragmas = new WeakMap() this.compilerOptions = new WeakMap() // compatibility with old clients this.name = this.name.bind(this) this.onDidDestroy = this.onDidDestroy.bind(this) this.registerCompletionBuffer = this.registerCompletionBuffer.bind(this) this.unregisterCompletionBuffer = this.unregisterCompletionBuffer.bind(this) this.getCompletionsForSymbol = this.getCompletionsForSymbol.bind(this) this.getCompletionsForType = this.getCompletionsForType.bind(this) this.getCompletionsForClass = this.getCompletionsForClass.bind(this) this.getCompletionsForModule = this.getCompletionsForModule.bind(this) this.getCompletionsForSymbolInModule = this.getCompletionsForSymbolInModule.bind( this, ) this.getCompletionsForLanguagePragmas = this.getCompletionsForLanguagePragmas.bind( this, ) this.getCompletionsForCompilerOptions = this.getCompletionsForCompilerOptions.bind( this, ) this.getCompletionsForHole = this.getCompletionsForHole.bind(this) this.process = process this.isActive = true this.process.onDidDestroy(() => { this.isActive = false }) } /* Public interface below */ /* name() Get backend name Returns String, unique string describing a given backend */ public name() { return 'haskell-ghc-mod' } /* onDidDestroy(callback) Destruction event subscription. Usually should be called only on package deactivation. callback: () -> */ public onDidDestroy(callback: () => void) { if (!this.isActive) { throw new Error('Backend inactive') } return this.process.onDidDestroy(callback) } /* registerCompletionBuffer(buffer) Every buffer that would be used with autocompletion functions has to be registered with this function. buffer: TextBuffer, buffer to be used in autocompletion Returns: Disposable, which will remove buffer from autocompletion */ public registerCompletionBuffer(buffer: TextBuffer) { if (!this.isActive) { throw new Error('Backend inactive') } if (this.bufferMap.has(buffer)) { return new Disposable(() => { /* void */ }) } const { bufferInfo } = this.getBufferInfo({ buffer }) setImmediate(async () => { const { rootDir, moduleMap } = await this.getModuleMap({ bufferInfo }) // tslint:disable-next-line:no-floating-promises this.getModuleInfo({ bufferInfo, rootDir, moduleMap }) const imports = await bufferInfo.getImports() for (const imprt of imports) { // tslint:disable-next-line:no-floating-promises this.getModuleInfo({ moduleName: imprt.name, bufferInfo, rootDir, moduleMap, }) } }) return new Disposable(() => this.unregisterCompletionBuffer(buffer)) } /* unregisterCompletionBuffer(buffer) buffer: TextBuffer, buffer to be removed from autocompletion */ public unregisterCompletionBuffer(buffer: TextBuffer) { const x = this.bufferMap.get(buffer) if (x) { x.destroy() } } /* getCompletionsForSymbol(buffer,prefix,position) buffer: TextBuffer, current buffer prefix: String, completion prefix position: Point, current cursor position Returns: Promise([symbol]) symbol: Object, a completion symbol name: String, symbol name qname: String, qualified name, if module is qualified. Otherwise, same as name typeSignature: String, type signature symbolType: String, one of ['type', 'class', 'function'] module: Object, symbol module information qualified: Boolean, true if module is imported as qualified name: String, module name alias: String, module alias hiding: Boolean, true if module is imported with hiding clause importList: [String], array of explicit imports/hidden imports */ @handleException public async getCompletionsForSymbol( buffer: TextBuffer, prefix: string, _position: Point, ): Promise<CB.ISymbol[]> { if (!this.isActive) { throw new Error('Backend inactive') } const symbols = await this.getSymbolsForBuffer(buffer) return this.filter(symbols, prefix, ['qname', 'qparent']) } /* getCompletionsForType(buffer,prefix,position) buffer: TextBuffer, current buffer prefix: String, completion prefix position: Point, current cursor position Returns: Promise([symbol]) symbol: Same as getCompletionsForSymbol, except symbolType is one of ['type', 'class'] */ @handleException public async getCompletionsForType( buffer: TextBuffer, prefix: string, _position: Point, ): Promise<CB.ISymbol[]> { if (!this.isActive) { throw new Error('Backend inactive') } const symbols = await this.getSymbolsForBuffer(buffer, ['type', 'class']) return FZ.filter(symbols, prefix, { key: 'qname' }) } /* getCompletionsForClass(buffer,prefix,position) buffer: TextBuffer, current buffer prefix: String, completion prefix position: Point, current cursor position Returns: Promise([symbol]) symbol: Same as getCompletionsForSymbol, except symbolType is one of ['class'] */ public async getCompletionsForClass( buffer: TextBuffer, prefix: string, _position: Point, ): Promise<CB.ISymbol[]> { if (!this.isActive) { throw new Error('Backend inactive') } const symbols = await this.getSymbolsForBuffer(buffer, ['class']) return FZ.filter(symbols, prefix, { key: 'qname' }) } /* getCompletionsForModule(buffer,prefix,position) buffer: TextBuffer, current buffer prefix: String, completion prefix position: Point, current cursor position Returns: Promise([module]) module: String, module name */ public async getCompletionsForModule( buffer: TextBuffer, prefix: string, _position: Point, ): Promise<string[]> { if (!this.isActive) { throw new Error('Backend inactive') } const rootDir = await this.process.getRootDir(buffer) let modules = this.modListMap.get(rootDir) if (!modules) { modules = await this.process.runList(buffer) this.modListMap.set(rootDir, modules) // refresh every minute setTimeout(() => this.modListMap.delete(rootDir), 60 * 1000) } return FZ.filter(modules, prefix) } /* getCompletionsForSymbolInModule(buffer,prefix,position,{module}) Used in import hiding/list completions buffer: TextBuffer, current buffer prefix: String, completion prefix position: Point, current cursor position module: String, module name (optional). If undefined, function will attempt to infer module name from position and buffer. Returns: Promise([symbol]) symbol: Object, symbol in given module name: String, symbol name typeSignature: String, type signature symbolType: String, one of ['type', 'class', 'function'] */ public async getCompletionsForSymbolInModule( buffer: TextBuffer, prefix: string, position: Point, opts?: { module: string }, ): Promise<CB.ISymbol[]> { if (!this.isActive) { throw new Error('Backend inactive') } let moduleName = opts ? opts.module : undefined if (!moduleName) { const lineRange = new Range([0, position.row], position) buffer.backwardsScanInRange( /^import\s+([\w.]+)/, lineRange, ({ match }) => (moduleName = match[1]), ) } const { bufferInfo } = this.getBufferInfo({ buffer }) const mis = await this.getModuleInfo({ bufferInfo, moduleName }) // tslint:disable: no-null-keyword const symbols = await mis.moduleInfo.select( { qualified: false, hiding: false, name: moduleName || mis.moduleName, importList: null, alias: null, }, undefined, true, ) // tslint:enable: no-null-keyword return FZ.filter(symbols, prefix, { key: 'name' }) } /* getCompletionsForLanguagePragmas(buffer,prefix,position) buffer: TextBuffer, current buffer prefix: String, completion prefix position: Point, current cursor position Returns: Promise([pragma]) pragma: String, language option */ public async getCompletionsForLanguagePragmas( buffer: TextBuffer, prefix: string, _position: Point, ): Promise<string[]> { if (!this.isActive) { throw new Error('Backend inactive') } const dir = await this.process.getRootDir(buffer) let ps = this.languagePragmas.get(dir) if (!ps) { ps = await this.process.runLang(dir) ps && this.languagePragmas.set(dir, ps) } return FZ.filter(ps, prefix) } /* getCompletionsForCompilerOptions(buffer,prefix,position) buffer: TextBuffer, current buffer prefix: String, completion prefix position: Point, current cursor position Returns: Promise([ghcopt]) ghcopt: String, compiler option (starts with '-f') */ public async getCompletionsForCompilerOptions( buffer: TextBuffer, prefix: string, _position: Point, ): Promise<string[]> { if (!this.isActive) { throw new Error('Backend inactive') } const dir = await this.process.getRootDir(buffer) let co = this.compilerOptions.get(dir) if (!co) { co = await this.process.runFlag(dir) this.compilerOptions.set(dir, co) } return FZ.filter(co, prefix) } /* getCompletionsForHole(buffer,prefix,position) Get completions based on expression type. It is assumed that `prefix` starts with '_' buffer: TextBuffer, current buffer prefix: String, completion prefix position: Point, current cursor position Returns: Promise([symbol]) symbol: Same as getCompletionsForSymbol */ @handleException public async getCompletionsForHole( buffer: TextBuffer, prefix: string, position: Point, ): Promise<CB.ISymbol[]> { if (!this.isActive) { throw new Error('Backend inactive') } const range = new Range(position, position) if (prefix.startsWith('_')) { prefix = prefix.slice(1) } const { type } = await this.process.getTypeInBuffer(buffer, range) const symbols = await this.getSymbolsForBuffer(buffer) const ts = symbols.filter((s) => { if (!s.typeSignature) { return false } const tl = s.typeSignature.split(' -> ').slice(-1)[0] if (tl.match(/^[a-z]$/)) { return false } const ts2 = tl.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&') const rx = RegExp(ts2.replace(/\b[a-z]\b/g, '.+'), '') return rx.test(type) }) if (prefix.length === 0) { return ts.sort( (a, b) => // tslint:disable-next-line: no-non-null-assertion FZ.score(b.typeSignature!, type) - FZ.score(a.typeSignature!, type), ) } else { return FZ.filter(ts, prefix, { key: 'qname' }) } } private async getSymbolsForBuffer( buffer: TextBuffer, symbolTypes?: CB.SymbolType[], ): Promise<CB.ISymbol[]> { const { bufferInfo } = this.getBufferInfo({ buffer }) const { rootDir, moduleMap } = await this.getModuleMap({ bufferInfo }) if (bufferInfo && moduleMap) { const imports = await bufferInfo.getImports() const promises = await Promise.all( imports.map(async (imp) => { const res = await this.getModuleInfo({ bufferInfo, moduleName: imp.name, rootDir, moduleMap, }) if (!res) { return [] } return res.moduleInfo.select(imp, symbolTypes) }), ) return ([] as typeof promises[0]).concat(...promises) } else { return [] } } private getBufferInfo({ buffer, }: { buffer: TextBuffer }): { bufferInfo: BufferInfo } { let bi = this.bufferMap.get(buffer) if (!bi) { bi = new BufferInfo(buffer) this.bufferMap.set(buffer, bi) } return { bufferInfo: bi } } private async getModuleMap({ bufferInfo, rootDir, }: { bufferInfo: BufferInfo rootDir?: Directory }): Promise<{ rootDir: Directory; moduleMap: Map<string, ModuleInfo> }> { if (!rootDir) { rootDir = await this.process.getRootDir(bufferInfo.buffer) } let mm = this.dirMap.get(rootDir) if (!mm) { mm = new Map() this.dirMap.set(rootDir, mm) } return { rootDir, moduleMap: mm, } } private async getModuleInfo(arg: { bufferInfo: BufferInfo moduleName?: string rootDir?: Directory moduleMap?: Map<string, ModuleInfo> }) { const { bufferInfo } = arg let dat if (arg.rootDir && arg.moduleMap) { dat = { rootDir: arg.rootDir, moduleMap: arg.moduleMap } } else { dat = await this.getModuleMap({ bufferInfo }) } const { moduleMap, rootDir } = dat let moduleName = arg.moduleName if (!moduleName) { moduleName = await bufferInfo.getModuleName() } if (!moduleName) { throw new Error(`Nameless module in ${bufferInfo.buffer.getUri()}`) } let moduleInfo = moduleMap.get(moduleName) if (!moduleInfo) { moduleInfo = new ModuleInfo(moduleName, this.process, rootDir) moduleMap.set(moduleName, moduleInfo) const mn = moduleName moduleInfo.onDidDestroy(() => { moduleMap.delete(mn) Util.debug(`${moduleName} removed from map`) }) } await moduleInfo.setBuffer(bufferInfo) return { bufferInfo, rootDir, moduleMap, moduleInfo, moduleName } } private filter<T, K extends keyof T>( candidates: T[], prefix: string, keys: K[], ): T[] { if (!prefix) { return candidates } const list = [] for (const candidate of candidates) { const scores = keys.map((key) => { const ck = candidate[key] if (ck) { return FZ.score(ck.toString(), prefix) } else { return 0 } }) const score = Math.max(...scores) if (score > 0) { list.push({ score, scoreN: scores.indexOf(score), data: candidate, }) } } return list .sort((a, b) => { const s = b.score - a.score if (s === 0) { return a.scoreN - b.scoreN } return s }) .map(({ data }) => data) } }
the_stack
import { Template } from '@aws-cdk/assertions'; import * as iam from '@aws-cdk/aws-iam'; import { Duration, RemovalPolicy, Stack } from '@aws-cdk/core'; import * as route53 from '../lib'; describe('record set', () => { test('with default ttl', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); // WHEN new route53.RecordSet(stack, 'Basic', { zone, recordName: 'www', recordType: route53.RecordType.CNAME, target: route53.RecordTarget.fromValues('zzz'), }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: 'www.myzone.', Type: 'CNAME', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, ResourceRecords: [ 'zzz', ], TTL: '1800', }); }); test('with custom ttl', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); // WHEN new route53.RecordSet(stack, 'Basic', { zone, recordName: 'aa', recordType: route53.RecordType.CNAME, target: route53.RecordTarget.fromValues('bbb'), ttl: Duration.seconds(6077), }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: 'aa.myzone.', Type: 'CNAME', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, ResourceRecords: [ 'bbb', ], TTL: '6077', }); }); test('with ttl of 0', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); // WHEN new route53.RecordSet(stack, 'Basic', { zone, recordName: 'aa', recordType: route53.RecordType.CNAME, target: route53.RecordTarget.fromValues('bbb'), ttl: Duration.seconds(0), }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { TTL: '0', }); }); test('defaults to zone root', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); // WHEN new route53.RecordSet(stack, 'Basic', { zone, recordType: route53.RecordType.A, target: route53.RecordTarget.fromValues('1.2.3.4'), }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: 'myzone.', Type: 'A', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, ResourceRecords: [ '1.2.3.4', ], }); }); test('A record with ip addresses', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); // WHEN new route53.ARecord(stack, 'A', { zone, recordName: 'www', target: route53.RecordTarget.fromIpAddresses('1.2.3.4', '5.6.7.8'), }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: 'www.myzone.', Type: 'A', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, ResourceRecords: [ '1.2.3.4', '5.6.7.8', ], TTL: '1800', }); }); test('A record with alias', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); const target: route53.IAliasRecordTarget = { bind: () => { return { hostedZoneId: 'Z2P70J7EXAMPLE', dnsName: 'foo.example.com', }; }, }; // WHEN new route53.ARecord(zone, 'Alias', { zone, recordName: '_foo', target: route53.RecordTarget.fromAlias(target), }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: '_foo.myzone.', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, Type: 'A', AliasTarget: { HostedZoneId: 'Z2P70J7EXAMPLE', DNSName: 'foo.example.com', }, }); }); test('AAAA record with ip addresses', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); // WHEN new route53.AaaaRecord(stack, 'AAAA', { zone, recordName: 'www', target: route53.RecordTarget.fromIpAddresses('2001:0db8:85a3:0000:0000:8a2e:0370:7334'), }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: 'www.myzone.', Type: 'AAAA', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, ResourceRecords: [ '2001:0db8:85a3:0000:0000:8a2e:0370:7334', ], TTL: '1800', }); }); test('AAAA record with alias on zone root', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); const target: route53.IAliasRecordTarget = { bind: () => { return { hostedZoneId: 'Z2P70J7EXAMPLE', dnsName: 'foo.example.com', }; }, }; // WHEN new route53.AaaaRecord(zone, 'Alias', { zone, target: route53.RecordTarget.fromAlias(target), }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: 'myzone.', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, Type: 'AAAA', AliasTarget: { HostedZoneId: 'Z2P70J7EXAMPLE', DNSName: 'foo.example.com', }, }); }); test('CNAME record', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); // WHEN new route53.CnameRecord(stack, 'CNAME', { zone, recordName: 'www', domainName: 'hello', }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: 'www.myzone.', Type: 'CNAME', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, ResourceRecords: [ 'hello', ], TTL: '1800', }); }); test('TXT record', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); // WHEN new route53.TxtRecord(stack, 'TXT', { zone, recordName: 'www', values: ['should be enclosed with double quotes'], }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: 'www.myzone.', Type: 'TXT', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, ResourceRecords: [ '"should be enclosed with double quotes"', ], TTL: '1800', }); }); test('TXT record with value longer than 255 chars', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); // WHEN new route53.TxtRecord(stack, 'TXT', { zone, recordName: 'www', values: ['hello'.repeat(52)], }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: 'www.myzone.', Type: 'TXT', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, ResourceRecords: [ '"hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello""hello"', ], TTL: '1800', }); }); test('SRV record', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); // WHEN new route53.SrvRecord(stack, 'SRV', { zone, recordName: 'www', values: [{ hostName: 'aws.com', port: 8080, priority: 10, weight: 5, }], }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: 'www.myzone.', Type: 'SRV', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, ResourceRecords: [ '10 5 8080 aws.com', ], TTL: '1800', }); }); test('CAA record', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); // WHEN new route53.CaaRecord(stack, 'CAA', { zone, recordName: 'www', values: [{ flag: 0, tag: route53.CaaTag.ISSUE, value: 'ssl.com', }], }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: 'www.myzone.', Type: 'CAA', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, ResourceRecords: [ '0 issue "ssl.com"', ], TTL: '1800', }); }); test('CAA Amazon record', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); // WHEN new route53.CaaAmazonRecord(stack, 'CAAAmazon', { zone, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: 'myzone.', Type: 'CAA', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, ResourceRecords: [ '0 issue "amazon.com"', ], TTL: '1800', }); }); test('CAA Amazon record with record name', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); // WHEN new route53.CaaAmazonRecord(stack, 'CAAAmazon', { zone, recordName: 'www', }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: 'www.myzone.', Type: 'CAA', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, ResourceRecords: [ '0 issue "amazon.com"', ], TTL: '1800', }); }); test('MX record', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); // WHEN new route53.MxRecord(stack, 'MX', { zone, recordName: 'mail', values: [{ hostName: 'workmail.aws', priority: 10, }], }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: 'mail.myzone.', Type: 'MX', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, ResourceRecords: [ '10 workmail.aws', ], TTL: '1800', }); }); test('NS record', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); // WHEN new route53.NsRecord(stack, 'NS', { zone, recordName: 'www', values: ['ns-1.awsdns.co.uk.', 'ns-2.awsdns.com.'], }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: 'www.myzone.', Type: 'NS', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, ResourceRecords: [ 'ns-1.awsdns.co.uk.', 'ns-2.awsdns.com.', ], TTL: '1800', }); }); test('DS record', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); // WHEN new route53.DsRecord(stack, 'DS', { zone, recordName: 'www', values: ['12345 3 1 123456789abcdef67890123456789abcdef67890'], }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: 'www.myzone.', Type: 'DS', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, ResourceRecords: [ '12345 3 1 123456789abcdef67890123456789abcdef67890', ], TTL: '1800', }); }); test('Zone delegation record', () => { // GIVEN const stack = new Stack(); const zone = new route53.HostedZone(stack, 'HostedZone', { zoneName: 'myzone', }); // WHEN new route53.ZoneDelegationRecord(stack, 'NS', { zone, recordName: 'foo', nameServers: ['ns-1777.awsdns-30.co.uk'], }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::Route53::RecordSet', { Name: 'foo.myzone.', Type: 'NS', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, ResourceRecords: [ 'ns-1777.awsdns-30.co.uk.', ], TTL: '172800', }); }); test('Cross account zone delegation record with parentHostedZoneId', () => { // GIVEN const stack = new Stack(); const parentZone = new route53.PublicHostedZone(stack, 'ParentHostedZone', { zoneName: 'myzone.com', crossAccountZoneDelegationPrincipal: new iam.AccountPrincipal('123456789012'), }); // WHEN const childZone = new route53.PublicHostedZone(stack, 'ChildHostedZone', { zoneName: 'sub.myzone.com', }); new route53.CrossAccountZoneDelegationRecord(stack, 'Delegation', { delegatedZone: childZone, parentHostedZoneId: parentZone.hostedZoneId, delegationRole: parentZone.crossAccountZoneDelegationRole!, ttl: Duration.seconds(60), removalPolicy: RemovalPolicy.RETAIN, }); // THEN Template.fromStack(stack).hasResourceProperties('Custom::CrossAccountZoneDelegation', { ServiceToken: { 'Fn::GetAtt': [ 'CustomCrossAccountZoneDelegationCustomResourceProviderHandler44A84265', 'Arn', ], }, AssumeRoleArn: { 'Fn::GetAtt': [ 'ParentHostedZoneCrossAccountZoneDelegationRole95B1C36E', 'Arn', ], }, ParentZoneId: { Ref: 'ParentHostedZoneC2BD86E1', }, DelegatedZoneName: 'sub.myzone.com', DelegatedZoneNameServers: { 'Fn::GetAtt': [ 'ChildHostedZone4B14AC71', 'NameServers', ], }, TTL: 60, }); Template.fromStack(stack).hasResource('Custom::CrossAccountZoneDelegation', { DeletionPolicy: 'Retain', UpdateReplacePolicy: 'Retain', }); }); test('Cross account zone delegation record with parentHostedZoneName', () => { // GIVEN const stack = new Stack(); const parentZone = new route53.PublicHostedZone(stack, 'ParentHostedZone', { zoneName: 'myzone.com', crossAccountZoneDelegationPrincipal: new iam.AccountPrincipal('123456789012'), }); // WHEN const childZone = new route53.PublicHostedZone(stack, 'ChildHostedZone', { zoneName: 'sub.myzone.com', }); new route53.CrossAccountZoneDelegationRecord(stack, 'Delegation', { delegatedZone: childZone, parentHostedZoneName: 'myzone.com', delegationRole: parentZone.crossAccountZoneDelegationRole!, ttl: Duration.seconds(60), }); // THEN Template.fromStack(stack).hasResourceProperties('Custom::CrossAccountZoneDelegation', { ServiceToken: { 'Fn::GetAtt': [ 'CustomCrossAccountZoneDelegationCustomResourceProviderHandler44A84265', 'Arn', ], }, AssumeRoleArn: { 'Fn::GetAtt': [ 'ParentHostedZoneCrossAccountZoneDelegationRole95B1C36E', 'Arn', ], }, ParentZoneName: 'myzone.com', DelegatedZoneName: 'sub.myzone.com', DelegatedZoneNameServers: { 'Fn::GetAtt': [ 'ChildHostedZone4B14AC71', 'NameServers', ], }, TTL: 60, }); }); test('Cross account zone delegation record throws when parent id and name both/nither are supplied', () => { // GIVEN const stack = new Stack(); const parentZone = new route53.PublicHostedZone(stack, 'ParentHostedZone', { zoneName: 'myzone.com', crossAccountZoneDelegationPrincipal: new iam.AccountPrincipal('123456789012'), }); // THEN const childZone = new route53.PublicHostedZone(stack, 'ChildHostedZone', { zoneName: 'sub.myzone.com', }); expect(() => { new route53.CrossAccountZoneDelegationRecord(stack, 'Delegation1', { delegatedZone: childZone, delegationRole: parentZone.crossAccountZoneDelegationRole!, ttl: Duration.seconds(60), }); }).toThrow(/At least one of parentHostedZoneName or parentHostedZoneId is required/); expect(() => { new route53.CrossAccountZoneDelegationRecord(stack, 'Delegation2', { delegatedZone: childZone, parentHostedZoneId: parentZone.hostedZoneId, parentHostedZoneName: parentZone.zoneName, delegationRole: parentZone.crossAccountZoneDelegationRole!, ttl: Duration.seconds(60), }); }).toThrow(/Only one of parentHostedZoneName and parentHostedZoneId is supported/); }); test('Multiple cross account zone delegation records', () => { // GIVEN const stack = new Stack(); const parentZone = new route53.PublicHostedZone(stack, 'ParentHostedZone', { zoneName: 'myzone.com', crossAccountZoneDelegationPrincipal: new iam.AccountPrincipal('123456789012'), }); // WHEN const childZone = new route53.PublicHostedZone(stack, 'ChildHostedZone', { zoneName: 'sub.myzone.com', }); new route53.CrossAccountZoneDelegationRecord(stack, 'Delegation', { delegatedZone: childZone, parentHostedZoneName: 'myzone.com', delegationRole: parentZone.crossAccountZoneDelegationRole!, ttl: Duration.seconds(60), }); const childZone2 = new route53.PublicHostedZone(stack, 'ChildHostedZone2', { zoneName: 'anothersub.myzone.com', }); new route53.CrossAccountZoneDelegationRecord(stack, 'Delegation2', { delegatedZone: childZone2, parentHostedZoneName: 'myzone.com', delegationRole: parentZone.crossAccountZoneDelegationRole!, ttl: Duration.seconds(60), }); // THEN const childHostedZones = [ { name: 'sub.myzone.com', id: 'ChildHostedZone4B14AC71', dependsOn: 'DelegationcrossaccountzonedelegationhandlerrolePolicy1E157602' }, { name: 'anothersub.myzone.com', id: 'ChildHostedZone2A37198F0', dependsOn: 'Delegation2crossaccountzonedelegationhandlerrolePolicy713BEAC3' }, ]; for (var childHostedZone of childHostedZones) { Template.fromStack(stack).hasResource('Custom::CrossAccountZoneDelegation', { Properties: { ServiceToken: { 'Fn::GetAtt': [ 'CustomCrossAccountZoneDelegationCustomResourceProviderHandler44A84265', 'Arn', ], }, AssumeRoleArn: { 'Fn::GetAtt': [ 'ParentHostedZoneCrossAccountZoneDelegationRole95B1C36E', 'Arn', ], }, ParentZoneName: 'myzone.com', DelegatedZoneName: childHostedZone.name, DelegatedZoneNameServers: { 'Fn::GetAtt': [ childHostedZone.id, 'NameServers', ], }, TTL: 60, }, DependsOn: [ childHostedZone.dependsOn, ], }); } }); test('Cross account zone delegation policies', () => { // GIVEN const stack = new Stack(); const parentZone = new route53.PublicHostedZone(stack, 'ParentHostedZone', { zoneName: 'myzone.com', crossAccountZoneDelegationPrincipal: new iam.AccountPrincipal('123456789012'), }); // WHEN const childZone = new route53.PublicHostedZone(stack, 'ChildHostedZone', { zoneName: 'sub.myzone.com', }); new route53.CrossAccountZoneDelegationRecord(stack, 'Delegation', { delegatedZone: childZone, parentHostedZoneName: 'myzone.com', delegationRole: parentZone.crossAccountZoneDelegationRole!, ttl: Duration.seconds(60), }); const childZone2 = new route53.PublicHostedZone(stack, 'ChildHostedZone2', { zoneName: 'anothersub.myzone.com', }); new route53.CrossAccountZoneDelegationRecord(stack, 'Delegation2', { delegatedZone: childZone2, parentHostedZoneName: 'myzone.com', delegationRole: parentZone.crossAccountZoneDelegationRole!, ttl: Duration.seconds(60), }); // THEN const policyNames = [ 'DelegationcrossaccountzonedelegationhandlerrolePolicy1E157602', 'Delegation2crossaccountzonedelegationhandlerrolePolicy713BEAC3', ]; for (var policyName of policyNames) { Template.fromStack(stack).hasResourceProperties('AWS::IAM::Policy', { PolicyName: policyName, PolicyDocument: { Version: '2012-10-17', Statement: [ { Action: 'sts:AssumeRole', Effect: 'Allow', Resource: { 'Fn::GetAtt': [ 'ParentHostedZoneCrossAccountZoneDelegationRole95B1C36E', 'Arn', ], }, }, ], }, Roles: [ { 'Fn::Select': [1, { 'Fn::Split': ['/', { 'Fn::Select': [5, { 'Fn::Split': [':', { 'Fn::GetAtt': [ 'CustomCrossAccountZoneDelegationCustomResourceProviderRoleED64687B', 'Arn', ], }], }], }], }], }, ], }); } }); });
the_stack
import { format as formatDate, parseISO as parseDate } from 'date-fns'; import * as React from 'react'; import { DateInput, DateTimeInput } from 'semantic-ui-calendar-react'; import { Button, Checkbox, CheckboxProps, DropdownProps, Form, Header, Input, Label } from 'semantic-ui-react'; import { RequestError } from '../../../api/common'; import { Cardinality, FormField, FormFieldType, FormInstanceEntry } from '../../../api/process/form'; import { DropdownWithAddition } from '../../molecules'; import { RequestErrorMessage } from '../index'; // date-fns format patterns const DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; // moment.js format patterns const MOMENT_DATE_FORMAT = 'YYYY-MM-DD'; const MOMENT_DATE_TIME_FORMAT = 'YYYY-MM-DDTHH:mm:ss.SSSZ'; interface State { [name: string]: any; } interface Props { form: FormInstanceEntry; errors?: { [name: string]: string; }; submitting?: boolean; submitError?: RequestError; completed?: boolean; wizard?: boolean; onSubmit: (values: State) => void; onReturn: () => void; } type DropdownAllowedValue = Array<boolean | number | string> | undefined; type DropdownValue = boolean | number | string | DropdownAllowedValue; const convertAllowedValue = (allowedValue: any) => { if (allowedValue === undefined) { return []; } if (allowedValue instanceof Array) { return allowedValue; } return [allowedValue]; }; class ProcessForm extends React.Component<Props, State> { constructor(props: Props) { super(props); this.state = {}; } handleReturn(ev: React.FormEvent<HTMLButtonElement>) { ev.preventDefault(); this.props.onReturn(); } handleSubmit(ev: React.FormEvent<HTMLFormElement>) { ev.preventDefault(); let values = { ...this.state }; if (!values) { values = {}; } const { form, onSubmit } = this.props; for (const f of form.fields) { const k = f.name; const v = values[k]; const t = f.type; if (v === null || v === undefined) { values[k] = f.value; } else if (v === '') { values[k] = null; } else if ((t === FormFieldType.INT || t === FormFieldType.DECIMAL) && isNaN(v)) { values[k] = null; } if ( (t === FormFieldType.DATE || t === FormFieldType.DATE_TIME) && values[k] !== undefined ) { // Append the client zone information for date format consistency const d = parseDate(values[k]); values[k] = formatDate(d, DATE_TIME_FORMAT); } } // remove undefined values const result = {}; Object.keys(values).forEach((k) => { const v = values[k]; if (v !== undefined && v !== null) { result[k] = v; } }); onSubmit(result); } handleInput( name: string, type: FormFieldType ): (event: React.SyntheticEvent<HTMLInputElement>) => void { return ({ target }) => { const t = target as HTMLInputElement; let v: string | number | boolean | File = t.value; if (type === FormFieldType.INT || type === FormFieldType.DECIMAL) { v = t.valueAsNumber; } else if (type === FormFieldType.FILE) { v = t.files![0]; } this.setState({ [name]: v }); }; } handleDateInput(name: string): (e: React.SyntheticEvent<HTMLElement>, data: any) => void { return (ev, { value }) => { this.setState({ [name]: value }); }; } handleDropdown( name: string ): (event: React.SyntheticEvent<HTMLElement>, data: DropdownProps) => void { return (ev, { value }) => { this.setState({ [name]: value }); }; } handleCheckboxInput( name: string ): (event: React.FormEvent<HTMLInputElement>, data: CheckboxProps) => void { return (ev, { checked }) => { this.setState({ [name]: checked }); }; } renderInput(name: string, type: FormFieldType, value: any, inputType?: string, opts?: {}) { const { submitting, completed } = this.props; return ( <Input name={name} disabled={submitting || completed} defaultValue={value} type={inputType} onChange={this.handleInput(name, type)} {...opts} /> ); } renderDropdown( name: string, cardinality: Cardinality, value: DropdownValue, allowedValue: DropdownAllowedValue, multiple: boolean, opts?: {} ) { const { submitting, completed } = this.props; const options = allowedValue ? allowedValue.map((v) => ({ text: v, value: v })) : []; const required = cardinality === Cardinality.AT_LEAST_ONE || cardinality === Cardinality.ONE_AND_ONLY_ONE; const allowAdditions = options.length === 0; if (value === null) { value = undefined; } if (multiple && value === undefined) { value = []; } return ( <DropdownWithAddition name={name} options={options} value={value} required={required} multiple={multiple} completed={completed} submitting={submitting} allowAdditions={allowAdditions} onChange={this.handleDropdown(name)} {...opts} /> ); } renderStringField( { name, label, type, cardinality, allowedValue, options }: FormField, value: any ) { const { errors } = this.props; const error = errors ? errors[name] : undefined; const inputType = options ? options.inputType : undefined; if (!cardinality) { cardinality = Cardinality.ONE_OR_NONE; } const required = cardinality === Cardinality.AT_LEAST_ONE || cardinality === Cardinality.ONE_AND_ONLY_ONE; const allowedValues = convertAllowedValue(allowedValue); const fixedInput = required && allowedValues.length === 1; if (fixedInput) { value = allowedValues[0]; } const singleValue = cardinality === Cardinality.ONE_AND_ONLY_ONE || cardinality === Cardinality.ONE_OR_NONE; const input = fixedInput || (singleValue && allowedValues.length === 0); const dropdown = !input; const multiSelect = (cardinality === Cardinality.AT_LEAST_ONE || cardinality === Cardinality.ANY) && allowedValues.length !== 1; return ( <Form.Field key={name} error={!!error} required={required}> <label>{label}</label> {dropdown ? this.renderDropdown( name, cardinality, value, allowedValues, multiSelect, options ) : this.renderInput(name, type, value, inputType, { readOnly: fixedInput, ...options })} {error && ( <Label basic={true} color="red" pointing={true}> {error} </Label> )} </Form.Field> ); } renderNumberField({ name, label, type, options }: FormField, value?: number) { const { errors } = this.props; const error = errors ? errors[name] : undefined; if (value !== undefined && isNaN(value)) { value = undefined; } return ( <Form.Field key={name} error={!!error}> <label>{label}</label> {this.renderInput(name, type, value, 'number', { step: type === 'decimal' ? 'any' : '1', ...options })} {error && ( <Label basic={true} color="red" pointing={true}> {error} </Label> )} </Form.Field> ); } renderBooleanField({ name, label, type, options }: FormField, value: boolean) { const { errors, submitting, completed } = this.props; const error = errors ? errors[name] : undefined; return ( <Form.Field key={name} error={!!error}> <label>{label}</label> <Checkbox name={name} disabled={submitting || completed} defaultChecked={value} onChange={this.handleCheckboxInput(name)} {...options} /> {error && ( <Label basic={true} color="red" pointing={true}> {error} </Label> )} </Form.Field> ); } renderFileField({ name, label, type, cardinality }: FormField) { const { errors, submitting, completed } = this.props; const error = errors ? errors[name] : undefined; const required = cardinality === Cardinality.ONE_AND_ONLY_ONE; return ( <Form.Field key={name} error={!!error} required={required}> <label>{label}</label> <Input name={name} type="file" disabled={submitting || completed} onChange={this.handleInput(name, type)} /> {error && ( <Label basic={true} color="red" pointing={true}> {error} </Label> )} </Form.Field> ); } renderDateField({ name, label, cardinality, type, options }: FormField, value: any) { const { errors } = this.props; const error = errors ? errors[name] : undefined; const popupPosition = options ? options.popupPosition : undefined; if (value === undefined) { value = ''; } if (!cardinality) { cardinality = Cardinality.ONE_OR_NONE; } const required = cardinality === Cardinality.AT_LEAST_ONE || cardinality === Cardinality.ONE_AND_ONLY_ONE; return ( <Form.Field key={name} error={!!error} required={required}> <label>{label}</label> <DateInput name={name} placeholder={`Date (${MOMENT_DATE_FORMAT})`} value={value} iconPosition="left" closable={true} popupPosition={popupPosition} dateFormat={MOMENT_DATE_FORMAT} autoComplete={'off'} clearable={!required} onChange={this.handleDateInput(name)} /> {error && ( <Label basic={true} color="red" pointing={true}> {error} </Label> )} </Form.Field> ); } renderDateTimeField({ name, label, cardinality, type, options }: FormField, value: any) { const { errors } = this.props; const error = errors ? errors[name] : undefined; const popupPosition = options ? options.popupPosition : undefined; if (value === undefined) { value = ''; } if (!cardinality) { cardinality = Cardinality.ONE_OR_NONE; } const required = cardinality === Cardinality.AT_LEAST_ONE || cardinality === Cardinality.ONE_AND_ONLY_ONE; return ( <Form.Field key={name} error={!!error} required={required}> <label>{label}</label> <DateTimeInput name={name} placeholder={`Date/Time (${MOMENT_DATE_TIME_FORMAT})`} value={value} iconPosition="left" closable={true} popupPosition={popupPosition} dateFormat={MOMENT_DATE_FORMAT} dateTimeFormat={MOMENT_DATE_TIME_FORMAT} autoComplete={'off'} clearable={!required} onChange={this.handleDateInput(name)} /> {error && ( <Label basic={true} color="red" pointing={true}> {error} </Label> )} </Form.Field> ); } renderField(f: FormField) { let value = this.state[f.name]; if (value === undefined) { value = f.value; } switch (f.type) { case FormFieldType.STRING: return this.renderStringField(f, value); case FormFieldType.INT: case FormFieldType.DECIMAL: return this.renderNumberField(f, value); case FormFieldType.BOOLEAN: return this.renderBooleanField(f, value); case FormFieldType.FILE: return this.renderFileField(f); case FormFieldType.DATE: return this.renderDateField(f, value); case FormFieldType.DATE_TIME: return this.renderDateTimeField(f, value); default: return <p key={f.name}>Unknown field type: {f.type}</p>; } } render() { const { form, submitting, submitError, completed } = this.props; return ( <> <Header as="h2">{form.name}</Header> {submitError && <RequestErrorMessage error={submitError} />} <Form loading={submitting} onSubmit={(ev) => this.handleSubmit(ev)}> {form.fields.map((f) => this.renderField(f))} {completed ? ( <Button icon="check" primary={true} content="Return to the process page" onClick={(ev) => this.handleReturn(ev)} /> ) : ( <Button id="formSubmitButton" type="submit" primary={true} disabled={submitting} content="Submit" /> )} </Form> </> ); } } export default ProcessForm;
the_stack
import { BuildIndexQueryError } from '../exceptions/ottoman-errors'; import { ValidationError } from '../schema'; import { isNumber } from '../utils/type-helpers'; import { BaseQuery } from './base-query'; import { IndexParamsOnExceptions, IndexParamsUsingGSIExceptions, MultipleQueryTypesException } from './exceptions'; import { buildIndexExpr, selectBuilder } from './helpers'; import { IConditionExpr, IGroupBy, IIndexOnParams, IIndexWithParams, IndexType, ISelectType, LetExprType, LogicalWhereExpr, QueryBuildOptionsType, SortType, } from './interface/query.types'; import { getDefaultInstance } from '../ottoman/ottoman'; import { QueryOptions, QueryResult } from 'couchbase'; export class Query extends BaseQuery { /** * SELECT Expression. */ private selectExpr?: ISelectType[] | string; /** * WHERE Expression. */ private whereExpr?: LogicalWhereExpr; /** * ORDER BY Expression. */ private orderExpr?: Record<string, SortType>; /** * LIMIT Expression. */ private limitExpr?: number; /** * OFFSET Expression. */ private offSetExpr?: number; /** * LET Expression. */ private letExpr?: LetExprType; /** * GROUP BY Expression. */ private groupByExpr?: IGroupBy[]; /** * LETTING Expression. */ private lettingExpr?: LetExprType; /** * HAVING Expression. */ private havingExpr?: LogicalWhereExpr; /** * Plain JOIN Expression. */ private plainJoinExpr?: string; /** * USE Expression. */ private useKeysExpr?: string[]; /** * Available query types. */ private queryType?: 'SELECT' | 'INDEX'; /** * INDEX ON Expression. */ private indexOn?: IIndexOnParams[]; /** * Types of supported Index statements. */ private indexType?: IndexType; /** * Index name. */ private indexName?: string; /** * INDEX USING GSI Expression. */ private indexUsingGSI?: boolean; /** * INDEX WITH Expression. */ private indexWith?: IIndexWithParams; /** * @summary Create an instance of Query. * @name Query * @class * @public * * @param conditions List of SELECT clause conditions * @param collection Collection name * @returns Query * * @example * ```ts * const query = new Query({ * $select: [{ $field: 'address' }], * $where: { * $nill: [ * { address: { $like: '%57-59%' } }, * { free_breakfast: true }, * { free_lunch: [1] } * ] * } * }, * 'travel-sample'); * ``` */ constructor(conditions: IConditionExpr, collection: string) { super(conditions, collection); if (conditions) { this.compileFromConditions(conditions); } } /** * Add result selectors to SELECT clause. * @method * @public * * @example * ```ts * const query = new Query({}, 'travel-sample'); * const result = query.select([{ $field: 'address' }]).build() * console.log(result) * ``` * ```sql * SELECT address * FROM `travel-sample` * ``` */ select(value?: ISelectType[] | string | undefined): Query { if (this.queryType === undefined || this.queryType === 'SELECT') { this.queryType = 'SELECT'; if (!value) { this.selectExpr = '*'; } else if (typeof value === 'string') { this.selectExpr = value; } else if (typeof value === 'object') { this.selectExpr = [...(this.selectExpr || []), ...value] as ISelectType[]; } return this; } throw new MultipleQueryTypesException('SELECT', this.queryType); } /** * Add index type and name to INDEX clause. * @method * @public * * @example * ```ts * const result = new Query({}, 'travel-sample') * .index('DROP', 'travel_sample_id_test') * .build(); * console.log(result) * ``` * ```sql * DROP INDEX `travel-sample`.`travel_sample_id_test` * ``` */ index(type: IndexType, name: string): Query { if (this.queryType === undefined) { if (name.search(/^[A-Za-z][A-Za-z0-9#_]*$/g) === -1) { throw new ValidationError( 'Valid GSI index names can contain any of the following characters: A-Z a-z 0-9 # _, and must start with a letter, [A-Z a-z]', ); } this.queryType = 'INDEX'; this.indexType = type; this.indexName = name; return this; } throw new MultipleQueryTypesException('INDEX', this.queryType); } /** * Add items to ON clause in INDEX clause. * @method * @public * * @example * ```ts * const on = [{ name: 'travel-sample.callsing', sort: 'ASC' }]; * const result = new Query({}, 'travel-sample') * .index('CREATE', 'travel_sample_id_test') * .on(on) * .build(); * console.log(result) * ``` * ```sql * CREATE INDEX `travel_sample_id_test` ON `travel-sample` (`travel-sample.callsing`['ASC']) * ``` **/ on(value: IIndexOnParams[]): Query { if (this.queryType === 'INDEX' && ['CREATE', 'CREATE PRIMARY', 'BUILD'].includes(this.indexType || '')) { this.indexOn = value; return this; } throw new IndexParamsOnExceptions(['CREATE', 'CREATE PRIMARY', 'BUILD']); } /** * Create INDEX using General Secondary Index (GSI). * @method * @public * * @example * ```ts * const result = new Query({}, 'travel-sample') * .index('CREATE', 'travel_sample_id_test') * .usingGSI() * .build(); * console.log(result) * ``` * ```sql * CREATE INDEX `travel_sample_id_test` USING GSI * ``` **/ usingGSI(): Query { if (this.queryType === 'INDEX') { this.indexUsingGSI = true; return this; } throw new IndexParamsUsingGSIExceptions(['CREATE', 'CREATE PRIMARY', 'BUILD']); } /** * Add items to WITH clause in INDEX clause. * @method * @public * * @example * ```ts * const withExpr = { nodes: ['192.168.1.1:8078'], defer_build: true, num_replica: 2 }; * const result = new Query({}, 'travel-sample') * .index('CREATE', 'travel_sample_id_test') * .with(withExpr) * .build(); * console.log(result) * ``` * ```sql * CREATE INDEX `travel_sample_id_test` * WITH {'nodes': ['192.168.1.1:8078'],'defer_build': true,'num_replica': 2} * ``` **/ with(value: IIndexWithParams): Query { if (this.queryType === 'INDEX') { this.indexWith = value; return this; } throw new BuildIndexQueryError('The WITH clause is only available for Indexes'); } /** * Add WHERE expression to SELECT clause. * @method * @public * * @example * ```ts * const expr_where = { * $or: [ * { address: { $like: '%57-59%' } }, * { free_breakfast: true }, * { name: { $eq: 'John', $ignoreCase: true } } * ] * }; * const query = new Query({}, 'travel-sample'); * const result = query.select([{ $field: 'address' }]) * .where(expr_where) * .build() * console.log(result) * ``` * ```sql * SELECT address * FROM `travel-sample` * WHERE (address LIKE "%57-59%" OR free_breakfast = true OR (LOWER(name) = LOWER("John"))) * ``` **/ where(value: LogicalWhereExpr): Query { this.whereExpr = value; return this; } /** * Add JOIN expression to SELECT clause. * @method * @public * * @example * ```tS * const query = new Query({}, 'beer-sample brewery'); * const result = query.select([{ $field: 'address' }]) * .plainJoin( * 'JOIN `beer-sample` beer ON beer.brewery_id = LOWER(REPLACE(brewery.name, " ", "_"))' * ) * .build() * console.log(result) * ``` * ```sql * SELECT beer.name * FROM `beer-sample` brewery * JOIN `beer-sample` beer ON beer.brewery_id = LOWER(REPLACE(brewery.name, " ", "_")) * ``` */ plainJoin(value: string): Query { this.plainJoinExpr = value; return this; } /** * Add ORDER BY expression to SELECT clause. * @method * @public * * @example * ```ts * const query = new Query({}, 'travel-sample'); * const result = query.select([{ $field: 'address' }]) * .orderBy({ size: 'DESC' }) * .build() * console.log(result) * ``` * ```sql * SELECT address * FROM `travel-sample` * ORDER BY size = 'DESC' * ``` */ orderBy(value: Record<string, SortType>): Query { this.orderExpr = value; return this; } /** * Add LIMIT expression to SELECT clause. * @method * @public * * @example * ```ts * const query = new Query({}, 'travel-sample'); * const result = query.select([{ $field: 'address' }]) * .limit(10) * .build() * console.log(result) * ``` * ```sql * SELECT address * FROM `travel-sample` * LIMIT 10 * ``` **/ limit(value: number): Query { this.limitExpr = value; return this; } /** * Add OFFSET expression to SELECT clause. * @method * @public * * @example * ```ts * const query = new Query({}, 'travel-sample'); * const result = query.select([{ $field: 'address' }]) * .offset(10) * .build() * console.log(result) * ``` * ```sql * SELECT address * FROM `travel-sample` * OFFSET 10 * ``` **/ offset(value: number): Query { this.offSetExpr = value; return this; } /** * Add LET expression to SELECT clause. * @method * @public * * @example * * ```ts * // SELECT expression definition * const selectExpr = 't1.airportname, t1.geo.lat, t1.geo.lon, t1.city, t1.type'; * * // LET expression definition * const letExpr: LetExprType = { * min_lat: 71, * max_lat: 'ABS(t1.geo.lon)*4+1', * place: '(SELECT RAW t2.country FROM `travel-sample` t2 WHERE t2.type = "landmark")', * }; * * // WHERE expression definition * const whereExpr: LogicalWhereExpr = { * $and: [ * { 't1.type': 'airport' }, * { 't1.geo.lat': { $gt: { $field: 'min_lat' } } }, * { 't1.geo.lat': { $lt: { $field: 'max_lat' } } }, * { 't1.country': { $in: { $field: 'place' } } }, * ], * }; * * // QUERY creation * const query = new Query({}, 'travel-sample t1') * .select(selectExpr) * .let(letExpr) * .where(whereExpr) * .build(); * * console.log(query); * * // QUERY output * ``` * ```sql * SELECT t1.airportname, * t1.geo.lat, * t1.geo.lon, * t1.city, * t1.type * FROM `travel-sample` t1 * LET min_lat=71, * max_lat=ABS(t1.geo.lon)*4+1, * place=( * SELECT RAW t2.country * FROM `travel-sample` t2 * WHERE t2.type = "landmark") * WHERE (t1.type="airport" * AND t1.geo.lat>min_lat * AND t1.geo.lat<max_lat * AND t1.country IN place); * ``` * * ```ts * // OTTOMAN initialization * const ottoman = getDefaultInstance(); * await startInTest(ottoman); * * // QUERY execution * const { rows } = await ottoman.query(query); * * // RESULTS * console.log(rows) * ``` * ```sh * [ * { * airportname: 'Wiley Post Will Rogers Mem', * city: 'Barrow', * lat: 71.285446, * lon: -156.766003, * type: 'airport', * }, * { * airportname: 'Dillant Hopkins Airport', * city: 'Keene', * lat: 72.270833, * lon: 42.898333, * type: 'airport', * }, * ] * ``` */ let(value: LetExprType): Query { this.letExpr = value; return this; } /** * Add GROUP BY expression to SELECT clause. * @method * @public * * @example * ```ts * const groupByExpr = [{ expr: 'COUNT(amount_val)', as: 'amount' }]; * const query = new Query({}, 'travel-sample'); * const result = query.select([{ $field: 'address' }]) * .groupBy(groupByExpr) * .build() * console.log(result) * ``` * ```sql * SELECT address * FROM `travel-sample` * GROUP BY COUNT(amount) AS amount * ``` */ groupBy(value: IGroupBy[]): Query { this.groupByExpr = value; return this; } /** * Add LETTING expression to GROUP BY clause. * @method * @public * * @example * ```ts * const groupByExpr = [{ expr: 'COUNT(amount_val)', as: 'amount' }]; * const letExpr = { amount_val: 10 }; * const query = new Query({}, 'travel-sample'); * const result = query.select([{ $field: 'address' }]) * .groupBy(groupByExpr) * .let(letExpr) * .build() * console.log(result) * ``` * ```sql * SELECT address * FROM `travel-sample` * GROUP BY COUNT(amount) AS amount LETTING amount = 10 * ``` */ letting(value: LetExprType): Query { this.lettingExpr = value; return this; } /** * Add HAVING expression to GROUP BY clause. * @method * @public * * @example * ```ts * const groupByExpr = [{ expr: 'COUNT(amount_val)', as: 'amount' }]; * const having = { address: { $like: '%58%' } }; * const query = new Query({}, 'travel-sample'); * const result = query.select([{ $field: 'address' }]) * .groupBy(groupByExpr) * .having(having) * .build() * console.log(result) * ``` * ```sql * SELECT address * FROM `travel-sample` * GROUP BY COUNT(amount) AS amount * HAVING address LIKE '%58%' * ``` */ having(value: LogicalWhereExpr): Query { this.havingExpr = value; return this; } /** * Add USE KEYS expression to SELECT clause. * @method * @public * * @example * ```ts * const query = new Query({}, 'travel-sample'); * const result = query.select([{ $field: 'address' }]) * .useKeys(['airlineR_8093']) * .build() * console.log(result) * ``` * ```sql * SELECT address * FROM `travel-sample` USE KEYS ['airlineR_8093'] * ``` */ useKeys(value: string[]): Query { this.useKeysExpr = value; return this; } /** * Converts the conditional parameters passed to the constructor to the properties of the N1QL Query. * @method * @public * */ compileFromConditions(conditionals: IConditionExpr): void { Object.keys(conditionals).forEach((value: string) => { switch (value) { case 'select': this.select(conditionals[value]); break; case 'let': !!conditionals[value] && this.let(conditionals[value] as LetExprType); break; case 'where': !!conditionals[value] && this.where(conditionals[value] as LogicalWhereExpr); break; case 'plainJoin': !!conditionals[value] && this.plainJoin(conditionals[value] as string); break; case 'groupBy': !!conditionals[value] && this.groupBy(conditionals[value] as IGroupBy[]); break; case 'letting': !!conditionals[value] && this.letting(conditionals[value] as LetExprType); break; case 'having': !!conditionals[value] && this.having(conditionals[value] as LogicalWhereExpr); break; case 'orderBy': !!conditionals[value] && this.orderBy(conditionals[value] as Record<string, SortType>); break; case 'limit': { const limit = conditionals[value]; isNumber(limit) && this.limit(limit as number); break; } case 'offset': !!conditionals[value] && this.offset(conditionals[value] as number); break; case 'use': !!conditionals[value] && this.useKeys(conditionals[value] as string[]); break; } }); } /** * Build a N1QL query from the defined parameters. * * Can also use `ignoreCase` as part of the `build` method, this will always prioritize the `$ignoreCase` value defined in clause. * @example * ```ts * const expr_where = { * $or: [ * { address: { $like: '%57-59%', $ignoreCase: false } }, // ignoreCase will not be applied * { free_breakfast: true }, * { name: 'John' } // ignoreCase will be applied * ], * }; * const query = new Query({}, 'travel-sample'); * const result = query.select([{ $field: 'address' }]) * .where(expr_where) * .build({ ignoreCase: true }); // ignore case is enabled for where clause elements * console.log(result) * ``` * ```sql * SELECT address * FROM `travel-sample` * WHERE (address LIKE "%57-59%" OR free_breakfast = true OR `(LOWER(name) = LOWER("John"))`) * ``` * * @method * @public * */ build(options: QueryBuildOptionsType = { ignoreCase: false }): string { switch (this.queryType) { case 'INDEX': switch (this.indexType) { case 'BUILD': case 'CREATE': case 'CREATE PRIMARY': if (this.indexOn) { return buildIndexExpr( this.collection, this.indexType, this.indexName || '', this.indexOn, this.whereExpr, this.indexUsingGSI, this.indexWith, ); } case 'DROP': return buildIndexExpr( this.collection, this.indexType, this.indexName || '', undefined, undefined, this.indexUsingGSI, ); } case 'SELECT': if (this.selectExpr) { return selectBuilder( this.collection, this.selectExpr, this.letExpr, this.whereExpr, this.orderExpr, this.limitExpr, this.offSetExpr, this.useKeysExpr, this.groupByExpr, this.lettingExpr, this.havingExpr, this.plainJoinExpr, options.ignoreCase, ); } } return ''; } execute<Result = any>( options: QueryBuildOptionsType = { ignoreCase: false }, queryOptions: QueryOptions = {}, ottomanInstance = getDefaultInstance(), ): Promise<QueryResult<Result>> | Promise<Result> { return ottomanInstance.query(this.build(options), queryOptions); } get conditions(): IConditionExpr { return this._conditions; } set conditions(value: IConditionExpr) { this._conditions = value; } get collection(): string { return this._collection; } set collection(value: string) { this._collection = value; } }
the_stack
import { printError } from "./debug"; import { SvgNamespace, ComponentDescriptorFlags, ComponentFlags, VNodeFlags, matchesWithAncestors } from "./misc"; import { ElementDescriptor } from "./element_descriptor"; import { VNode, vNodeAttach, vNodeDetach, vNodeMount, vNodeRender, vNodeDispose, syncVNodes } from "./vnode"; import { InvalidatorSubscription, Invalidator } from "./invalidator"; import { clock, nextFrame, startUpdateComponentEachFrame, startMounting, finishMounting, isMounting } from "./scheduler"; /** * Component Descriptor registry is used in DEBUG mode for developer tools. * * All ComponentDescriptor instances that have a `name` property will be registered in this registry. * * NOTE: It will be automatically removed in RELEASE mode, so there is no overhead. */ export const ComponentDescriptorRegistry = ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") ? new Map<string, ComponentDescriptor<any, any>>() : undefined; /** * Component's root element. * * When back reference is enabled in Component Descriptor, element will have `kiviComponent` property with a reference * to Component instance. * * In DEBUG mode all elements have `kiviDebugComponent` reference to Component instance. */ export interface ComponentRootElement<P, S> extends Element { /** * Back reference from an Element to Component that is always present in DEBUG mode. */ kiviDebugComponent?: Component<P, S>; /** * Back reference from an Element to Component. There are two references so we can check in DEBUG mode if we are * missing this back reference in delegated event handlers. */ kiviComponent?: Component<P, S>; } /** * Delegated Event Controller. */ export class DelegatedEventController { private _stop: boolean; constructor() { this._stop = false; } stop(): void { this._stop = true; } isStopped(): boolean { return this._stop; } } /** * Component Descriptor. * * Each component should declare its properties and behavior in `ComponentDescriptor` object. * * Component descriptor has two parametric types: first parametric type `P` is a props type and second type `S` is a * state type. * * Component descriptor provides a `createComponent` and `createRootComponent` methods to create component instances. * * Example: * * class State { * xy: number; * * constructor(props: number) { * this.xy = props * props; * } * } * * const MyComponent = new ComponentDescriptor<number, State>() * .canvas() * .init((c) => { * c.state = new State(props); * }) * .update((c, props, state) => { * const ctx = c.get2DContext(); * ctx.fillStyle = 'rgba(0, 0, 0, 1)'; * ctx.fillRect(props, props, state.xy, state.xy); * }); * * const componentInstance = MyComponent.createRootComponent(10); * * NOTE: It may seem unnecessary to pass `props` and `state` to lifecycle methods, but it is implemented this way * to slightly improve "cold" rendering. This functions won't be optimized by JIT compiler until they have enough * information about types, so instead of performing two generic lookups on component objects, we are taking references * in "hot" functions and passing them as parameters. * * @final */ export class ComponentDescriptor<P, S> { /** * Flags marked on component when component is instantiated. See `ComponentFlags` for details. */ _markFlags: number; /** * Flags marked on component root vnode when vnode is instantiated. See `VNodeFlags` for details. */ _markRootFlags: number; /** * Flags, see `ComponentDescriptorFlags` for details. */ _flags: number; /** * Tag name of the root element or reference to an ElementDescriptor. */ _tag: string | ElementDescriptor<any>; /** * New props received handler overrides default props received behavior. If new props will cause a change in * component's representation, it should mark component as dirty with `markDirty` method. */ _newPropsReceived: ((component: Component<P, S>, oldProps: P, newProps: P) => void) | null; /** * Lifecycle handler update. * * Update will be invoked when component is created and when it gets invalidated. */ _update: ((component: Component<P, S>, props: P, state: S) => void) | null; /** * Lifecycle handler init. * * Initialize Component, if component has internal state, it should be created in this lifecycle method. Internal * event handlers should begistereed in this lifecycle method. */ _init: ((component: Component<P, S>, props: P) => void) | null; /** * Lifecycle handler attached is invoked when Component is attached to the document. * * All subscriptions should be created in this lifecycle method. */ _attached: ((component: Component<P, S>, props: P, state: S) => void) | null; /** * Lifecycle handler detached is invoked when Component is detached from the document. * * When component is detached, all invalidation subscriptions are automatically canceled. */ _detached: ((component: Component<P, S>, props: P, state: S) => void) | null; /** * Lifecycle handler disposed. * * Disposed method is invoked when component is completely destroyed and noone will access it anymore. */ _disposed: ((component: Component<P, S>, props: P, state: S) => void) | null; /** * Pool of recycled components. */ _recycledPool: Component<P, S>[] | null; /** * Maximum number of recycled components (recycled pool size). */ _maxRecycled: number; /** * Name that is used in DEBUG mode. * * NOTE: It will be automatically removed in RELEASE builds, so there is no overhead. */ name: string; constructor(name?: string) { this._markFlags = ComponentFlags.Dirty; this._markRootFlags = VNodeFlags.Root; this._flags = 0; this._tag = "div"; this._newPropsReceived = null; this._update = null; this._init = null; this._attached = null; this._detached = null; this._disposed = null; if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") { if (name === undefined) { this.name = "unnamed"; } else { this.name = name; if (ComponentDescriptorRegistry!.has(name)) { printError(`Component with name ${name} is already registered in ComponentDescriptorRegistry.`); } else { ComponentDescriptorRegistry!.set(name, this); } } } if ("<@KIVI_COMPONENT_RECYCLING@>" as string === "COMPONENT_RECYCLING_ENABLED") { this._recycledPool = null; this._maxRecycled = 0; } } /** * Set tag name or an Element Descriptor for a root element. * * const MyComponent = new ComponentDescriptor() * .tagName("table"); */ tagName(tagName: string | ElementDescriptor<any>): ComponentDescriptor<P, S> { this._tag = tagName; if (typeof tagName !== "string") { this._markFlags |= tagName._markFlags; this._markRootFlags |= tagName._markFlags; this._flags |= tagName._markFlags; } return this; } /** * Use SVG Namespace to create a root element. * * const MySvgComponent = new ComponentDescriptor() * .svg() * .tagName("circle"); */ svg(): ComponentDescriptor<P, S> { this._markFlags |= ComponentFlags.Svg; this._markRootFlags |= VNodeFlags.Svg; this._flags |= ComponentDescriptorFlags.Svg; return this; } /** * Turn component into a canvas object. * * Tag name of a root element will be automatically set to `canvas`. * * const MyCanvasComponent = new ComponentDescriptor() * .canvas() * .update((c) => { * const ctx = c.get2DContext(); * ctx.fillStyle = "red"; * ctx.fillRect(0, 0, 10, 10); * }); */ canvas(): ComponentDescriptor<P, S> { this._markFlags |= ComponentFlags.Canvas2D; this._flags |= ComponentDescriptorFlags.Canvas2D; this._tag = "canvas"; return this; } /** * Set init lifecycle handler. * * Initialize Component, if component has internal state, it should be created in this lifecycle method. Internal * event handlers should begistereed in this lifecycle method. * * `element` and `props` properties will be initialized before init handler is invoked. * * const MyComponent = new ComponentDescriptor() * .tagName("button") * .init((c) => { * c.element.addEventListener("click", (e) => { * e.preventDefault(); * e.stopPropagation(); * console.log("clicked"); * }); * }) * .update((c) => { * c.sync(c.createVRoot().children("click me")); * }); */ init(init: (component: Component<P, S>, props: P) => void): ComponentDescriptor<P, S> { this._init = init; return this; } /** * Set newPropsReceived handler. * * New props received handler overrides default props received behavior. If new props will cause a change in * component's representation, it should mark component as dirty with `markDirty` method. * * const MyComponent = new ComponentDescriptor<{a: number}, void>() * .newPropsReceived((c, oldProps, newProps) => { * if (oldProps.a !== newProps.a) { * c.markDirty(); * } * }) * .update((c, props) => { * c.sync(c.createVRoot().children(c.props.toString())); * }); */ newPropsReceived(newPropsReceived: (component: Component<P, S>, oldProps: P, newProps: P) => void): ComponentDescriptor<P, S> { this._newPropsReceived = newPropsReceived; return this; } /** * Set update lifecycle handler. * * Update will be invoked when component is created and when it gets invalidated. * * const MyComponent = new ComponentDescriptor<{a: number}, void>() * .update((c) => { * c.sync(c.createVRoot().children("content")); * }); */ update(update: (component: Component<P, S>, props: P, state: S) => void): ComponentDescriptor<P, S> { this._update = update; return this; } /** * Set attached lifecycle handler. * * Attached handler is invoked when Component is attached to the document. * * All subscriptions should be created in this lifecycle method. * * const onChange = new Invalidator(); * * const MyComponent = new ComponentDescriptor() * .attached((c) => { * c.subscribe(onChange); * }) * .update((c) => { * c.sync(c.createVRoot().children("content")); * }); */ attached(attached: (component: Component<P, S>, props: P, state: S) => void): ComponentDescriptor<P, S> { this._attached = attached; return this; } /** * Lifecycle detached lifecycle handler. * * Detached handler is invoked when Component is detached from the document. * * When component is detached, all invalidation subscriptions are automatically canceled. * * const MyComponent = new ComponentDescriptor<any, {onResize: (e: Event) => void}>() * .init((c) => { * c.state = {onResize: (e) => { console.log("window resized"); }}; * }) * .attached((c, props, state) => { * window.addEventListener("resize", state.onResize); * }) * .detached((c, props, state) => { * window.removeEventListener(state.onResize); * }) * .update((c) => { * c.sync(c.createVRoot().children("content")); * }); */ detached(detached: (component: Component<P, S>, props: P, state: S) => void): ComponentDescriptor<P, S> { this._detached = detached; return this; } /** * Set disposed lifecycle handler. * * Disposed handler is invoked when component is completely destroyed and noone will access it anymore. * * let allocatedComponents = 0; * * const MyComponent = new ComponentDescriptor() * .init((c) => { * allocatedComponents++; * }) * .disposed((c) => { * allocatedComponents--; * }) * .update((c) => { * c.sync(c.createVRoot().children("content")); * }); */ disposed(disposed: (component: Component<P, S>, props: P, state: S) => void): ComponentDescriptor<P, S> { this._disposed = disposed; return this; } /** * Enable back reference from root element to component instance. Back references are used to find component instances * in delegated event handlers. * * Back reference will be assigned to `kiviComponent` property. * * const MyComponent = new ComponentDescriptor() * .enableBackRef() * .init((c) => { * c.element.addEventListener("click", (e) => { * console.log(getBackRef<Component>(e.target) === c); * }); * }) * .update((c) => { * c.sync(c.createVRoot().children("content")); * }); */ enableBackRef(): ComponentDescriptor<P, S> { this._flags |= ComponentDescriptorFlags.EnabledBackRef; return this; } /** * Enable component recycling. * * When component recycling is enabled, components will be instantiated from recycled pool. * * Component recycling is disabled by default and should be enabled by replacing all `<@KIVI_COMPONENT_RECYCLING@>` * with `COMPONENT_RECYCLING_ENABLED` strings. * * const MyComponent = new ComponentDescriptor() * .enableRecycling(100) * .update((c) => { * c.sync(c.createVRoot().children("content")); * }); */ enableRecycling(maxRecycled: number): ComponentDescriptor<P, S> { if ("<@KIVI_COMPONENT_RECYCLING@>" as string === "COMPONENT_RECYCLING_ENABLED") { this._markFlags |= ComponentFlags.EnabledRecycling; this._flags |= ComponentDescriptorFlags.EnabledRecycling; this._recycledPool = []; this._maxRecycled = maxRecycled; } return this; } /** * Component has immutable props. * * When Component has accepts only immutable props, it will always check them for identity before marking component * as dirty. */ immutableProps(): ComponentDescriptor<P, S> { this._markFlags |= ComponentFlags.ImmutableProps; return this; } /** * Create a Virtual DOM node representing component. * * const MyComponent = new ComponentDescriptor<number, void>() * .update((c, props) => { * c.sync(c.createVRoot().children(props.toString())); * }); * * const vnode = MyComponent.createVNode(10); */ createVNode(props?: P): VNode { if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") { if ((this._markFlags & ComponentFlags.ImmutableProps) !== 0) { throw new Error("Failed to create VNode: VNodes for components with immutable props should be created with " + "createImmutableVNode method."); } } return new VNode(VNodeFlags.Component, this, props === undefined ? null : props); } /** * Create a Virtual DOM node with immutable props representing component. * * Immutable props will be checked for identity before triggering an update, if props identity is the same, then * component won't be marked as dirty. * * const MyComponent = new ComponentDescriptor<number, void>() * .update((c, props) => { * c.sync(c.createVRoot().children(props.toString())); * }); * * const vnode = MyComponent.createImmutableVNode(10); */ createImmutableVNode(props?: P): VNode { return new VNode(VNodeFlags.Component | VNodeFlags.ImmutableProps, this, props === undefined ? null : props); } /** * Creates a root component instance that doesn't have any parents. * * const MyComponent = new ComponentDescriptor<number, void>() * .update((c, props) => { * c.sync(c.createVRoot().children(props.toString())); * }); * * const component = MyComponent.createRootComponent(10); */ createRootComponent(props?: P): Component<P, S> { return this.createComponent(undefined, props); } /** * Create a component. * * const ChildComponent = new ComponentDescriptor() * .update((c) => { * c.sync(c.createVRoot().children("child")); * }); * * const ParentComponent = new ComponentDescriptor() * .init((c) => { * const child = ChildComponent.createComponent(c); * c.element.appendChild(child.element); * child.attached(); * child.update(); * }); * * const rootComponent = MyComponent.createRootComponent(); */ createComponent(parent: Component<any, any> | undefined, props?: P): Component<P, S> { let element: Element; let component: Component<P, S>; if ("<@KIVI_COMPONENT_RECYCLING@>" as string !== "COMPONENT_RECYCLING_ENABLED" || ((this._flags & ComponentDescriptorFlags.EnabledRecycling) === 0) || (this._recycledPool!.length === 0)) { if ((this._flags & ComponentDescriptorFlags.ElementDescriptor) === 0) { element = ((this._flags & ComponentDescriptorFlags.Svg) === 0) ? document.createElement(this._tag as string) : document.createElementNS(SvgNamespace, this._tag as string); } else { element = (this._tag as ElementDescriptor<any>).createElement(); } component = new Component<P, S>(this._markFlags, this, element, parent, props); if ((this._flags & ComponentDescriptorFlags.EnabledBackRef) !== 0) { (element as ComponentRootElement<P, S>).kiviComponent = component; } if (this._init !== null) { this._init(component, component.props!); } } else { component = this._recycledPool!.pop() !; component.depth = parent === undefined ? 0 : parent.depth + 1; } return component; } /** * Mount component on top of existing html element. * * const element = document.createElement("div"); * document.body.appendChild(element); * element.innerHTML("<span>content</span>"); * * const MyComponent = new ComponentDescriptor() * .update((c) => { * c.sync(c.createVRoot.children([createVElement("span").children("content")])); * }); * * const component = MyComponent.mountComponent(element); * component.update(); */ mountComponent(element: Element, parent?: Component<any, any>, props?: P): Component<P, S> { const component = new Component<P, S>(this._markFlags, this, element, parent, props); if (this._init !== null) { this._init(component, component.props!); } componentAttached(component); return component; } /** * Create event handler. */ createEventHandler<E extends Event>(handler: (event: E, component: Component<P, S>, props: P, state: S) => void): (event: E) => void { this._flags |= ComponentDescriptorFlags.EnabledBackRef; return function (event) { const component = (event.currentTarget as ComponentRootElement<P, S>).kiviComponent; if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") { if (component === undefined) { throw new Error(`Failed to dispatch event to event handler: cannot find reference to component on a DOM` + `element.`); } } handler(event, component!, component!.props!, component!.state!); }; } /** * Create delegated event handler. * * `selector` selector that should match an event `target` with its ancestors. * `componentSelector` selector that should match component instance. If it is `false`, then it will look for * component instance in an event `currentTarget`. */ createDelegatedEventHandler<E extends Event>(selector: string, componentSelector: string | boolean, handler: (event: E, component: Component<P, S>, props: P, state: S, matchingTarget: Element, controller?: DelegatedEventController) => void): (event: E, controller?: DelegatedEventController) => void { this._flags |= ComponentDescriptorFlags.EnabledBackRef; return function (event, controller) { if (controller === undefined || !controller.isStopped()) { let matchingTarget = matchesWithAncestors(event.target as Element, selector, event.currentTarget as Element); if (matchingTarget !== null) { let target: Element | null = matchingTarget; if (typeof componentSelector === "boolean") { if (!componentSelector) { target = event.currentTarget as Element; } } else { target = matchesWithAncestors(matchingTarget, componentSelector, event.currentTarget as Element); } const component = (target as ComponentRootElement<P, S>).kiviComponent; if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") { if (component === undefined) { throw new Error(`Failed to dispatch event to event handler: cannot find reference to component on a DOM` + `element.`); } } handler(event, component!, component!.props!, component!.state!, matchingTarget, controller); } } }; } } /** * Component. * * @final */ export class Component<P, S> { /** * Flags, see `ComponentFlags` for details. * * Lowest 24 bits are reserved for kivi flags, other bits can be used for user flags. */ flags: number; /** * Timestamp when component were updated last time, using scheduler monotonically increasing clock. */ mtime: number; /** * Component descriptor. */ readonly descriptor: ComponentDescriptor<P, S>; /** * Reference to the root element. */ readonly element: ComponentRootElement<P, S>; /** * Depth in the components tree. * * Depth property is used by scheduler to determine its priority when updating components. */ depth: number; /** * Component's props. */ props: P | null; /** * Component's state. */ state: S | null; /** * Root node can contain a virtual dom root if Component represents a DOM subtree, or Canvas context if Component is * a Canvas object. */ _root: VNode | CanvasRenderingContext2D | null; _subscriptions: InvalidatorSubscription | null; _transientSubscriptions: InvalidatorSubscription | null; constructor(flags: number, descriptor: ComponentDescriptor<P, S>, element: Element, parent?: Component<any, any>, props?: P) { this.flags = flags; this.mtime = 0; this.descriptor = descriptor; this.element = element as ComponentRootElement<P, S>; this.depth = parent === undefined ? 0 : parent.depth + 1; this.props = props === undefined ? null : props; this.state = null; this._root = ((flags & ComponentFlags.Canvas2D) === 0) ? null : (element as HTMLCanvasElement).getContext("2d"); this._subscriptions = null; this._transientSubscriptions = null; if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") { this.element.kiviDebugComponent = this; } } /** * Get canvas 2d rendering context. */ get2DContext(): CanvasRenderingContext2D { if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") { if ((this.flags & ComponentFlags.Canvas2D) === 0) { throw new Error("Failed to get 2d context: component isn't a canvas."); } } return this._root as CanvasRenderingContext2D; } /** * Mark component as dirty and cancel all transient subscriptions. */ markDirty(): void { if ((this.flags & ComponentFlags.Dirty) === 0) { this.flags |= ComponentFlags.Dirty; componentCancelTransientSubscriptions(this); } } /** * Creates a virtual dom root node. */ createVRoot(): VNode { return new VNode(this.descriptor._markRootFlags, this.descriptor._tag, null); } /** * Adds component to a scheduler queue that will update component each animation frame. * * Component will be updated always, even when scheduler is in throttled mode. */ startUpdateEachFrame(): void { this.flags |= ComponentFlags.UpdateEachFrame; if ((this.flags & ComponentFlags.InUpdateEachFrameQueue) === 0) { this.flags |= ComponentFlags.InUpdateEachFrameQueue; startUpdateComponentEachFrame(this); } } /** * Remove component from a scheduler queue that updates component each animation frame. */ stopUpdateEachFrame(): void { this.flags &= ~ComponentFlags.UpdateEachFrame; } /** * Set new props and update component. * * Props are checked by their identity, unless it is disabled by component descriptor method * `disableCheckDataIdentity()`. */ update(newProps?: P): void { updateComponent(this, newProps); } /** * Sync internal representation using Virtual DOM API. * * If this method is called during mounting phase, then Virtual DOM will be mounted on top of the existing document * tree. * * When virtual dom is passed to sync method, its ownership is transfered. Mutating and reading from virtual dom * after it is passed to sync is an undefined behavior. */ sync(newRoot: VNode): void { if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") { if ((newRoot._flags & VNodeFlags.Root) === 0) { throw new Error("Failed to sync: sync methods accepts only VNodes representing root node."); } if ((this.flags & ComponentFlags.ElementDescriptor) !== (newRoot._flags & VNodeFlags.ElementDescriptor)) { if ((this.flags & ComponentFlags.ElementDescriptor) === 0) { throw new Error("Failed to sync: vdom root should have the same type as root registered in component " + "descriptor, component descriptor is using ElementDescriptor."); } else { throw new Error("Failed to sync: vdom root should have the same type as root registered in component " + "descriptor, component descriptor is using a simple element."); } } } if (this._root === null) { newRoot.cref = this; if ("<@KIVI_MOUNTING@>" as string === "MOUNTING_ENABLED" && isMounting()) { vNodeMount(newRoot, this.element, this); } else { newRoot.ref = this.element; vNodeRender(newRoot, this); } } else { syncVNodes(this._root as VNode, newRoot, this); } this._root = newRoot; } /** * Invalidate component and schedule component to update on the next frame. * * Dirty flags parameter can be used to add hints that describe what has been changed. * This method will automatically cancel all transient subscriptions if preserve transient subscriptions is false. */ invalidate(dirtyFlags: number = ComponentFlags.DirtyView, preserveTransientSubscriptions = false): void { this.flags |= dirtyFlags; if ((this.flags & (ComponentFlags.Dirty | ComponentFlags.Disposed)) === 0) { this.flags |= ComponentFlags.Dirty; if (!preserveTransientSubscriptions) { componentCancelTransientSubscriptions(this); } nextFrame().updateComponent(this); } } /** * Attach method should be invoked when component is attached to the document. */ attach(): void { componentAttached(this); if (this._root !== null && ((this.flags & ComponentFlags.Canvas2D) === 0)) { vNodeAttach(this._root as VNode); } } /** * Detach method should be invoked when component is detached from the document. */ detach(): void { if (this._root !== null && ((this.flags & ComponentFlags.Canvas2D) === 0)) { vNodeDetach(this._root as VNode); } componentDetached(this); } /** * Dispose method should be invoked when component is destroyed. */ dispose(): void { if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") { if ((this.flags & ComponentFlags.Disposed) !== 0) { throw new Error("Failed to dispose Component: component is already disposed."); } } if ("<@KIVI_COMPONENT_RECYCLING@>" as string !== "COMPONENT_RECYCLING_ENABLED" || ((this.flags & ComponentFlags.EnabledRecycling) === 0) || (this.descriptor._recycledPool!.length >= this.descriptor._maxRecycled)) { this.flags |= ComponentFlags.Disposed; if (this._root !== null && ((this.flags & ComponentFlags.Canvas2D) === 0)) { vNodeDispose(this._root as VNode); } if ((this.flags & ComponentFlags.Attached) !== 0) { componentDetached(this); } const disposed = this.descriptor._disposed; if (disposed !== null) { disposed(this, this.props!, this.state!); } } else { this.detach(); this.descriptor._recycledPool!.push(this); } } /** * Subscribe to invalidator object. */ subscribe(invalidator: Invalidator): InvalidatorSubscription { return invalidator.subscribeComponent(this); } /** * Transiently subscribe to invalidator object. * * Each time component is invalidated, all transient subscriptions will be canceled. */ transientSubscribe(invalidator: Invalidator): InvalidatorSubscription { return invalidator.transientSubscribeComponent(this); } } export function updateComponent(component: Component<any, any>, newProps?: any): void { if (newProps !== undefined && (component.flags & ComponentFlags.ImmutableProps) === 0) { const oldProps = component.props; const newPropsReceived = component.descriptor._newPropsReceived; if (newPropsReceived !== null) { newPropsReceived(component, oldProps, newProps); } else { component.markDirty(); } component.props = newProps; } if ((component.flags & (ComponentFlags.Dirty | ComponentFlags.Attached)) === (ComponentFlags.Dirty | ComponentFlags.Attached)) { component.descriptor._update!(component, component.props, component.state); component.mtime = clock(); component.flags &= ~(ComponentFlags.Dirty | ComponentFlags.InUpdateQueue); } } function componentAttached(component: Component<any, any>): void { if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") { if ((component.flags & ComponentFlags.Attached) !== 0) { throw new Error("Failed to attach Component: component is already attached."); } } component.flags |= ComponentFlags.Attached; if ("<@KIVI_COMPONENT_RECYCLING@>" as string === "COMPONENT_RECYCLING_ENABLED") { component.flags &= ~ComponentFlags.Recycled; } const attached = component.descriptor._attached; if (attached !== null) { attached(component, component.props, component.state); } } function componentDetached(component: Component<any, any>): void { if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") { if ((component.flags & ComponentFlags.Attached) === 0) { throw new Error("Failed to detach Component: component is already detached."); } } component.flags &= ~(ComponentFlags.Attached | ComponentFlags.UpdateEachFrame); componentCancelSubscriptions(component); componentCancelTransientSubscriptions(component); const detached = component.descriptor._detached; if (detached !== null) { detached(component, component.props, component.state); } } /** * Cancel subscriptions. */ function componentCancelSubscriptions(component: Component<any, any>): void { let subscription = component._subscriptions; while (subscription !== null) { subscription._cancel(); subscription = subscription._componentNext; } component._subscriptions = null; } /** * Cancel transient subscriptions. */ function componentCancelTransientSubscriptions(component: Component<any, any>): void { let subscription = component._transientSubscriptions; while (subscription !== null) { subscription._cancel(); subscription = subscription._componentNext; } component._transientSubscriptions = null; } /** * Inject component into DOM. */ export function injectComponent<P, S>(descriptor: ComponentDescriptor<P, S>, container: Element, props?: P, sync?: boolean): Component<P, S> { const c = descriptor.createComponent(undefined, props); if (sync) { container.appendChild(c.element as Node); componentAttached(c); updateComponent(c); } else { nextFrame().write(function () { container.appendChild(c.element as Node); componentAttached(c); updateComponent(c); }); } return c; } /** * Mount component on top of existing DOM. */ export function mountComponent<P, S>(descriptor: ComponentDescriptor<P, S>, element: Element, props?: P, sync?: boolean): Component<P, S> { const c = descriptor.mountComponent(element, undefined, props); if (sync) { startMounting(); componentAttached(c); updateComponent(c); finishMounting(); } else { nextFrame().write(function () { startMounting(); componentAttached(c); updateComponent(c); finishMounting(); }); } return c; }
the_stack
import type { Language } from "./Language"; import { Entity, IEntitySettings, IEntityPrivate } from "./Entity" import { TextFormatter } from "./TextFormatter"; import * as $object from "./Object"; import * as $utils from "./Utils"; import * as $type from "./Type"; /** * @ignore */ export interface INumberSuffix { number: number; suffix: string; } export interface INumberFormatterSettings extends IEntitySettings { /** * Number format to be used when formatting numbers. * * @default "#,###.#####" */ numberFormat?: string | Intl.NumberFormatOptions; /** * A threshold value for negative numbers. * * @default 0 */ negativeBase?: number; /** * Prefixes and thresholds to group big numbers into, e.g. 1M. * * Used in conjunction with `a` modifier of the number format. */ bigNumberPrefixes?: INumberSuffix[]; /** * Prefixes and thresholds to group small numbers into, e.g. 1m. * * Used in conjunction with `a` modifier of the number format. */ smallNumberPrefixes?: INumberSuffix[]; /** * All numbers below this value are considered small. * * @default 1 */ smallNumberThreshold?: number; /** * Prefixes to and thresholds to use when grouping data size numbers, e.g. 1MB. * * Used in conjunction with `b` modifier of the number format. */ bytePrefixes?: INumberSuffix[]; /** * Indicates which fields in data should be considered numeric. * * It is used when formatting data placeholder values. */ numericFields?: string[]; /** * Locales if you are using date formats in `Intl.NumberFormatOptions` syntax. * * @see (@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat) about using Intl for number formatting * @param value Locales */ intlLocales?: string; } export interface INumberFormatterPrivate extends IEntityPrivate { } /** * Number formatter * * @see {@link https://www.amcharts.com/docs/v5/concepts/formatters/formatting-numbers/} for more info * @important */ export class NumberFormatter extends Entity { declare public _settings: INumberFormatterSettings; declare public _privateSettings: INumberFormatterPrivate; protected _setDefaults() { // Defaults this._setDefault("negativeBase", 0); this._setDefault("numberFormat", "#,###.#####"); this._setDefault("smallNumberThreshold", 1.00); const bns = "_big_number_suffix_"; const sns = "_small_number_suffix_"; const bs = "_byte_suffix_"; this._setDefault("bigNumberPrefixes", [ { "number": 1e+3, "suffix": this._t(bns + "3") }, { "number": 1e+6, "suffix": this._t(bns + "6") }, { "number": 1e+9, "suffix": this._t(bns + "9") }, { "number": 1e+12, "suffix": this._t(bns + "12") }, { "number": 1e+15, "suffix": this._t(bns + "15") }, { "number": 1e+18, "suffix": this._t(bns + "18") }, { "number": 1e+21, "suffix": this._t(bns + "21") }, { "number": 1e+24, "suffix": this._t(bns + "24") } ]); this._setDefault("smallNumberPrefixes", [ { "number": 1e-24, "suffix": this._t(sns + "24") }, { "number": 1e-21, "suffix": this._t(sns + "21") }, { "number": 1e-18, "suffix": this._t(sns + "18") }, { "number": 1e-15, "suffix": this._t(sns + "15") }, { "number": 1e-12, "suffix": this._t(sns + "12") }, { "number": 1e-9, "suffix": this._t(sns + "9") }, { "number": 1e-6, "suffix": this._t(sns + "6") }, { "number": 1e-3, "suffix": this._t(sns + "3") } ]); this._setDefault("bytePrefixes", [ { "number": 1, suffix: this._t(bs + "B") }, { "number": 1024, suffix: this._t(bs + "KB") }, { "number": 1048576, suffix: this._t(bs + "MB") }, { "number": 1073741824, suffix: this._t(bs + "GB") }, { "number": 1099511627776, suffix: this._t(bs + "TB") }, { "number": 1125899906842624, suffix: this._t(bs + "PB") } ]); super._setDefaults(); } public _beforeChanged() { super._beforeChanged(); } /** * Formats the number according to specific format. * * @param value Value to format * @param format Format to apply * @return Formatted number */ public format(value: number | string, format?: string | Intl.NumberFormatOptions, precision?: number): string { // no format passed in or "Number" if (format == null || ($type.isString(format) && format.toLowerCase() === "number")) { format = this.get("numberFormat", ""); } // Init return value let formatted; // Cast to number just in case // TODO: maybe use better casting let source: number = Number(value); // Is it a built-in format or Intl.NumberFormatOptions if ($type.isObject(format)) { try { if (this.get("intlLocales")) { return new Intl.NumberFormat(this.get("intlLocales"), <Intl.NumberFormatOptions>format).format(source); } else { return new Intl.NumberFormat(undefined, <Intl.NumberFormatOptions>format).format(source); } } catch (e) { return "Invalid"; } } else { // Clean format format = $utils.cleanFormat(format!); // Get format info (it will also deal with parser caching) let info = this.parseFormat(format, this._root.language); // format and replace the number let details; if (source > this.get("negativeBase")) { details = info.positive; } else if (source < this.get("negativeBase")) { details = info.negative; } else { details = info.zero; } // Adjust precision if (precision != null && !details.mod) { details = $object.copy(details); details.decimals.active = source == 0 ? 0 : precision; } // Format formatted = details.template.split($type.PLACEHOLDER).join(this.applyFormat(source, details)); } return formatted; } /** * Parses supplied format into structured object which can be used to format * the number. * * @param format Format string, i.e. "#,###.00" * @param language Language * @ignore */ protected parseFormat(format: string, language: Language): any { // Check cache // TODO // let cached = this.getCache(format); // if (cached != null) { // return cached; // } const thousandSeparator = language.translateEmpty("_thousandSeparator"); const decimalSeparator = language.translateEmpty("_decimalSeparator") // init format parse info holder let info: any = { "positive": { "thousands": { "active": -1, "passive": -1, "interval": -1, "separator": thousandSeparator }, "decimals": { "active": -1, "passive": -1, "separator": decimalSeparator }, "template": "", "source": "", "parsed": false }, "negative": { "thousands": { "active": -1, "passive": -1, "interval": -1, "separator": thousandSeparator }, "decimals": { "active": -1, "passive": -1, "separator": decimalSeparator }, "template": "", "source": "", "parsed": false }, "zero": { "thousands": { "active": -1, "passive": -1, "interval": -1, "separator": thousandSeparator }, "decimals": { "active": -1, "passive": -1, "separator": decimalSeparator }, "template": "", "source": "", "parsed": false } }; // Escape double vertical bars (that mean display one vertical bar) format = format.replace("||", $type.PLACEHOLDER2); // Split it up and deal with different formats let parts = format.split("|"); info.positive.source = parts[0]; if (typeof parts[2] === "undefined") { info.zero = info.positive; } else { info.zero.source = parts[2]; } if (typeof parts[1] === "undefined") { info.negative = info.positive; } else { info.negative.source = parts[1]; } // Parse each $object.each(info, (_part, item) => { // Already parsed if (item.parsed) { return; } // Check cached // TODO // if (typeof this.getCache(item.source) !== "undefined") { // info[part] = this.getCache(item.source); // return; // } // Begin parsing let partFormat = item.source; // Just "Number"? if (partFormat.toLowerCase() === "number") { partFormat = this.get("numberFormat", "#,###.#####"); } // Let TextFormatter split into chunks let chunks = TextFormatter.chunk(partFormat, true); for (let i: number = 0; i < chunks.length; i++) { let chunk = chunks[i]; // replace back double vertical bar chunk.text = chunk.text.replace($type.PLACEHOLDER2, "|"); if (chunk.type === "value") { // Parse format // Look for codes let matches: string[] | null = chunk.text.match(/[#0.,]+[ ]?[abesABES%!]?[abesABES‰!]?/); if (matches) { if (matches === null || matches[0] === "") { // no codes here - assume string // nothing to do here item.template += chunk.text; } else { // look for the format modifiers at the end let mods: string[] | null = matches[0].match(/[abesABES%‰!]{2}|[abesABES%‰]{1}$/); if (mods) { item.mod = mods[0].toLowerCase(); item.modSpacing = matches[0].match(/[ ]{1}[abesABES%‰!]{1}$/) ? true : false; } // break the format up let a = matches[0].split("."); // Deal with thousands if (a[0] === "") { // No directives for thousands // Leave default settings (no formatting) } else { // Counts item.thousands.active = (a[0].match(/0/g) || []).length; item.thousands.passive = (a[0].match(/\#/g) || []).length + item.thousands.active; // Separator interval let b = a[0].split(","); if (b.length === 1) { // No thousands separators // Do nothing } else { // Use length fo the last chunk as thousands length item.thousands.interval = (b.pop() || "").length; if (item.thousands.interval === 0) { item.thousands.interval = -1; } } } // Deal with decimals if (typeof (a[1]) === "undefined") { // No directives for decimals // Leave at defaults (no formatting) } else { // Counts item.decimals.active = (a[1].match(/0/g) || []).length; item.decimals.passive = (a[1].match(/\#/g) || []).length + item.decimals.active; } // Add special code to template item.template += chunk.text.split(matches[0]).join($type.PLACEHOLDER); } } } else { // Quoted string - take it as it is item.template += chunk.text; } } // Apply style formatting //item.template = getTextFormatter().format(item.template, this.outputFormat); // Save cache // TODO //this.setCache(item.source, item); // Mark this as parsed item.parsed = true; }); // Save cache (the whole thing) // TODO //this.setCache(format, info); return info; } /** * Applies parsed format to a numeric value. * * @param value Value * @param details Parsed format as returned by parseFormat() * @return Formatted number * @ignore */ protected applyFormat(value: number, details: any): string { // Use absolute values let negative: boolean = value < 0; value = Math.abs(value); // Recalculate according to modifier let prefix: string = "", suffix: string = ""; let mods: string[] = details.mod ? details.mod.split("") : []; if (mods.indexOf("b") !== -1) { let a = this.applyPrefix(value, this.get("bytePrefixes")!, mods.indexOf("!") !== -1); value = a[0]; prefix = a[1]; suffix = a[2]; if (details.modSpacing) { suffix = " " + suffix; } } else if (mods.indexOf("a") !== -1) { let a = this.applyPrefix(value, value < this.get("smallNumberThreshold")! ? this.get("smallNumberPrefixes")! : this.get("bigNumberPrefixes")!, mods.indexOf("!") !== -1); value = a[0]; prefix = a[1]; suffix = a[2]; if (details.modSpacing) { suffix = " " + suffix; } } else if (mods.indexOf("%") !== -1) { let ol = Math.min(value.toString().length + 2, 21); value *= 100; value = parseFloat(value.toPrecision(ol)); suffix = "%"; } else if (mods.indexOf("‰") !== -1) { let ol = Math.min(value.toString().length + 3, 21); value *= 1000; value = parseFloat(value.toPrecision(ol)); suffix = "‰"; } // Round to passive if (mods.indexOf("e") !== -1) { // convert the value to exponential let exp: string[]; if (details.decimals.passive >= 0) { exp = value.toExponential(details.decimals.passive).split("e"); } else { exp = value.toExponential().split("e"); } value = Number(exp[0]); suffix = "e" + exp[1]; if (details.modSpacing) { suffix = " " + suffix; } } else if (details.decimals.passive === 0) { value = Math.round(value); } else if (details.decimals.passive > 0) { let d: number = Math.pow(10, details.decimals.passive); value = Math.round(value * d) / d; } // Init return value let res: string = ""; // Calc integer and decimal parts let a = $type.numberToString(value).split("."); // Format integers let ints = a[0]; // Pad integers to active length if (ints.length < details.thousands.active) { ints = Array(details.thousands.active - ints.length + 1).join("0") + ints; } // Insert thousands separators if (details.thousands.interval > 0) { let ip: string[] = []; let intsr: string = ints.split("").reverse().join(""); for (let i = 0, len = ints.length; i <= len; i += details.thousands.interval) { let c: string = intsr.substr(i, details.thousands.interval).split("").reverse().join(""); if (c !== "") { ip.unshift(c); } } ints = ip.join(details.thousands.separator); } // Add integers res += ints; // Add decimals if (a.length === 1) { a.push(""); } let decs: string = a[1]; // Fill zeros? if (decs.length < details.decimals.active) { decs += Array(details.decimals.active - decs.length + 1).join("0"); } if (decs !== "") { res += details.decimals.separator + decs; } // Can't have empty return value if (res === "") { res = "0"; } // Add minus sign back if (value !== 0 && negative && (mods.indexOf("s") === -1)) { res = "-" + res; } // Add suffixes/prefixes if (prefix) { res = prefix + res; } if (suffix) { res += suffix; } return res; } protected applyPrefix(value: number, prefixes: any[], force: boolean = false): any[] { let newvalue = value; let prefix = ""; let suffix = ""; let applied = false; let k = 1; for (let i = 0, len = prefixes.length; i < len; i++) { if (prefixes[i].number <= value) { if (prefixes[i].number === 0) { newvalue = 0; } else { newvalue = value / prefixes[i].number; k = prefixes[i].number; } prefix = prefixes[i].prefix; suffix = prefixes[i].suffix; applied = true; } } if (!applied && force && prefixes.length && value != 0) { // Prefix was not applied. Use the first prefix. newvalue = value / prefixes[0].number; prefix = prefixes[0].prefix; suffix = prefixes[0].suffix; applied = true; } if (applied) { newvalue = parseFloat( newvalue.toPrecision( Math.min(k.toString().length + Math.floor(newvalue).toString().replace(/[^0-9]*/g, "").length, 21) ) ); } return [newvalue, prefix, suffix]; } /** * Replaces brackets with temporary placeholders. * * @ignore Exclude from docs * @param text Input text * @return Escaped text */ public escape(text: string): string { return text.replace("||", $type.PLACEHOLDER2); } /** * Replaces placeholders back to brackets. * * @ignore Exclude from docs * @param text Escaped text * @return Unescaped text */ public unescape(text: string): string { return text.replace($type.PLACEHOLDER2, "|"); } }
the_stack
import { expect, use } from 'chai'; import { useFakeTimers, stub, spy } from 'sinon'; import * as sinonChai from 'sinon-chai'; import * as _ from 'lodash'; import * as moment from 'moment'; import { Op } from 'sequelize'; import * as chaiAsPromised from 'chai-as-promised'; import { createSequelize } from '../utils/sequelize'; import { Model, Table, Column, PrimaryKey, ForeignKey, HasMany, BelongsTo, DataType, Default, AutoIncrement, CreatedAt, DeletedAt, UpdatedAt, BelongsToMany, } from '../../src'; import chaiDatetime = require('chai-datetime'); import { TableOptions } from '../../src/model/table/table-options'; use(sinonChai); use(chaiAsPromised); use(chaiDatetime); let clock; describe('model', () => { let sequelize; @Table class MainUser extends Model { @Column username: string; @Column secretValue: string; @Column data: string; @Column intVal: number; @Column theDate: Date; @Column aBool: boolean; } before(() => { clock = useFakeTimers(); }); after(() => { clock.restore(); }); beforeEach(() => { sequelize = createSequelize(); sequelize.addModels([MainUser]); return MainUser.sync({ force: true }); }); describe('instantiation when not initialized', () => { it('should throw an error', () => { @Table class Test extends Model {} expect(() => new Test()).to.throw(/^Model not initialized/); }); }); describe('static functions when not initialized', () => { it('should throw an error', () => { @Table class Test extends Model {} expect(() => Test.beforeCreate(() => { // beforeCreate }) ).to.throw(/^Model not initialized/); }); }); describe('constructor', () => { it('uses the passed dao name as tablename if freezeTableName', () => { @Table({ freezeTableName: true, tableName: 'FrozenUser' }) class User extends Model {} sequelize.addModels([User]); expect(User['tableName']).to.equal('FrozenUser'); }); it('uses the pluralized dao name as tablename unless freezeTableName', () => { @Table({ freezeTableName: false, tableName: 'SuperUser' }) class User extends Model {} sequelize.addModels([User]); expect(User['tableName']).to.equal('SuperUser'); }); it('uses checks to make sure dao factory isnt leaking on multiple define', () => { (() => { @Table({ freezeTableName: false, tableName: 'SuperUser' }) class User extends Model {} sequelize.addModels([User]); })(); const factorySize = sequelize['modelManager'].all.length; (() => { @Table({ freezeTableName: false, tableName: 'SuperUser' }) class User extends Model {} sequelize.addModels([User]); })(); const factorySize2 = sequelize['modelManager'].all.length; expect(factorySize).to.equal(factorySize2); }); it('allows us us to predefine the ID column with our own specs', () => { @Table class User extends Model { @PrimaryKey @Default('User') @Column id: string; } sequelize.addModels([User]); return User.sync({ force: true }).then(() => { return expect(User.create({ id: 'My own ID!' })).to.eventually.have.property( 'id', 'My own ID!' ); }); }); it('throws an error if 2 autoIncrements are passed', () => { expect(() => { @Table class User extends Model { @PrimaryKey @AutoIncrement @Column id: string; @PrimaryKey @AutoIncrement @Column id2: string; } sequelize.addModels([User]); }).to.throw(Error, 'Invalid Instance definition. Only one autoincrement field allowed.'); }); // TODO@robin not throwing, but should: looks good on sequelize-typescript side, so whats wrong? // it('throws an error if a custom model-wide validation is not a function', () => { // expect(() => { // @Table // class User extends Model { // @Column({ // validate: { // notFunction: 33 // } // }) // field: string; // } // sequelize.addModels([User]); // }).to.throw(Error, 'Members of the validate option must be functions. Model: Foo, error with validate member notFunction'); // }); // // it('throws an error if a custom model-wide validation has the same name as a field', () => { // expect(() => { // @Table // class User extends Model { // @Column({ // validate: { // field: () => null // } // }) // field: string; // } // sequelize.addModels([User]); // }).to.throw(Error, 'A model validator function must not have the same name as a field. Model: Foo, field/validation name: field'); // }); it('should allow me to set a default value for createdAt and updatedAt', () => { clock.restore(); @Table({ timestamps: true }) class User extends Model { @Column aNumber: number; @Default(moment('2012-01-01').toDate()) @Column createdAt: Date; @Default(moment('2012-01-02').toDate()) @Column updatedAt: Date; } sequelize.addModels([User]); return User.sync({ force: true }).then(() => { return User.create({ aNumber: 5 }).then((user) => { clock.restore(); return User.bulkCreate([{ aNumber: 10 }, { aNumber: 12 }]).then(() => { return User.findAll({ where: { aNumber: { [Op.gte]: 10 } } }).then((users) => { expect(moment(user.createdAt).format('YYYY-MM-DD')).to.equal('2012-01-01'); expect(moment(user.updatedAt).format('YYYY-MM-DD')).to.equal('2012-01-02'); users.forEach((u) => { expect(moment(u.createdAt).format('YYYY-MM-DD')).to.equal('2012-01-01'); expect(moment(u.updatedAt).format('YYYY-MM-DD')).to.equal('2012-01-02'); }); }); }); }); }); }); it('should allow me to set a function as default value', () => { const defaultFunction = stub().returns(5); @Table({ timestamps: true }) class User extends Model { @Default(defaultFunction) @Column aNumber: number; } sequelize.addModels([User]); return User.sync({ force: true }).then(() => { return User.create().then((user) => { return User.create().then((user2) => { expect(user.aNumber).to.equal(5); expect(user2.aNumber).to.equal(5); expect(defaultFunction.callCount).to.equal(2); }); }); }); }); it('should allow me to override updatedAt, createdAt, and deletedAt fields', () => { @Table class User extends Model { @Column aNumber: number; @UpdatedAt updatedOn: Date; @CreatedAt dateCreated: Date; @DeletedAt deletedAtThisTime: Date; } sequelize.addModels([User]); return User.sync({ force: true }).then(() => { return User.create({ aNumber: 4 }).then((user) => { expect(user.updatedOn).to.exist; expect(user.dateCreated).to.exist; return user.destroy().then(() => { return user.reload({ paranoid: false }).then(() => { expect(user.deletedAtThisTime).to.exist; }); }); }); }); }); it('should allow me to disable some of the timestamp fields', () => { @Table({ updatedAt: false, createdAt: false }) class User extends Model { @Column name: string; @DeletedAt deletedAtThisTime: Date; } sequelize.addModels([User]); return User.sync({ force: true }).then(() => { return User.create({ name: 'heyo', }).then((user) => { expect(user.createdAt).not.to.exist; expect(user['false']).not.to.exist; // because, you know we might accidentally add a field named 'false' user.name = 'heho'; return user.save().then((_user) => { expect(_user.updatedAt).not.to.exist; return _user.destroy().then(() => { return _user.reload({ paranoid: false }).then(() => { expect(_user.deletedAtThisTime).to.exist; }); }); }); }); }); }); it('returns proper defaultValues after save when setter is set', () => { const titleSetter = spy(); @Table({ updatedAt: false, createdAt: false }) class Task extends Model { @Column({ type: DataType.STRING(50), allowNull: false, defaultValue: '', set: titleSetter, }) title: string; @DeletedAt deletedAtThisTime: Date; } sequelize.addModels([Task]); return Task.sync({ force: true }).then(() => { return Task.build() .save() .then((record) => { expect(record.title).to.be.a('string'); expect(record.title).to.equal(''); expect(titleSetter.notCalled).to.be.ok; // The setter method should not be invoked for default values }); }); }); it('should work with both paranoid and underscored being true', () => { @Table({ paranoid: true, underscored: true }) class User extends Model { @Column aNumber: number; } sequelize.addModels([User]); return User.sync({ force: true }).then(() => { return User.create({ aNumber: 30 }).then(() => { return User.count().then((c) => { expect(c).to.equal(1); }); }); }); }); it('allows multiple column unique keys to be defined', () => { @Table class User extends Model { @Column({ unique: 'user_and_email', }) username: string; @Column({ unique: 'user_and_email', }) email: string; @Column({ unique: 'a_and_b', }) aCol: string; @Column({ unique: 'a_and_b', }) bCol: string; } sequelize.addModels([User]); return User.sync({ force: true, logging: _.after( 2, _.once((sql) => { expect(sql).to.match( /UNIQUE\s*([`"]?user_and_email[`"]?)?\s*\([`"]?username[`"]?, [`"]?email[`"]?\)/ ); expect(sql).to.match( /UNIQUE\s*([`"]?a_and_b[`"]?)?\s*\([`"]?aCol[`"]?, [`"]?bCol[`"]?\)/ ); }) ), }); }); it('allows unique on column with field aliases', () => { @Table class User extends Model { @Column({ field: 'user_name', unique: 'user_name_unique', }) username: string; } sequelize.addModels([User]); return User.sync({ force: true }).then(() => { return sequelize['queryInterface'].showIndex(User['tableName']).then((indexes) => { expect(indexes).to.have.length(1); const idxUnique = indexes[0]; expect(idxUnique.primary).to.equal(false); expect(idxUnique.unique).to.equal(true); expect(idxUnique.fields).to.deep.equal([ { attribute: 'user_name', length: undefined, order: undefined }, ]); }); }); }); it('allows us to customize the error message for unique constraint', () => { @Table class User extends Model { @Column({ unique: { name: 'user_and_email', msg: 'User and email must be unique' }, }) username: string; @Column({ unique: 'user_and_email', }) email: string; } sequelize.addModels([User]); return User.sync({ force: true }) .then(() => { return Promise.all([ User.create({ username: 'tobi', email: 'tobi@tobi.me' }), User.create({ username: 'tobi', email: 'tobi@tobi.me' }), ]); }) .catch((err) => { expect(err.message).to.equal('User and email must be unique'); }); // Native Catch expect one parameter only }); // If you use migrations to create unique indexes that have explicit names and/or contain fields // that have underscore in their name. Then sequelize must use the index name to map the custom message to the error thrown from db. it('allows us to map the customized error message with unique constraint name', () => { // Fake migration style index creation with explicit index definition @Table({ timestamps: true, indexes: [ { name: 'user_and_email_index', unique: true, fields: [ 'userId', { name: 'email', collate: 'RTRIM', order: 'DESC', length: 5, }, ], }, ], }) class User extends Model { @Column userId: number; @Column email: string; } sequelize.addModels([User]); return User.sync({ force: true }) .then(() => { // Redefine the model to use the index in database and override error message @Table({ timestamps: true }) class User extends Model { @Column({ unique: { name: 'user_and_email_index', msg: 'User and email must be unique' }, }) userId: number; @Column({ unique: 'user_and_email_index', }) email: string; } sequelize.addModels([User]); return Promise.all([ User.create({ userId: 1, email: 'tobi@tobi.me' }), User.create({ userId: 1, email: 'tobi@tobi.me' }), ]); }) .catch((err) => { expect(err.message).to.equal('User and email must be unique'); }); // Native Catch expect one parameter only }); it('should allow the user to specify indexes in options', () => { @Table({ indexes: [ { name: 'a_b_uniq', unique: true, method: 'BTREE', fields: [ 'fieldB', { attribute: 'fieldA', collate: 'RTRIM', order: 'DESC', length: 5, }, ], }, { type: 'FULLTEXT', fields: ['fieldC'], concurrently: true, }, { type: 'FULLTEXT', fields: ['fieldD'], }, ], engine: 'MyISAM', } as TableOptions) class ModelA extends Model { @Column fieldA: string; @Column fieldB: number; @Column fieldC: string; @Column fieldD: string; } sequelize.addModels([ModelA]); return sequelize .sync() .then(() => { return sequelize.sync(); // The second call should not try to create the indices again }) .then(() => { return sequelize['queryInterface'].showIndex(ModelA['tableName']); }) .then(([idx1, idx2]) => { expect(idx1.fields).to.deep.equal([ { attribute: 'fieldB', length: undefined, order: undefined }, { attribute: 'fieldA', length: undefined, order: undefined }, ]); expect(idx2.fields).to.deep.equal([ { attribute: 'fieldC', length: undefined, order: undefined }, ]); expect(idx1.name).to.equal('a_b_uniq'); expect(idx1.unique).to.be.ok; expect(idx2.name).to.equal('model_as_field_c'); expect(idx2.unique).not.to.be.ok; }); }); }); describe('build using new', () => { it('should create an instance of defined model', () => { const name = 'test'; @Table class User extends Model { @Column name: string; } sequelize.addModels([User]); const user = new User({ name }); expect(user).to.be.an.instanceOf(User); expect(user).to.have.property('name', name); }); }); describe('build', () => { it("doesn't create database entries", () => { MainUser.build({ username: 'John Wayne' }); return MainUser.findAll().then((users) => { expect(users).to.have.length(0); }); }); it('fills the objects with default values (timestamps=true)', () => { @Table({ timestamps: true }) class Task extends Model { @Default('a task!') @Column title: string; @Default(2) @Column foo: number; @Column bar: Date; @Default('asd') @Column(DataType.TEXT) foobar: string; @Default(false) @Column flag: boolean; } sequelize.addModels([Task]); expect(Task.build().title).to.equal('a task!'); expect(Task.build().foo).to.equal(2); expect(Task.build().bar).to.not.be.ok; expect(Task.build().foobar).to.equal('asd'); expect(Task.build().flag).to.be.false; }); it('fills the objects with default values', () => { @Table class Task extends Model { @Default('a task!') @Column title: string; @Default(2) @Column foo: number; @Column bar: Date; @Default('asd') @Column(DataType.TEXT) foobar: string; @Default(false) @Column flag: boolean; } sequelize.addModels([Task]); expect(Task.build().title).to.equal('a task!'); expect(Task.build().foo).to.equal(2); expect(Task.build().bar).to.not.be.ok; expect(Task.build().foobar).to.equal('asd'); expect(Task.build().flag).to.be.false; }); it('attaches getter and setter methods from attribute definition', () => { @Table class Product extends Model { @Column({ get(this: Product): string { return 'answer = ' + this.getDataValue('price'); }, set(this: Product, value: number): any { return this.setDataValue('price', value + 42); }, }) price: number; } sequelize.addModels([Product]); expect(Product.build({ price: 42 }).price).to.equal('answer = 84'); const p = Product.build({ price: 1 }); expect(p.price).to.equal('answer = 43'); p.price = 0; expect(p.price).to.equal('answer = 42'); }); it('uses get/set accessors', () => { @Table class Product extends Model { @Column(DataType.INTEGER) get priceInCents() { return this.getDataValue('priceInCents'); } @Column(DataType.VIRTUAL) set price(value: any) { this.setDataValue('priceInCents', value * 100); } get price() { return '$' + this.getDataValue('priceInCents') / 100; } } sequelize.addModels([Product]); expect(Product.build({ price: 20 }).priceInCents).to.equal(20 * 100); expect(Product.build({ priceInCents: 30 * 100 }).price).to.equal('$' + 30); }); describe('include', () => { it('should support basic includes', () => { @Table class Product extends Model { @Column title: string; @HasMany(() => Tag) tags: Tag[]; @ForeignKey(() => User) userId: number; @BelongsTo(() => User) user: { id: number; firstName: string; lastName: string; products: Product[] }; // why {...} instead of User? // with User reference it throws, // because of order of classes: User reference // does not exist here, when transpiled to es6 // see transpiled js file for details // NOTICE: this wouldn't be a problem if each // class is defined in its own file } @Table class Tag extends Model { id: number; @Column name: string; @ForeignKey(() => Product) productId: number; } @Table class User extends Model { @Column firstName: string; @Column lastName: string; @HasMany(() => Product) products: Product[]; } sequelize.addModels([Product, Tag, User]); const product = Product.build( { id: 1, title: 'Chair', tags: [ { id: 1, name: 'Alpha' }, { id: 2, name: 'Beta' }, ], user: { id: 1, firstName: 'Mick', lastName: 'Hansen', }, }, { include: [User, Tag], } ); expect(product.tags).to.be.ok; expect(product.tags.length).to.equal(2); expect(product.tags[0]).to.be.instanceof(Tag); expect(product.user).to.be.ok; expect(product.user).to.be.instanceof(User); }); it('should support includes with aliases', () => { @Table class Product extends Model { @Column title: string; @HasMany(() => Tag) categories: Tag[]; @ForeignKey(() => User) userId: number; @BelongsToMany(() => User, 'product_followers', 'productId', 'userId') followers: User[]; } @Table class Tag extends Model { id: number; @Column name: string; @ForeignKey(() => Product) productId: number; } @Table class User extends Model { id: number; @Column firstName: string; @Column lastName: string; @BelongsToMany(() => Product, 'product_followers', 'productId', 'userId') following: Product[]; } sequelize.addModels([Product, Tag, User]); const product = Product.build( { id: 1, title: 'Chair', categories: [ { id: 1, name: 'Alpha' }, { id: 2, name: 'Beta' }, { id: 3, name: 'Charlie' }, { id: 4, name: 'Delta' }, ], followers: [ { id: 1, firstName: 'Mick', lastName: 'Hansen', }, { id: 2, firstName: 'Jan', lastName: 'Meier', }, ], }, { include: [ { model: User, as: 'followers' }, { model: Tag, as: 'categories' }, ], } ); expect(product.categories).to.be.ok; expect(product.categories.length).to.equal(4); expect(product.categories[0]).to.be.instanceof(Tag); expect(product.followers).to.be.ok; expect(product.followers.length).to.equal(2); expect(product.followers[0]).to.be.instanceof(User); }); }); }); describe('findOne', () => { // TODO@robin sqlite3 transaction issue // if (current.dialect.supports.transactions) { // it('supports the transaction option in the first parameter', () => { // return Support.prepareTransactionTest(this.sequelize).bind({}).then((sequelize) => { // const User = sequelize.define('User', {username: Sequelize.STRING, foo: Sequelize.STRING}); // return User.sync({force: true}).then(() => { // return sequelize.transaction().then((t) => { // return User.create({username: 'foo'}, {transaction: t}).then(() => { // return User.findOne({where: {username: 'foo'}, transaction: t}).then((user) => { // expect(user).to.not.be.null; // return t.rollback(); // }); // }); // }); // }); // }); // }); // } it('should not fail if model is paranoid and where is an empty array', () => { @Table({ paranoid: true, timestamps: true }) class User extends Model { @Column username: string; } sequelize.addModels([User]); return User.sync({ force: true }) .then(() => { return User.create({ username: 'A fancy name' }); }) .then(() => { return User.findOne({ where: {} }); }) .then((u) => { expect(u.username).to.equal('A fancy name'); }); }); it('should filter based on the where clause even if IFindOptions.include is []', () => { @Table({ paranoid: true, timestamps: true }) class User extends Model { @Column username: string; } sequelize.addModels([User]); return User.sync({ force: true }) .then(() => { return User.create({ username: 'a1' }); }) .then(() => { return User.create({ username: 'a2' }); }) .then(() => { return User.findOne({ where: { username: 'a2' }, include: [] }); }) .then((u) => { expect(u.username).to.equal('a2'); }) .then(() => { return User.findOne({ where: { username: 'a1' }, include: [] }); }) .then((u) => { expect(u.username).to.equal('a1'); }); }); }); describe('findOrInitialize', () => { // TODO@robin sqlite3 transaction issue // if (current.dialect.supports.transactions) { // it('supports transactions', () => { // return Support.prepareTransactionTest(this.sequelize).bind({}).then((sequelize) => { // const User = sequelize.define('User', {username: Sequelize.STRING, foo: Sequelize.STRING}); // // return User.sync({force: true}).then(() => { // return sequelize.transaction().then((t) => { // return User.create({username: 'foo'}, {transaction: t}).then(() => { // return User.findOrInitialize({ // where: {username: 'foo'} // }).spread((user1) => { // return User.findOrInitialize({ // where: {username: 'foo'}, // transaction: t // }).spread((user2) => { // return User.findOrInitialize({ // where: {username: 'foo'}, // defaults: {foo: 'asd'}, // transaction: t // }).spread((user3) => { // expect(user1.isNewRecord).to.be.true; // expect(user2.isNewRecord).to.be.false; // expect(user3.isNewRecord).to.be.false; // return t.commit(); // }); // }); // }); // }); // }); // }); // }); // }); // } describe('returns an instance if it already exists', () => { it('with a single find field', () => { return MainUser.create({ username: 'Username' }).then((user) => { return MainUser.findOrBuild({ where: { username: user.username }, }).then(([_user, initialized]) => { expect(_user.id).to.equal(user.id); expect(_user.username).to.equal('Username'); expect(initialized).to.be.false; }); }); }); it('with multiple find fields', () => { return MainUser.create({ username: 'Username', data: 'data' }).then((user) => { return MainUser.findOrBuild({ where: { username: user.username, data: user.data, }, }).then(([_user, initialized]) => { expect(_user.id).to.equal(user.id); expect(_user.username).to.equal('Username'); expect(_user.data).to.equal('data'); expect(initialized).to.be.false; }); }); }); it('builds a new instance with default value.', () => { const data = { username: 'Username', }; const defaultValues = { data: 'ThisIsData', }; return MainUser.findOrBuild({ where: data, defaults: defaultValues, }).then(([user, initialized]) => { expect(user.id).to.be.null; expect(user.username).to.equal('Username'); expect(user.data).to.equal('ThisIsData'); expect(initialized).to.be.true; expect(user.isNewRecord).to.be.true; }); }); }); }); describe('update', () => { it('throws an error if no where clause is given', () => { @Table class User extends Model { @Column username: string; } sequelize.addModels([User]); return sequelize .sync({ force: true }) .then(() => { return (User as any).update(); }) .then( () => { throw new Error('Update should throw an error if no where clause is given.'); }, (err) => { expect(err).to.be.an.instanceof(Error); expect(err.message).to.match(/^Missing where attribute in the options parameter/); } ); }); // TODO@robin sqlite3 transaction issue // if (current.dialect.supports.transactions) { // it('supports transactions', () => { // return Support.prepareTransactionTest(this.sequelize).bind({}).then((sequelize) => { // const User = sequelize.define('User', {username: Sequelize.STRING}); // // return User.sync({force: true}).then(() => { // return User.create({username: 'foo'}).then(() => { // return sequelize.transaction().then((t) => { // return User.update({username: 'bar'}, {where: {username: 'foo'}, transaction: t}).then(() => { // return User.findAll().then((users1) => { // return User.findAll({transaction: t}).then((users2) => { // expect(users1[0].username).to.equal('foo'); // expect(users2[0].username).to.equal('bar'); // return t.rollback(); // }); // }); // }); // }); // }); // }); // }); // }); // } it('updates the attributes that we select only without updating createdAt', () => { @Table({ timestamps: true, paranoid: true }) class User extends Model { @Column username: string; @Column secretValue: string; } sequelize.addModels([User]); let test = false; return User.sync({ force: true }) .then(() => { return User.create({ username: 'Peter', secretValue: '42' }).then((user) => { return user.update( { secretValue: '43' }, { fields: ['secretValue'], logging: (sql) => { test = true; expect(sql).to.match( /UPDATE\s+[`"]+Users[`"]+\s+SET\s+[`"]+secretValue[`"]=(\$1|\?),[`"]+updatedAt[`"]+=(\$2|\?)\s+WHERE [`"]+id[`"]+\s=\s(\$3|\?)/ ); }, } ); }); }) .then(() => { expect(test).to.be.true; }); }); // // it('allows sql logging of updated statements', () => { // const User = this.sequelize.define('User', { // name: Sequelize.STRING, // bio: Sequelize.TEXT // }, { // paranoid: true // }); // const test = false; // return User.sync({force: true}).then(() => { // return User.create({name: 'meg', bio: 'none'}).then((u) => { // expect(u).to.exist; // return u.updateAttributes({name: 'brian'}, { // logging: (sql) => { // test = true; // expect(sql).to.exist; // expect(sql.toUpperCase().indexOf('UPDATE')).to.be.above(-1); // } // }); // }); // }).then(() => { // expect(test).to.be.true; // }); // }); // // it('updates only values that match filter', () => { // const self = this // , data = [{username: 'Peter', secretValue: '42'}, // {username: 'Paul', secretValue: '42'}, // {username: 'Bob', secretValue: '43'}]; // // return MainUser.bulkCreate(data).then(() => { // return self.User.update({username: 'Bill'}, {where: {secretValue: '42'}}).then(() => { // return self.User.findAll({order: ['id']}).then((users) => { // expect(users.length).to.equal(3); // // users.forEach((user) => { // if (user.secretValue === '42') { // expect(user.username).to.equal('Bill'); // } else { // expect(user.username).to.equal('Bob'); // } // }); // // }); // }); // }); // }); // // it('updates only values that match the allowed fields', () => { // const self = this // , data = [{username: 'Peter', secretValue: '42'}]; // // return MainUser.bulkCreate(data).then(() => { // return self.User.update({username: 'Bill', secretValue: '43'}, { // where: {secretValue: '42'}, // fields: ['username'] // }).then(() => { // return self.User.findAll({order: ['id']}).then((users) => { // expect(users.length).to.equal(1); // // const user = users[0]; // expect(user.username).to.equal('Bill'); // expect(user.secretValue).to.equal('42'); // }); // }); // }); // }); // // it('updates with casting', () => { // const self = this; // return MainUser.create({ // username: 'John' // }).then(() => { // return self.User.update({username: self.sequelize.cast('1', dialect === 'mssql' ? 'nvarchar' : 'char')}, {where: {username: 'John'}}).then(() => { // return self.User.findAll().then((users) => { // expect(users[0].username).to.equal('1'); // }); // }); // }); // }); // // it('updates with function and column value', () => { // const self = this; // // return MainUser.create({ // username: 'John' // }).then(() => { // return self.User.update({username: self.sequelize.fn('upper', self.sequelize.col('username'))}, {where: {username: 'John'}}).then(() => { // return self.User.findAll().then((users) => { // expect(users[0].username).to.equal('JOHN'); // }); // }); // }); // }); // // it('does not update virtual attributes', () => { // const User = this.sequelize.define('User', { // username: Sequelize.STRING, // virtual: Sequelize.VIRTUAL // }); // // return User.create({ // username: 'jan' // }).then(() => { // return User.update({ // username: 'kurt', // virtual: 'test' // }, { // where: { // username: 'jan' // } // }); // }).then(() => { // return User.findAll(); // }).spread((user) => { // expect(user.username).to.equal('kurt'); // }); // }); // // it('doesn\'t update attributes that are altered by virtual setters when option is enabled', () => { // const User = this.sequelize.define('UserWithVirtualSetters', { // username: Sequelize.STRING, // illness_name: Sequelize.STRING, // illness_pain: Sequelize.INTEGER, // illness: { // type: Sequelize.VIRTUAL, // set: (value) => { // this.set('illness_name', value.name); // this.set('illness_pain', value.pain); // } // } // }); // // return User.sync({force: true}).then(() => { // return User.create({ // username: 'Jan', // illness_name: 'Headache', // illness_pain: 5 // }); // }).then(() => { // return User.update({ // illness: {pain: 10, name: 'Backache'} // }, { // where: { // username: 'Jan' // }, // sideEffects: false // }); // }).then((user) => { // return User.findAll(); // }).spread((user) => { // expect(user.illness_pain).to.be.equal(5); // }); // }); // // it('updates attributes that are altered by virtual setters', () => { // const User = this.sequelize.define('UserWithVirtualSetters', { // username: Sequelize.STRING, // illness_name: Sequelize.STRING, // illness_pain: Sequelize.INTEGER, // illness: { // type: Sequelize.VIRTUAL, // set: (value) => { // this.set('illness_name', value.name); // this.set('illness_pain', value.pain); // } // } // }); // // return User.sync({force: true}).then(() => { // return User.create({ // username: 'Jan', // illness_name: 'Headache', // illness_pain: 5 // }); // }).then(() => { // return User.update({ // illness: {pain: 10, name: 'Backache'} // }, { // where: { // username: 'Jan' // } // }); // }).then((user) => { // return User.findAll(); // }).spread((user) => { // expect(user.illness_pain).to.be.equal(10); // }); // }); // // it('should properly set data when individualHooks are true', () => { // const self = this; // // self.User.beforeUpdate((instance) => { // instance.set('intVal', 1); // }); // // return self.User.create({username: 'Peter'}).then((user) => { // return self.User.update({data: 'test'}, {where: {id: user.id}, individualHooks: true}).then(() => { // return self.User.findById(user.id).then(function(userUpdated) { // expect(userUpdated.intVal).to.be.equal(1); // }); // }); // }); // }); // // it('sets updatedAt to the current timestamp', () => { // const data = [{username: 'Peter', secretValue: '42'}, // {username: 'Paul', secretValue: '42'}, // {username: 'Bob', secretValue: '43'}]; // // return MainUser.bulkCreate(data).bind(this).then(() => { // return MainUser.findAll({order: ['id']}); // }).then((users) => { // this.updatedAt = users[0].updatedAt; // // expect(this.updatedAt).to.be.ok; // expect(this.updatedAt).to.equalTime(users[2].updatedAt); // All users should have the same updatedAt // // // Pass the time so we can actually see a change // clock.tick(1000); // return MainUser.update({username: 'Bill'}, {where: {secretValue: '42'}}); // }).then(() => { // return MainUser.findAll({order: ['id']}); // }).then((users) => { // expect(users[0].username).to.equal('Bill'); // expect(users[1].username).to.equal('Bill'); // expect(users[2].username).to.equal('Bob'); // // expect(users[0].updatedAt).to.be.afterTime(this.updatedAt); // expect(users[2].updatedAt).to.equalTime(this.updatedAt); // }); // }); // // it('returns the number of affected rows', () => { // const self = this // , data = [{username: 'Peter', secretValue: '42'}, // {username: 'Paul', secretValue: '42'}, // {username: 'Bob', secretValue: '43'}]; // // return MainUser.bulkCreate(data).then(() => { // return self.User.update({username: 'Bill'}, {where: {secretValue: '42'}}).spread((affectedRows) => { // expect(affectedRows).to.equal(2); // }).then(() => { // return self.User.update({username: 'Bill'}, {where: {secretValue: '44'}}).spread((affectedRows) => { // expect(affectedRows).to.equal(0); // }); // }); // }); // }); }); // // describe('destroy', () => { // it('convenient method `truncate` should clear the table', () => { // const User = this.sequelize.define('User', {username: DataTypes.STRING}), // data = [ // {username: 'user1'}, // {username: 'user2'} // ]; // // return this.sequelize.sync({force: true}).then(() => { // return User.bulkCreate(data); // }).then(() => { // return User.truncate(); // }).then(() => { // return expect(User.findAll()).to.eventually.have.length(0); // }); // }); // // it('truncate should clear the table', () => { // const User = this.sequelize.define('User', {username: DataTypes.STRING}), // data = [ // {username: 'user1'}, // {username: 'user2'} // ]; // // return this.sequelize.sync({force: true}).then(() => { // return User.bulkCreate(data); // }).then(() => { // return User.destroy({truncate: true}); // }).then(() => { // return expect(User.findAll()).to.eventually.have.length(0); // }); // }); // // it('throws an error if no where clause is given', () => { // const User = this.sequelize.define('User', {username: DataTypes.STRING}); // // return this.sequelize.sync({force: true}).then(() => { // return User.destroy(); // }).then(() => { // throw new Error('Destroy should throw an error if no where clause is given.'); // }, (err) => { // expect(err).to.be.an.instanceof(Error); // expect(err.message).to.equal('Missing where or truncate attribute in the options parameter of model.destroy.'); // }); // }); // // it('deletes all instances when given an empty where object', () => { // const User = this.sequelize.define('User', {username: DataTypes.STRING}), // data = [ // {username: 'user1'}, // {username: 'user2'} // ]; // // return this.sequelize.sync({force: true}).then(() => { // return User.bulkCreate(data); // }).then(() => { // return User.destroy({where: {}}); // }).then((affectedRows) => { // expect(affectedRows).to.equal(2); // return User.findAll(); // }).then((users) => { // expect(users).to.have.length(0); // }); // }); // // if (current.dialect.supports.transactions) { // it('supports transactions', () => { // return Support.prepareTransactionTest(this.sequelize).bind({}).then((sequelize) => { // const User = sequelize.define('User', {username: Sequelize.STRING}); // // return User.sync({force: true}).then(() => { // return User.create({username: 'foo'}).then(() => { // return sequelize.transaction().then((t) => { // return User.destroy({ // where: {}, // transaction: t // }).then(() => { // return User.count().then((count1) => { // return User.count({transaction: t}).then((count2) => { // expect(count1).to.equal(1); // expect(count2).to.equal(0); // return t.rollback(); // }); // }); // }); // }); // }); // }); // }); // }); // } // // it('deletes values that match filter', () => { // const self = this // , data = [{username: 'Peter', secretValue: '42'}, // {username: 'Paul', secretValue: '42'}, // {username: 'Bob', secretValue: '43'}]; // // return MainUser.bulkCreate(data).then(() => { // return self.User.destroy({where: {secretValue: '42'}}) // .then(() => { // return self.User.findAll({order: ['id']}).then((users) => { // expect(users.length).to.equal(1); // expect(users[0].username).to.equal('Bob'); // }); // }); // }); // }); // // it('works without a primary key', () => { // const Log = this.sequelize.define('Log', { // client_id: DataTypes.INTEGER, // content: DataTypes.TEXT, // timestamp: DataTypes.DATE // }); // Log.removeAttribute('id'); // // return Log.sync({force: true}).then(() => { // return Log.create({ // client_id: 13, // content: 'Error!', // timestamp: new Date() // }); // }).then(() => { // return Log.destroy({ // where: { // client_id: 13 // } // }); // }).then(() => { // return Log.findAll().then((logs) => { // expect(logs.length).to.equal(0); // }); // }); // }); // // it('supports .field', () => { // const UserProject = this.sequelize.define('UserProject', { // userId: { // type: DataTypes.INTEGER, // field: 'user_id' // } // }); // // return UserProject.sync({force: true}).then(() => { // return UserProject.create({ // userId: 10 // }); // }).then(() => { // return UserProject.destroy({ // where: { // userId: 10 // } // }); // }).then(() => { // return UserProject.findAll(); // }).then((userProjects) => { // expect(userProjects.length).to.equal(0); // }); // }); // // it('sets deletedAt to the current timestamp if paranoid is true', () => { // const self = this // , qi = this.sequelize.queryInterface.QueryGenerator.quoteIdentifier.bind(this.sequelize.queryInterface.QueryGenerator) // , ParanoidUser = self.sequelize.define('ParanoidUser', { // username: Sequelize.STRING, // secretValue: Sequelize.STRING, // data: Sequelize.STRING, // intVal: {type: Sequelize.INTEGER, defaultValue: 1} // }, { // paranoid: true // }) // , data = [{username: 'Peter', secretValue: '42'}, // {username: 'Paul', secretValue: '42'}, // {username: 'Bob', secretValue: '43'}]; // // return ParanoidUser.sync({force: true}).then(() => { // return ParanoidUser.bulkCreate(data); // }).bind({}).then(() => { // // since we save in UTC, let's format to UTC time // this.date = moment().utc().format('YYYY-MM-DD h:mm'); // return ParanoidUser.destroy({where: {secretValue: '42'}}); // }).then(() => { // return ParanoidUser.findAll({order: ['id']}); // }).then((users) => { // expect(users.length).to.equal(1); // expect(users[0].username).to.equal('Bob'); // // return self.sequelize.query('SELECT * FROM ' + qi('ParanoidUsers') + ' WHERE ' + qi('deletedAt') + ' IS NOT NULL ORDER BY ' + qi('id')); // }).spread((users) => { // expect(users[0].username).to.equal('Peter'); // expect(users[1].username).to.equal('Paul'); // // expect(moment(new Date(users[0].deletedAt)).utc().format('YYYY-MM-DD h:mm')).to.equal(this.date); // expect(moment(new Date(users[1].deletedAt)).utc().format('YYYY-MM-DD h:mm')).to.equal(this.date); // }); // }); // // it('does not set deletedAt for previously destroyed instances if paranoid is true', () => { // const User = this.sequelize.define('UserCol', { // secretValue: Sequelize.STRING, // username: Sequelize.STRING // }, {paranoid: true}); // // return User.sync({force: true}).then(() => { // return User.bulkCreate([ // {username: 'Toni', secretValue: '42'}, // {username: 'Tobi', secretValue: '42'}, // {username: 'Max', secretValue: '42'} // ]).then(() => { // return User.findById(1).then((user) => { // return user.destroy().then(() => { // return user.reload({paranoid: false}).then(() => { // const deletedAt = user.deletedAt; // // return User.destroy({where: {secretValue: '42'}}).then(() => { // return user.reload({paranoid: false}).then(() => { // expect(user.deletedAt).to.eql(deletedAt); // }); // }); // }); // }); // }); // }); // }); // }); // // describe("can't find records marked as deleted with paranoid being true", () => { // it('with the DAOFactory', () => { // const User = this.sequelize.define('UserCol', { // username: Sequelize.STRING // }, {paranoid: true}); // // return User.sync({force: true}).then(() => { // return User.bulkCreate([ // {username: 'Toni'}, // {username: 'Tobi'}, // {username: 'Max'} // ]).then(() => { // return User.findById(1).then((user) => { // return user.destroy().then(() => { // return User.findById(1).then((user) => { // expect(user).to.be.null; // return User.count().then((cnt) => { // expect(cnt).to.equal(2); // return User.findAll().then((users) => { // expect(users).to.have.length(2); // }); // }); // }); // }); // }); // }); // }); // }); // }); // // describe('can find paranoid records if paranoid is marked as false in query', () => { // it('with the DAOFactory', () => { // const User = this.sequelize.define('UserCol', { // username: Sequelize.STRING // }, {paranoid: true}); // // return User.sync({force: true}) // .then(() => { // return User.bulkCreate([ // {username: 'Toni'}, // {username: 'Tobi'}, // {username: 'Max'} // ]); // }) // .then(() => { // return User.findById(1); // }) // .then((user) => { // return user.destroy(); // }) // .then(() => { // return User.find({where: 1, paranoid: false}); // }) // .then((user) => { // expect(user).to.exist; // return User.findById(1); // }) // .then((user) => { // expect(user).to.be.null; // return [User.count(), User.count({paranoid: false})]; // }) // .spread((cnt, cntWithDeleted) => { // expect(cnt).to.equal(2); // expect(cntWithDeleted).to.equal(3); // }); // }); // }); // // it('should include deleted associated records if include has paranoid marked as false', () => { // const User = this.sequelize.define('User', { // username: Sequelize.STRING // }, {paranoid: true}); // const Pet = this.sequelize.define('Pet', { // name: Sequelize.STRING, // UserId: Sequelize.INTEGER // }, {paranoid: true}); // // User.hasMany(Pet); // Pet.belongsTo(User); // // const user; // return User.sync({force: true}) // .then(() => { // return Pet.sync({force: true}); // }) // .then(() => { // return User.create({username: 'Joe'}); // }) // .then((_user) => { // user = _user; // return Pet.bulkCreate([ // {name: 'Fido', UserId: user.id}, // {name: 'Fifi', UserId: user.id} // ]); // }) // .then(() => { // return Pet.findById(1); // }) // .then((pet) => { // return pet.destroy(); // }) // .then(() => { // return [ // User.find({where: {id: user.id}, include: Pet}), // User.find({ // where: {id: user.id}, // include: [{model: Pet, paranoid: false}] // }) // ]; // }) // .spread((user, userWithDeletedPets) => { // expect(user).to.exist; // expect(user.Pets).to.have.length(1); // expect(userWithDeletedPets).to.exist; // expect(userWithDeletedPets.Pets).to.have.length(2); // }); // }); // // it('should delete a paranoid record if I set force to true', () => { // const self = this; // const User = this.sequelize.define('paranoiduser', { // username: Sequelize.STRING // }, {paranoid: true}); // // return User.sync({force: true}).then(() => { // return User.bulkCreate([ // {username: 'Bob'}, // {username: 'Tobi'}, // {username: 'Max'}, // {username: 'Tony'} // ]); // }).then(() => { // return User.find({where: {username: 'Bob'}}); // }).then((user) => { // return user.destroy({force: true}); // }).then(() => { // return expect(User.find({where: {username: 'Bob'}})).to.eventually.be.null; // }).then(() => { // return User.find({where: {username: 'Tobi'}}); // }).then((tobi) => { // return tobi.destroy(); // }).then(() => { // return self.sequelize.query('SELECT * FROM paranoidusers WHERE username=\'Tobi\'', {plain: true}); // }).then((result) => { // expect(result.username).to.equal('Tobi'); // return User.destroy({where: {username: 'Tony'}}); // }).then(() => { // return self.sequelize.query('SELECT * FROM paranoidusers WHERE username=\'Tony\'', {plain: true}); // }).then((result) => { // expect(result.username).to.equal('Tony'); // return User.destroy({where: {username: ['Tony', 'Max']}, force: true}); // }).then(() => { // return self.sequelize.query('SELECT * FROM paranoidusers', {raw: true}); // }).spread((users) => { // expect(users).to.have.length(1); // expect(users[0].username).to.equal('Tobi'); // }); // }); // // it('returns the number of affected rows', () => { // const self = this // , data = [{username: 'Peter', secretValue: '42'}, // {username: 'Paul', secretValue: '42'}, // {username: 'Bob', secretValue: '43'}]; // // return MainUser.bulkCreate(data).then(() => { // return self.User.destroy({where: {secretValue: '42'}}).then((affectedRows) => { // expect(affectedRows).to.equal(2); // }); // }).then(() => { // return self.User.destroy({where: {secretValue: '44'}}).then((affectedRows) => { // expect(affectedRows).to.equal(0); // }); // }); // }); // // it('supports table schema/prefix', () => { // const self = this // , data = [{username: 'Peter', secretValue: '42'}, // {username: 'Paul', secretValue: '42'}, // {username: 'Bob', secretValue: '43'}] // , prefixUser = self.User.schema('prefix'); // // const run = () => { // return prefixUser.sync({force: true}).then(() => { // return prefixUser.bulkCreate(data).then(() => { // return prefixUser.destroy({where: {secretValue: '42'}}).then(() => { // return prefixUser.findAll({order: ['id']}).then((users) => { // expect(users.length).to.equal(1); // expect(users[0].username).to.equal('Bob'); // }); // }); // }); // }); // }; // // return this.sequelize.queryInterface.dropAllSchemas().then(() => { // return self.sequelize.queryInterface.createSchema('prefix').then(() => { // return run.call(self); // }); // }); // }); // }); // // describe('restore', () => { // it('returns an error if the model is not paranoid', () => { // const self = this; // // return MainUser.create({username: 'Peter', secretValue: '42'}) // .then(() => { // expect(() => { // self.User.restore({where: {secretValue: '42'}}); // }).to.throw(Error, 'Model is not paranoid'); // }); // }); // // it('restores a previously deleted model', () => { // const self = this // , ParanoidUser = self.sequelize.define('ParanoidUser', { // username: Sequelize.STRING, // secretValue: Sequelize.STRING, // data: Sequelize.STRING, // intVal: {type: Sequelize.INTEGER, defaultValue: 1} // }, { // paranoid: true // }) // , data = [{username: 'Peter', secretValue: '42'}, // {username: 'Paul', secretValue: '43'}, // {username: 'Bob', secretValue: '44'}]; // // return ParanoidUser.sync({force: true}).then(() => { // return ParanoidUser.bulkCreate(data); // }).then(() => { // return ParanoidUser.destroy({where: {secretValue: '42'}}); // }).then(() => { // return ParanoidUser.restore({where: {secretValue: '42'}}); // }).then(() => { // return ParanoidUser.find({where: {secretValue: '42'}}); // }).then((user) => { // expect(user).to.be.ok; // expect(user.username).to.equal('Peter'); // }); // }); // }); // // describe('equals', () => { // it('correctly determines equality of objects', () => { // return MainUser.create({username: 'hallo', data: 'welt'}).then((u) => { // expect(u.equals(u)).to.be.ok; // }); // }); // // // sqlite can't handle multiple primary keys // if (dialect !== 'sqlite') { // it('correctly determines equality with multiple primary keys', () => { // const userKeys = this.sequelize.define('userkeys', { // foo: {type: Sequelize.STRING, primaryKey: true}, // bar: {type: Sequelize.STRING, primaryKey: true}, // name: Sequelize.STRING, // bio: Sequelize.TEXT // }); // // return userKeys.sync({force: true}).then(() => { // return userKeys.create({foo: '1', bar: '2', name: 'hallo', bio: 'welt'}).then((u) => { // expect(u.equals(u)).to.be.ok; // }); // }); // }); // } // }); // // describe('equalsOneOf', () => { // // sqlite can't handle multiple primary keys // if (dialect !== 'sqlite') { // beforeEach(() => { // MainUserKey = this.sequelize.define('userKeys', { // foo: {type: Sequelize.STRING, primaryKey: true}, // bar: {type: Sequelize.STRING, primaryKey: true}, // name: Sequelize.STRING, // bio: Sequelize.TEXT // }); // // return MainUserKey.sync({force: true}); // }); // // it('determines equality if one is matching', () => { // return MainUserKey.create({foo: '1', bar: '2', name: 'hallo', bio: 'welt'}).then((u) => { // expect(u.equalsOneOf([u, {a: 1}])).to.be.ok; // }); // }); // // it("doesn't determine equality if none is matching", () => { // return MainUserKey.create({foo: '1', bar: '2', name: 'hallo', bio: 'welt'}).then((u) => { // expect(u.equalsOneOf([{b: 2}, {a: 1}])).to.not.be.ok; // }); // }); // } // }); // // describe('count', () => { // if (current.dialect.supports.transactions) { // it('supports transactions', () => { // return Support.prepareTransactionTest(this.sequelize).bind({}).then((sequelize) => { // const User = sequelize.define('User', {username: Sequelize.STRING}); // // return User.sync({force: true}).then(() => { // return sequelize.transaction().then((t) => { // return User.create({username: 'foo'}, {transaction: t}).then(() => { // return User.count().then((count1) => { // return User.count({transaction: t}).then((count2) => { // expect(count1).to.equal(0); // expect(count2).to.equal(1); // return t.rollback(); // }); // }); // }); // }); // }); // }); // }); // } // // it('counts all created objects', () => { // const self = this; // return MainUser.bulkCreate([{username: 'user1'}, {username: 'user2'}]).then(() => { // return self.User.count().then((count) => { // expect(count).to.equal(2); // }); // }); // }); // // it('returns multiple rows when using group', () => { // const self = this; // return MainUser.bulkCreate([ // {username: 'user1', data: 'A'}, // {username: 'user2', data: 'A'}, // {username: 'user3', data: 'B'} // ]).then(() => { // return self.User.count({ // attributes: ['data'], // group: ['data'] // }).then((count) => { // expect(count.length).to.equal(2); // }); // }); // }); // // describe("options sent to aggregate", () => { // const options, aggregateSpy; // // beforeEach(() => { // options = {where: {username: 'user1'}}; // // aggregateSpy = spy(MainUser, "aggregate"); // }); // // afterEach(() => { // expect(aggregateSpy).to.have.been.calledWith( // sinon.match.any, sinon.match.any, // sinon.match.object.and(sinon.match.has('where', {username: 'user1'}))); // // aggregateSpy.restore(); // }); // // it('modifies option "limit" by setting it to null', () => { // options.limit = 5; // // return MainUser.count(options).then(() => { // expect(aggregateSpy).to.have.been.calledWith( // sinon.match.any, sinon.match.any, // sinon.match.object.and(sinon.match.has('limit', null))); // }); // }); // // it('modifies option "offset" by setting it to null', () => { // options.offset = 10; // // return MainUser.count(options).then(() => { // expect(aggregateSpy).to.have.been.calledWith( // sinon.match.any, sinon.match.any, // sinon.match.object.and(sinon.match.has('offset', null))); // }); // }); // // it('modifies option "order" by setting it to null', () => { // options.order = "username"; // // return MainUser.count(options).then(() => { // expect(aggregateSpy).to.have.been.calledWith( // sinon.match.any, sinon.match.any, // sinon.match.object.and(sinon.match.has('order', null))); // }); // }); // }); // // it('allows sql logging', () => { // const test = false; // return MainUser.count({ // logging: (sql) => { // test = true; // expect(sql).to.exist; // expect(sql.toUpperCase().indexOf('SELECT')).to.be.above(-1); // } // }).then(() => { // expect(test).to.be.true; // }); // }); // // it('filters object', () => { // const self = this; // return MainUser.create({username: 'user1'}).then(() => { // return self.User.create({username: 'foo'}).then(() => { // return self.User.count({where: ["username LIKE '%us%'"]}).then((count) => { // expect(count).to.equal(1); // }); // }); // }); // }); // // it('supports distinct option', () => { // const Post = this.sequelize.define('Post', {}); // const PostComment = this.sequelize.define('PostComment', {}); // Post.hasMany(PostComment); // return Post.sync({force: true}) // .then(() => PostComment.sync({force: true})) // .then(() => Post.create({})) // .then((post) => PostComment.bulkCreate([{PostId: post.id}, {PostId: post.id}])) // .then(() => Promise.join( // Post.count({distinct: false, include: [{model: PostComment, required: false}]}), // Post.count({distinct: true, include: [{model: PostComment, required: false}]}), // (count1, count2) => { // expect(count1).to.equal(2); // expect(count2).to.equal(1); // }) // ); // }); // // }); // // describe('min', () => { // beforeEach(() => { // const self = this; // MainUserWithAge = this.sequelize.define('UserWithAge', { // age: Sequelize.INTEGER // }); // // MainUserWithDec = this.sequelize.define('UserWithDec', { // value: Sequelize.DECIMAL(10, 3) // }); // // return MainUserWithAge.sync({force: true}).then(() => { // return self.UserWithDec.sync({force: true}); // }); // }); // // if (current.dialect.supports.transactions) { // it('supports transactions', () => { // return Support.prepareTransactionTest(this.sequelize).bind({}).then((sequelize) => { // const User = sequelize.define('User', {age: Sequelize.INTEGER}); // // return User.sync({force: true}).then(() => { // return sequelize.transaction().then((t) => { // return User.bulkCreate([{age: 2}, {age: 5}, {age: 3}], {transaction: t}).then(() => { // return User.min('age').then((min1) => { // return User.min('age', {transaction: t}).then((min2) => { // expect(min1).to.be.not.ok; // expect(min2).to.equal(2); // return t.rollback(); // }); // }); // }); // }); // }); // }); // }); // } // // it('should return the min value', () => { // const self = this; // return MainUserWithAge.bulkCreate([{age: 3}, {age: 2}]).then(() => { // return self.UserWithAge.min('age').then((min) => { // expect(min).to.equal(2); // }); // }); // }); // // it('allows sql logging', () => { // const test = false; // return MainUserWithAge.min('age', { // logging: (sql) => { // test = true; // expect(sql).to.exist; // expect(sql.toUpperCase().indexOf('SELECT')).to.be.above(-1); // } // }).then(() => { // expect(test).to.be.true; // }); // }); // // it('should allow decimals in min', () => { // const self = this; // return MainUserWithDec.bulkCreate([{value: 5.5}, {value: 3.5}]).then(() => { // return self.UserWithDec.min('value').then((min) => { // expect(min).to.equal(3.5); // }); // }); // }); // // it('should allow strings in min', () => { // const self = this; // return MainUser.bulkCreate([{username: 'bbb'}, {username: 'yyy'}]).then(() => { // return self.User.min('username').then((min) => { // expect(min).to.equal('bbb'); // }); // }); // }); // // it('should allow dates in min', () => { // const self = this; // return MainUser.bulkCreate([{theDate: new Date(2000, 1, 1)}, {theDate: new Date(1990, 1, 1)}]).then(() => { // return self.User.min('theDate').then((min) => { // expect(min).to.be.a('Date'); // expect(new Date(1990, 1, 1)).to.equalDate(min); // }); // }); // }); // }); // // describe('max', () => { // beforeEach(() => { // const self = this; // MainUserWithAge = this.sequelize.define('UserWithAge', { // age: Sequelize.INTEGER, // order: Sequelize.INTEGER // }); // // MainUserWithDec = this.sequelize.define('UserWithDec', { // value: Sequelize.DECIMAL(10, 3) // }); // // return MainUserWithAge.sync({force: true}).then(() => { // return self.UserWithDec.sync({force: true}); // }); // }); // // if (current.dialect.supports.transactions) { // it('supports transactions', () => { // return Support.prepareTransactionTest(this.sequelize).bind({}).then((sequelize) => { // const User = sequelize.define('User', {age: Sequelize.INTEGER}); // // return User.sync({force: true}).then(() => { // return sequelize.transaction().then((t) => { // return User.bulkCreate([{age: 2}, {age: 5}, {age: 3}], {transaction: t}).then(() => { // return User.max('age').then((min1) => { // return User.max('age', {transaction: t}).then((min2) => { // expect(min1).to.be.not.ok; // expect(min2).to.equal(5); // return t.rollback(); // }); // }); // }); // }); // }); // }); // }); // } // // it('should return the max value for a field named the same as an SQL reserved keyword', () => { // const self = this; // return MainUserWithAge.bulkCreate([{age: 2, order: 3}, {age: 3, order: 5}]).then(() => { // return self.UserWithAge.max('order').then((max) => { // expect(max).to.equal(5); // }); // }); // }); // // it('should return the max value', () => { // const self = this; // return self.UserWithAge.bulkCreate([{age: 2}, {age: 3}]).then(() => { // return self.UserWithAge.max('age').then((max) => { // expect(max).to.equal(3); // }); // }); // }); // // it('should allow decimals in max', () => { // const self = this; // return MainUserWithDec.bulkCreate([{value: 3.5}, {value: 5.5}]).then(() => { // return self.UserWithDec.max('value').then((max) => { // expect(max).to.equal(5.5); // }); // }); // }); // // it('should allow dates in max', () => { // const self = this; // return MainUser.bulkCreate([ // {theDate: new Date(2013, 11, 31)}, // {theDate: new Date(2000, 1, 1)} // ]).then(() => { // return self.User.max('theDate').then((max) => { // expect(max).to.be.a('Date'); // expect(max).to.equalDate(new Date(2013, 11, 31)); // }); // }); // }); // // it('should allow strings in max', () => { // const self = this; // return MainUser.bulkCreate([{username: 'aaa'}, {username: 'zzz'}]).then(() => { // return self.User.max('username').then((max) => { // expect(max).to.equal('zzz'); // }); // }); // }); // // it('allows sql logging', () => { // const logged = false; // return MainUserWithAge.max('age', { // logging: (sql) => { // expect(sql).to.exist; // logged = true; // expect(sql.toUpperCase().indexOf('SELECT')).to.be.above(-1); // } // }).then(() => { // expect(logged).to.true; // }); // }); // }); // // describe('sum', () => { // beforeEach(() => { // MainUserWithAge = this.sequelize.define('UserWithAge', { // age: Sequelize.INTEGER, // order: Sequelize.INTEGER, // gender: Sequelize.ENUM('male', 'female') // }); // // MainUserWithDec = this.sequelize.define('UserWithDec', { // value: Sequelize.DECIMAL(10, 3) // }); // // MainUserWithFields = this.sequelize.define('UserWithFields', { // age: { // type: Sequelize.INTEGER, // field: 'user_age' // }, // order: Sequelize.INTEGER, // gender: { // type: Sequelize.ENUM('male', 'female'), // field: 'male_female' // } // }); // // return Promise.join( // MainUserWithAge.sync({force: true}), // MainUserWithDec.sync({force: true}), // MainUserWithFields.sync({force: true}) // ); // }); // // it('should return the sum of the values for a field named the same as an SQL reserved keyword', () => { // const self = this; // return MainUserWithAge.bulkCreate([{age: 2, order: 3}, {age: 3, order: 5}]).then(() => { // return self.UserWithAge.sum('order').then((sum) => { // expect(sum).to.equal(8); // }); // }); // }); // // it('should return the sum of a field in various records', () => { // const self = this; // return self.UserWithAge.bulkCreate([{age: 2}, {age: 3}]).then(() => { // return self.UserWithAge.sum('age').then((sum) => { // expect(sum).to.equal(5); // }); // }); // }); // // it('should allow decimals in sum', () => { // const self = this; // return MainUserWithDec.bulkCreate([{value: 3.5}, {value: 5.25}]).then(() => { // return self.UserWithDec.sum('value').then((sum) => { // expect(sum).to.equal(8.75); // }); // }); // }); // // it('should accept a where clause', () => { // const options = {where: {'gender': 'male'}}; // // const self = this; // return self.UserWithAge.bulkCreate([{age: 2, gender: 'male'}, {age: 3, gender: 'female'}]).then(() => { // return self.UserWithAge.sum('age', options).then((sum) => { // expect(sum).to.equal(2); // }); // }); // }); // // it('should accept a where clause with custom fields', () => { // return MainUserWithFields.bulkCreate([ // {age: 2, gender: 'male'}, // {age: 3, gender: 'female'} // ]).bind(this).then(() => { // return expect(MainUserWithFields.sum('age', { // where: {'gender': 'male'} // })).to.eventually.equal(2); // }); // }); // // it('allows sql logging', () => { // const logged = false; // return MainUserWithAge.sum('age', { // logging: (sql) => { // expect(sql).to.exist; // logged = true; // expect(sql.toUpperCase().indexOf('SELECT')).to.be.above(-1); // } // }).then(() => { // expect(logged).to.true; // }); // }); // }); // // describe('schematic support', () => { // beforeEach(() => { // const self = this; // // MainUserPublic = this.sequelize.define('UserPublic', { // age: Sequelize.INTEGER // }); // // MainUserSpecial = this.sequelize.define('UserSpecial', { // age: Sequelize.INTEGER // }); // // return self.sequelize.dropAllSchemas().then(() => { // return self.sequelize.createSchema('schema_test').then(() => { // return self.sequelize.createSchema('special').then(() => { // return self.UserSpecial.schema('special').sync({force: true}).then((UserSpecialSync) => { // self.UserSpecialSync = UserSpecialSync; // }); // }); // }); // }); // }); // // it('should be able to drop with schemas', () => { // return MainUserSpecial.drop(); // }); // // it('should be able to list schemas', () => { // return this.sequelize.showAllSchemas().then((schemas) => { // expect(schemas).to.be.instanceof(Array); // // // FIXME: reenable when schema support is properly added // if (dialect !== 'mssql') { // // sqlite & MySQL doesn't actually create schemas unless Model.sync() is called // // Postgres supports schemas natively // expect(schemas).to.have.length((dialect === 'postgres' ? 2 : 1)); // } // // }); // }); // // if (dialect === 'mysql' || dialect === 'sqlite') { // it('should take schemaDelimiter into account if applicable', () => { // const test = 0; // const UserSpecialUnderscore = this.sequelize.define('UserSpecialUnderscore', {age: Sequelize.INTEGER}, { // schema: 'hello', // schemaDelimiter: '_' // }); // const UserSpecialDblUnderscore = this.sequelize.define('UserSpecialDblUnderscore', {age: Sequelize.INTEGER}); // return UserSpecialUnderscore.sync({force: true}).then((User) => { // return UserSpecialDblUnderscore.schema('hello', '__').sync({force: true}).then((DblUser) => { // return DblUser.create({age: 3}, { // logging: (sql) => { // expect(sql).to.exist; // test++; // expect(sql.indexOf('INSERT INTO `hello__UserSpecialDblUnderscores`')).to.be.above(-1); // } // }).then(() => { // return User.create({age: 3}, { // logging: (sql) => { // expect(sql).to.exist; // test++; // expect(sql.indexOf('INSERT INTO `hello_UserSpecialUnderscores`')).to.be.above(-1); // } // }); // }); // }).then(() => { // expect(test).to.equal(2); // }); // }); // }); // } // // it('should describeTable using the default schema settings', () => { // const self = this // , UserPublic = this.sequelize.define('Public', { // username: Sequelize.STRING // }) // , count = 0; // // return UserPublic.sync({force: true}).then(() => { // return UserPublic.schema('special').sync({force: true}).then(() => { // return self.sequelize.queryInterface.describeTable('Publics', { // logging: (sql) => { // if (dialect === 'sqlite' || dialect === 'mysql' || dialect === 'mssql') { // expect(sql).to.not.contain('special'); // count++; // } // } // }).then((table) => { // if (dialect === 'postgres') { // expect(table.id.defaultValue).to.not.contain('special'); // count++; // } // return self.sequelize.queryInterface.describeTable('Publics', { // schema: 'special', // logging: (sql) => { // if (dialect === 'sqlite' || dialect === 'mysql' || dialect === 'mssql') { // expect(sql).to.contain('special'); // count++; // } // } // }).then((table) => { // if (dialect === 'postgres') { // expect(table.id.defaultValue).to.contain('special'); // count++; // } // }); // }).then(() => { // expect(count).to.equal(2); // }); // }); // }); // }); // // it('should be able to reference a table with a schema set', () => { // const self = this; // // const UserPub = this.sequelize.define('UserPub', { // username: Sequelize.STRING // }, {schema: 'prefix'}); // // const ItemPub = this.sequelize.define('ItemPub', { // name: Sequelize.STRING // }, {schema: 'prefix'}); // // UserPub.hasMany(ItemPub, { // foreignKeyConstraint: true // }); // // const run = () => { // return UserPub.sync({force: true}).then(() => { // return ItemPub.sync({ // force: true, logging: _.after(2, _.once((sql) => { // if (dialect === 'postgres') { // expect(sql).to.match(/REFERENCES\s+"prefix"\."UserPubs" \("id"\)/); // } else if (dialect === 'mssql') { // expect(sql).to.match(/REFERENCES\s+\[prefix\]\.\[UserPubs\] \(\[id\]\)/); // } else { // expect(sql).to.match(/REFERENCES\s+`prefix\.UserPubs` \(`id`\)/); // } // // })) // }); // }); // }; // // if (dialect === 'postgres') { // return this.sequelize.queryInterface.dropAllSchemas().then(() => { // return self.sequelize.queryInterface.createSchema('prefix').then(() => { // return run.call(self); // }); // }); // } else { // return run.call(self); // } // }); // // it('should be able to create and update records under any valid schematic', () => { // const self = this; // const logged = 0; // return self.UserPublic.sync({force: true}).then((UserPublicSync) => { // return UserPublicSync.create({age: 3}, { // logging: (UserPublic) => { // logged++; // if (dialect === 'postgres') { // expect(self.UserSpecialSync.getTableName().toString()).to.equal('"special"."UserSpecials"'); // expect(UserPublic.indexOf('INSERT INTO "UserPublics"')).to.be.above(-1); // } else if (dialect === 'sqlite') { // expect(self.UserSpecialSync.getTableName().toString()).to.equal('`special.UserSpecials`'); // expect(UserPublic.indexOf('INSERT INTO `UserPublics`')).to.be.above(-1); // } else if (dialect === 'mssql') { // expect(self.UserSpecialSync.getTableName().toString()).to.equal('[special].[UserSpecials]'); // expect(UserPublic.indexOf('INSERT INTO [UserPublics]')).to.be.above(-1); // } else { // expect(self.UserSpecialSync.getTableName().toString()).to.equal('`special.UserSpecials`'); // expect(UserPublic.indexOf('INSERT INTO `UserPublics`')).to.be.above(-1); // } // } // }).then((UserPublic) => { // return self.UserSpecialSync.schema('special').create({age: 3}, { // logging: (UserSpecial) => { // logged++; // if (dialect === 'postgres') { // expect(UserSpecial.indexOf('INSERT INTO "special"."UserSpecials"')).to.be.above(-1); // } else if (dialect === 'sqlite') { // expect(UserSpecial.indexOf('INSERT INTO `special.UserSpecials`')).to.be.above(-1); // } else if (dialect === 'mssql') { // expect(UserSpecial.indexOf('INSERT INTO [special].[UserSpecials]')).to.be.above(-1); // } else { // expect(UserSpecial.indexOf('INSERT INTO `special.UserSpecials`')).to.be.above(-1); // } // } // }).then((UserSpecial) => { // return UserSpecial.updateAttributes({age: 5}, { // logging: (user) => { // logged++; // if (dialect === 'postgres') { // expect(user.indexOf('UPDATE "special"."UserSpecials"')).to.be.above(-1); // } else if (dialect === 'mssql') { // expect(user.indexOf('UPDATE [special].[UserSpecials]')).to.be.above(-1); // } else { // expect(user.indexOf('UPDATE `special.UserSpecials`')).to.be.above(-1); // } // } // }); // }); // }).then(() => { // expect(logged).to.equal(3); // }); // }); // }); // }); // // describe('references', () => { // beforeEach(() => { // const self = this; // // this.Author = this.sequelize.define('author', {firstName: Sequelize.STRING}); // // return this.sequelize.getQueryInterface().dropTable('posts', {force: true}).then(() => { // return self.sequelize.getQueryInterface().dropTable('authors', {force: true}); // }).then(() => { // return self.Author.sync(); // }); // }); // // it('uses an existing dao factory and references the author table', () => { // const authorIdColumn = {type: Sequelize.INTEGER, references: {model: this.Author, key: 'id'}}; // // const Post = this.sequelize.define('post', { // title: Sequelize.STRING, // authorId: authorIdColumn // }); // // this.Author.hasMany(Post); // Post.belongsTo(this.Author); // // // The posts table gets dropped in the before filter. // return Post.sync({ // logging: _.once((sql) => { // if (dialect === 'postgres') { // expect(sql).to.match(/"authorId" INTEGER REFERENCES "authors" \("id"\)/); // } else if (dialect === 'mysql') { // expect(sql).to.match(/FOREIGN KEY \(`authorId`\) REFERENCES `authors` \(`id`\)/); // } else if (dialect === 'mssql') { // expect(sql).to.match(/FOREIGN KEY \(\[authorId\]\) REFERENCES \[authors\] \(\[id\]\)/); // } else if (dialect === 'sqlite') { // expect(sql).to.match(/`authorId` INTEGER REFERENCES `authors` \(`id`\)/); // } else { // throw new Error('Undefined dialect!'); // } // }) // }); // }); // // it('uses a table name as a string and references the author table', () => { // const authorIdColumn = {type: Sequelize.INTEGER, references: {model: 'authors', key: 'id'}}; // // const self = this // , Post = self.sequelize.define('post', {title: Sequelize.STRING, authorId: authorIdColumn}); // // this.Author.hasMany(Post); // Post.belongsTo(this.Author); // // // The posts table gets dropped in the before filter. // return Post.sync({ // logging: _.once((sql) => { // if (dialect === 'postgres') { // expect(sql).to.match(/"authorId" INTEGER REFERENCES "authors" \("id"\)/); // } else if (dialect === 'mysql') { // expect(sql).to.match(/FOREIGN KEY \(`authorId`\) REFERENCES `authors` \(`id`\)/); // } else if (dialect === 'sqlite') { // expect(sql).to.match(/`authorId` INTEGER REFERENCES `authors` \(`id`\)/); // } else if (dialect === 'mssql') { // expect(sql).to.match(/FOREIGN KEY \(\[authorId\]\) REFERENCES \[authors\] \(\[id\]\)/); // } else { // throw new Error('Undefined dialect!'); // } // }) // }); // }); // // it('emits an error event as the referenced table name is invalid', () => { // const authorIdColumn = {type: Sequelize.INTEGER, references: {model: '4uth0r5', key: 'id'}}; // // const Post = this.sequelize.define('post', {title: Sequelize.STRING, authorId: authorIdColumn}); // // this.Author.hasMany(Post); // Post.belongsTo(this.Author); // // // The posts table gets dropped in the before filter. // return Post.sync().then(() => { // if (dialect === 'sqlite') { // // sorry ... but sqlite is too stupid to understand whats going on ... // expect(1).to.equal(1); // } else { // // the parser should not end up here ... // expect(2).to.equal(1); // } // // return; // }).catch((err) => { // if (dialect === 'mysql') { // // MySQL 5.7 or above doesn't support POINT EMPTY // if (dialect === 'mysql' && semver.gte(current.options.databaseVersion, '5.6.0')) { // expect(err.message).to.match(/Cannot add foreign key constraint/); // } else { // expect(err.message).to.match(/Can\'t create table/); // } // } else if (dialect === 'sqlite') { // // the parser should not end up here ... see above // expect(1).to.equal(2); // } else if (dialect === 'postgres') { // expect(err.message).to.match(/relation "4uth0r5" does not exist/); // } else if (dialect === 'mssql') { // expect(err.message).to.match(/Could not create constraint/); // } else { // throw new Error('Undefined dialect!'); // } // }); // }); // // it('works with comments', () => { // // Test for a case where the comment was being moved to the end of the table when there was also a reference on the column, see #1521 // // jshint ignore:start // const Member = this.sequelize.define('Member', {}); // const idColumn = { // type: Sequelize.INTEGER, // primaryKey: true, // autoIncrement: false, // comment: 'asdf' // }; // // idColumn.references = {model: Member, key: 'id'}; // // const Profile = this.sequelize.define('Profile', {id: idColumn}); // // jshint ignore:end // // return this.sequelize.sync({force: true}); // }); // }); // // describe('blob', () => { // beforeEach(() => { // this.BlobUser = this.sequelize.define('blobUser', { // data: Sequelize.BLOB // }); // // return this.BlobUser.sync({force: true}); // }); // // describe('buffers', () => { // it('should be able to take a buffer as parameter to a BLOB field', () => { // return this.BlobUser.create({ // data: new Buffer('Sequelize') // }).then((user) => { // expect(user).to.be.ok; // }); // }); // // it('should return a buffer when fetching a blob', () => { // const self = this; // return this.BlobUser.create({ // data: new Buffer('Sequelize') // }).then((user) => { // return self.BlobUser.findById(user.id).then((user) => { // expect(user.data).to.be.an.instanceOf(Buffer); // expect(user.data.toString()).to.have.string('Sequelize'); // }); // }); // }); // // it('should work when the database returns null', () => { // const self = this; // return this.BlobUser.create({ // // create a null column // }).then((user) => { // return self.BlobUser.findById(user.id).then((user) => { // expect(user.data).to.be.null; // }); // }); // }); // }); // // if (dialect !== 'mssql') { // // NOTE: someone remember to inform me about the intent of these tests. Are // // you saying that data passed in as a string is automatically converted // // to binary? i.e. "Sequelize" is CAST as binary, OR that actual binary // // data is passed in, in string form? Very unclear, and very different. // // describe('strings', () => { // it('should be able to take a string as parameter to a BLOB field', () => { // return this.BlobUser.create({ // data: 'Sequelize' // }).then((user) => { // expect(user).to.be.ok; // }); // }); // // it('should return a buffer when fetching a BLOB, even when the BLOB was inserted as a string', () => { // const self = this; // return this.BlobUser.create({ // data: 'Sequelize' // }).then((user) => { // return self.BlobUser.findById(user.id).then((user) => { // expect(user.data).to.be.an.instanceOf(Buffer); // expect(user.data.toString()).to.have.string('Sequelize'); // }); // }); // }); // }); // } // // }); // // describe('paranoid is true and where is an array', () => { // // beforeEach(() => { // MainUser = this.sequelize.define('User', {username: DataTypes.STRING}, {paranoid: true}); // this.Project = this.sequelize.define('Project', {title: DataTypes.STRING}, {paranoid: true}); // // this.Project.belongsToMany(MainUser, {through: 'project_user'}); // MainUser.belongsToMany(this.Project, {through: 'project_user'}); // // const self = this; // return this.sequelize.sync({force: true}).then(() => { // return self.User.bulkCreate([{ // username: 'leia' // }, { // username: 'luke' // }, { // username: 'vader' // }]).then(() => { // return self.Project.bulkCreate([{ // title: 'republic' // }, { // title: 'empire' // }]).then(() => { // return self.User.findAll().then((users) => { // return self.Project.findAll().then((projects) => { // const leia = users[0] // , luke = users[1] // , vader = users[2] // , republic = projects[0] // , empire = projects[1]; // return leia.setProjects([republic]).then(() => { // return luke.setProjects([republic]).then(() => { // return vader.setProjects([empire]).then(() => { // return leia.destroy(); // }); // }); // }); // }); // }); // }); // }); // }); // }); // // it('should not fail when array contains Sequelize.or / and', () => { // return MainUser.findAll({ // where: [ // this.sequelize.or({username: 'vader'}, {username: 'luke'}), // this.sequelize.and({id: [1, 2, 3]}) // ] // }) // .then((res) => { // expect(res).to.have.length(2); // }); // }); // // it('should not fail with an include', () => { // return MainUser.findAll({ // where: [ // this.sequelize.queryInterface.QueryGenerator.quoteIdentifiers('Projects.title') + ' = ' + this.sequelize.queryInterface.QueryGenerator.escape('republic') // ], // include: [ // {model: this.Project} // ] // }).then((users) => { // expect(users.length).to.be.equal(1); // expect(users[0].username).to.be.equal('luke'); // }); // }); // // it('should not overwrite a specified deletedAt by setting paranoid: false', () => { // const tableName = ''; // if (MainUser.name) { // tableName = this.sequelize.queryInterface.QueryGenerator.quoteIdentifier(MainUser.name) + '.'; // } // return MainUser.findAll({ // paranoid: false, // where: [ // tableName + this.sequelize.queryInterface.QueryGenerator.quoteIdentifier('deletedAt') + ' IS NOT NULL ' // ], // include: [ // {model: this.Project} // ] // }).then((users) => { // expect(users.length).to.be.equal(1); // expect(users[0].username).to.be.equal('leia'); // }); // }); // // it('should not overwrite a specified deletedAt (complex query) by setting paranoid: false', () => { // return MainUser.findAll({ // paranoid: false, // where: [ // this.sequelize.or({username: 'leia'}, {username: 'luke'}), // this.sequelize.and( // {id: [1, 2, 3]}, // this.sequelize.or({deletedAt: null}, {deletedAt: {gt: new Date(0)}}) // ) // ] // }) // .then((res) => { // expect(res).to.have.length(2); // }); // }); // // }); // // if (dialect !== 'sqlite' && current.dialect.supports.transactions) { // it('supports multiple async transactions', () => { // this.timeout(90000); // const self = this; // return Support.prepareTransactionTest(this.sequelize).bind({}).then((sequelize) => { // const User = sequelize.define('User', {username: Sequelize.STRING}); // const testAsync = () => { // return sequelize.transaction().then((t) => { // return User.create({ // username: 'foo' // }, { // transaction: t // }).then(() => { // return User.findAll({ // where: { // username: 'foo' // } // }).then((users) => { // expect(users).to.have.length(0); // }); // }).then(() => { // return User.findAll({ // where: { // username: 'foo' // }, // transaction: t // }).then((users) => { // expect(users).to.have.length(1); // }); // }).then(() => { // return t; // }); // }).then((t) => { // return t.rollback(); // }); // }; // return User.sync({force: true}).then(() => { // const tasks = []; // for (const i = 0; i < 1000; i++) { // tasks.push(testAsync.bind(this)); // } // return self.sequelize.Promise.resolve(tasks).map((entry) => { // return entry(); // }, { // // Needs to be one less than ??? else the non transaction query won't ever get a connection // concurrency: (sequelize.config.pool && sequelize.config.pool.max || 5) - 1 // }); // }); // }); // }); // } // // describe('Unique', () => { // it('should set unique when unique is true', () => { // const self = this; // const uniqueTrue = self.sequelize.define('uniqueTrue', { // str: {type: Sequelize.STRING, unique: true} // }); // // return uniqueTrue.sync({ // force: true, logging: _.after(2, _.once((s) => { // expect(s).to.match(/UNIQUE/); // })) // }); // }); // // it('should not set unique when unique is false', () => { // const self = this; // const uniqueFalse = self.sequelize.define('uniqueFalse', { // str: {type: Sequelize.STRING, unique: false} // }); // // return uniqueFalse.sync({ // force: true, logging: _.after(2, _.once((s) => { // expect(s).not.to.match(/UNIQUE/); // })) // }); // }); // // it('should not set unique when unique is unset', () => { // const self = this; // const uniqueUnset = self.sequelize.define('uniqueUnset', { // str: {type: Sequelize.STRING} // }); // // return uniqueUnset.sync({ // force: true, logging: _.after(2, _.once((s) => { // expect(s).not.to.match(/UNIQUE/); // })) // }); // }); // }); // // it('should be possible to use a key named UUID as foreign key', () => { // // jshint ignore:start // const project = this.sequelize.define('project', { // UserId: { // type: Sequelize.STRING, // references: { // model: 'Users', // key: 'UUID' // } // } // }); // // const user = this.sequelize.define('Users', { // UUID: { // type: Sequelize.STRING, // primaryKey: true, // unique: true, // allowNull: false, // validate: { // notNull: true, // notEmpty: true // } // } // }); // // jshint ignore:end // // return this.sequelize.sync({force: true}); // }); // // describe('bulkCreate errors', () => { // it('should return array of errors if validate and individualHooks are true', () => { // const data = [{username: null}, // {username: null}, // {username: null}]; // // const user = this.sequelize.define('Users', { // username: { // type: Sequelize.STRING, // allowNull: false, // validate: { // notNull: true, // notEmpty: true // } // } // }); // // return expect(user.bulkCreate(data, { // validate: true, // individualHooks: true // })).to.be.rejectedWith(Promise.AggregateError); // }); // }); });
the_stack
import { Machine, assign } from 'xstate' // This is the root machine, composing all the other machines and is the brain of the bottom sheet interface OverlayStateSchema { states: { // the overlay usually starts in the closed position closed: {} opening: { states: { // Used to fire off the springStart event start: {} // Decide how to transition to the open state based on what the initialState is transition: {} // Fast enter animation, sheet is open by default immediately: { states: { open: {} activating: {} } } smoothly: { states: { // This state only happens when the overlay should start in an open state, instead of animating from the bottom // openImmediately: {} // visuallyHidden will render the overlay in the open state, but with opacity 0 // doing this solves two problems: // on Android focusing an input element will trigger the softkeyboard to show up, which will change the viewport height // on iOS the focus event will break the view by triggering a scrollIntoView event if focus happens while the overlay is below the viewport and body got overflow:hidden // by rendering things with opacity 0 we ensure keyboards and scrollIntoView all happen in a way that match up with what the sheet will look like. // we can then move it to the opening position below the viewport, and animate it into view without worrying about height changes or scrolling overflow:hidden events visuallyHidden: {} // In this state we're activating focus traps, scroll locks and more, this will sometimes trigger soft keyboards and scrollIntoView // @TODO we might want to add a delay here before proceeding to open, to give android and iOS enough time to adjust the viewport when focusing an interactive element activating: {} // Animates from the bottom open: {} } } // Used to fire off the springEnd event end: {} // And finally we're ready to transition to open done: {} } } open: {} // dragging responds to user gestures, which may interrupt the opening state, closing state or snapping // when interrupting an opening event, it fires onSpringEnd(OPEN) before onSpringStart(DRAG) // when interrupting a closing event, it fires onSpringCancel(CLOSE) before onSpringStart(DRAG) // when interrupting a dragging event, it fires onSpringCancel(SNAP) before onSpringStart(DRAG) dragging: {} // snapping happens whenever transitioning to a new snap point, often after dragging snapping: { states: { start: {} snappingSmoothly: {} end: {} done: {} } } resizing: { states: { start: {} resizingSmoothly: {} end: {} done: {} } } closing: { states: { start: {} deactivating: {} closingSmoothly: {} end: {} done: {} } } } } type OverlayEvent = | { type: 'OPEN' } | { type: 'SNAP' payload: { y: number velocity: number source: 'dragging' | 'custom' | string } } | { type: 'CLOSE' } | { type: 'DRAG' } | { type: 'RESIZE' } // The context (extended state) of the machine interface OverlayContext { initialState: 'OPEN' | 'CLOSED' } function sleep(ms = 1000) { return new Promise((resolve) => setTimeout(resolve, ms)) } const cancelOpen = { CLOSE: { target: '#overlay.closing', actions: 'onOpenCancel' }, } const openToDrag = { DRAG: { target: '#overlay.dragging', actions: 'onOpenEnd' }, } const openToResize = { RESIZE: { target: '#overlay.resizing', actions: 'onOpenEnd' }, } const initiallyOpen = ({ initialState }) => initialState === 'OPEN' const initiallyClosed = ({ initialState }) => initialState === 'CLOSED' // Copy paste the machine into https://xstate.js.org/viz/ to make sense of what's going on in here ;) export const overlayMachine = Machine< OverlayContext, OverlayStateSchema, OverlayEvent >( { id: 'overlay', initial: 'closed', context: { initialState: 'CLOSED' }, states: { closed: { on: { OPEN: 'opening', CLOSE: undefined } }, opening: { initial: 'start', states: { start: { invoke: { src: 'onOpenStart', onDone: 'transition', }, }, transition: { always: [ { target: 'immediately', cond: 'initiallyOpen' }, { target: 'smoothly', cond: 'initiallyClosed' }, ], }, immediately: { initial: 'open', states: { open: { invoke: { src: 'openImmediately', onDone: 'activating' }, }, activating: { invoke: { src: 'activate', onDone: '#overlay.opening.end' }, on: { ...openToDrag, ...openToResize }, }, }, }, smoothly: { initial: 'visuallyHidden', states: { visuallyHidden: { invoke: { src: 'renderVisuallyHidden', onDone: 'activating' }, }, activating: { invoke: { src: 'activate', onDone: 'open' }, }, open: { invoke: { src: 'openSmoothly', onDone: '#overlay.opening.end' }, on: { ...openToDrag, ...openToResize }, }, }, }, end: { invoke: { src: 'onOpenEnd', onDone: 'done' }, on: { CLOSE: '#overlay.closing', DRAG: '#overlay.dragging' }, }, done: { type: 'final', }, }, on: { ...cancelOpen }, onDone: 'open', }, open: { on: { DRAG: '#overlay.dragging', SNAP: 'snapping', RESIZE: 'resizing' }, }, dragging: { on: { SNAP: 'snapping' }, }, snapping: { initial: 'start', states: { start: { invoke: { src: 'onSnapStart', onDone: 'snappingSmoothly', }, entry: [ assign({ // @ts-expect-error y: (_, { payload: { y } }) => y, velocity: (_, { payload: { velocity } }) => velocity, snapSource: (_, { payload: { source = 'custom' } }) => source, }), ], }, snappingSmoothly: { invoke: { src: 'snapSmoothly', onDone: 'end' }, }, end: { invoke: { src: 'onSnapEnd', onDone: 'done' }, on: { RESIZE: '#overlay.resizing', SNAP: '#overlay.snapping', CLOSE: '#overlay.closing', DRAG: '#overlay.dragging', }, }, done: { type: 'final' }, }, on: { SNAP: { target: 'snapping', actions: 'onSnapEnd' }, RESIZE: { target: '#overlay.resizing', actions: 'onSnapCancel' }, DRAG: { target: '#overlay.dragging', actions: 'onSnapCancel' }, CLOSE: { target: '#overlay.closing', actions: 'onSnapCancel' }, }, onDone: 'open', }, resizing: { initial: 'start', states: { start: { invoke: { src: 'onResizeStart', onDone: 'resizingSmoothly', }, }, resizingSmoothly: { invoke: { src: 'resizeSmoothly', onDone: 'end' }, }, end: { invoke: { src: 'onResizeEnd', onDone: 'done' }, on: { SNAP: '#overlay.snapping', CLOSE: '#overlay.closing', DRAG: '#overlay.dragging', }, }, done: { type: 'final' }, }, on: { RESIZE: { target: 'resizing', actions: 'onResizeEnd' }, SNAP: { target: 'snapping', actions: 'onResizeCancel' }, DRAG: { target: '#overlay.dragging', actions: 'onResizeCancel' }, CLOSE: { target: '#overlay.closing', actions: 'onResizeCancel' }, }, onDone: 'open', }, closing: { initial: 'start', states: { start: { invoke: { src: 'onCloseStart', onDone: 'deactivating', }, on: { OPEN: { target: '#overlay.open', actions: 'onCloseCancel' } }, }, deactivating: { invoke: { src: 'deactivate', onDone: 'closingSmoothly' }, }, closingSmoothly: { invoke: { src: 'closeSmoothly', onDone: 'end' }, }, end: { invoke: { src: 'onCloseEnd', onDone: 'done' }, on: { OPEN: { target: '#overlay.opening', actions: 'onCloseCancel' }, }, }, done: { type: 'final' }, }, on: { CLOSE: undefined, OPEN: { target: '#overlay.opening', actions: 'onCloseCancel' }, }, onDone: 'closed', }, }, on: { CLOSE: 'closing', }, }, { actions: { onOpenCancel: (context, event) => { console.log('onOpenCancel', { context, event }) }, onSnapCancel: (context, event) => { console.log('onSnapCancel', { context, event }) }, onResizeCancel: (context, event) => { console.log('onResizeCancel', { context, event }) }, onCloseCancel: (context, event) => { console.log('onCloseCancel', { context, event }) }, onOpenEnd: (context, event) => { console.log('onOpenCancel', { context, event }) }, onSnapEnd: (context, event) => { console.log('onSnapEnd', { context, event }) }, onRezizeEnd: (context, event) => { console.log('onRezizeEnd', { context, event }) }, }, services: { onSnapStart: async () => { await sleep() }, onOpenStart: async () => { await sleep() }, onCloseStart: async () => { await sleep() }, onResizeStart: async () => { await sleep() }, onSnapEnd: async () => { await sleep() }, onOpenEnd: async () => { await sleep() }, onCloseEnd: async () => { await sleep() }, onResizeEnd: async () => { await sleep() }, renderVisuallyHidden: async (context, event) => { console.group('renderVisuallyHidden') console.log({ context, event }) await sleep() console.groupEnd() }, activate: async (context, event) => { console.group('activate') console.log({ context, event }) await sleep() console.groupEnd() }, deactivate: async (context, event) => { console.group('deactivate') console.log({ context, event }) await sleep() console.groupEnd() }, openSmoothly: async (context, event) => { console.group('openSmoothly') console.log({ context, event }) await sleep() console.groupEnd() }, openImmediately: async (context, event) => { console.group('openImmediately') console.log({ context, event }) await sleep() console.groupEnd() }, snapSmoothly: async (context, event) => { console.group('snapSmoothly') console.log({ context, event }) await sleep() console.groupEnd() }, resizeSmoothly: async (context, event) => { console.group('resizeSmoothly') console.log({ context, event }) await sleep() console.groupEnd() }, closeSmoothly: async (context, event) => { console.group('closeSmoothly') console.log({ context, event }) await sleep() console.groupEnd() }, }, guards: { initiallyClosed, initiallyOpen }, } )
the_stack
* Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { Clause } from './clause'; import { MemoryInterface } from '../memory'; import { RelationshipType } from './relationshipType'; import { TriggerTree } from './triggerTree'; import { Trigger } from './trigger'; enum Operation { none = 'none', found = 'found', added = 'added', removed = 'removed', inserted = 'inserted', } /** * Node in a trigger tree. */ export class Node { private _allTriggers: Trigger[] = []; private _triggers: Trigger[] = []; private _specializations: Node[] = []; /** * Intializes a new instance of the `Node` class. * @param clause The logical conjunction this node represents. * @param tree The trigger tree this node is found in. * @param trigger The trigger to initialize this node. */ public constructor(clause: Clause, tree: TriggerTree, trigger?: Trigger) { this.clause = new Clause(clause); this.tree = tree; if (trigger) { this._allTriggers.push(trigger); this._triggers.push(trigger); } } /** * Gets all of the most specific triggers that contains the `Clause` in this node. */ public get triggers(): Trigger[] { return this._triggers; } /** * Gets all triggers that contain the `Clause` in this node. */ public get allTriggers(): Trigger[] { return this._allTriggers; } /** * Gets specialized children of this node. */ public get specializations(): Node[] { return this._specializations; } /** * Gets the logical conjunction this node represents. */ public clause: Clause; /** * Gets the tree this node is found in. */ public tree: TriggerTree; /** * Gets a string that represents the current node. * @param builder An array of string to build the string of node. * @param indent An integer representing the number of spaces at the start of a line. */ public toString(builder: string[] = [], indent = 0): string { return this.clause.toString(builder, indent); } /** * Identify the relationship between two nodes. * @param other Node to compare against. * @returns Relationship between this node an the other. */ public relationship(other: Node): RelationshipType { return this.clause.relationship(other.clause, this.tree.comparers); } /** * Gets the most specific matches below this node. * @param state Frame to evaluate against. * @returns List of the most specific matches found. */ public matches(state: MemoryInterface | any): Trigger[] { const matches = new Set<Trigger>(); this._matches(state, matches, new Map<Node, boolean>()); return Array.from(matches); } /** * Adds a child node. * @param triggerNode The node to be added. * @returns Whether adding node operation is successful. */ public addNode(triggerNode: Node): boolean { return this._addNode(triggerNode, new Map<Node, Operation>()) === Operation.added; } /** * Removes a trigger from node. * @param trigger The trigger to be removed. * @returns Whether removing trigger operation is successful. */ public removeTrigger(trigger: Trigger): boolean { return this._removeTrigger(trigger, new Set<Node>()); } private _addNode(triggerNode: Node, ops: Map<Node, Operation>): Operation { if (ops.has(this)) { return Operation.none; } let op = Operation.none; const trigger = triggerNode.triggers[0]; const relationship = this.relationship(triggerNode); switch (relationship) { case RelationshipType.equal: // Ensure action is not already there const found = this._allTriggers.find( (existing) => trigger.action != undefined && trigger.action === existing.action ) !== undefined; op = Operation.found; if (!found) { this._allTriggers.push(trigger); let add = true; for (let i = 0; i < this._triggers.length; ) { const existing = this._triggers[i]; const reln = trigger.relationship(existing, this.tree.comparers); if (reln === RelationshipType.generalizes) { add = false; break; } else if (reln === RelationshipType.specializes) { this._triggers.splice(i, 1); } else { ++i; } } if (add) { this._triggers.push(trigger); } op = Operation.added; } break; case RelationshipType.incomparable: for (const child of this._specializations) { child._addNode(triggerNode, ops); } break; case RelationshipType.specializes: triggerNode._addSpecialization(this); op = Operation.inserted; break; case RelationshipType.generalizes: let foundOne = false; let removals: Node[]; for (let i = 0; i < this._specializations.length; i++) { const child = this._specializations[i]; const childOp = child._addNode(triggerNode, ops); if (childOp != Operation.none) { foundOne = true; if (childOp === Operation.inserted) { if (!removals) { removals = []; } removals.push(child); op = Operation.added; } else { op = childOp; } } } if (removals) { for (const removal of removals) { const removed = this._specializations.findIndex((item) => item === removal); if (removed >= 0) { this._specializations.splice(removed, 1); } } this._specializations.push(triggerNode); } if (!foundOne) { this._specializations.push(triggerNode); op = Operation.added; } break; } // Prevent visiting this node again ops.set(this, op); return op; } private _matches(state: MemoryInterface | any, matches: Set<Trigger>, matched: Map<Node, boolean>): boolean { let found = matched.get(this); if (found) { return true; } found = false; for (const child of this._specializations) { if (child._matches(state, matches, matched)) { found = true; } } // No child matched so we might if (!found) { const { value: match, error } = this.clause.tryEvaluate(state); if (!error && match) { for (const trigger of this.triggers) { if (trigger.matches(this.clause, state)) { matches.add(trigger); found = true; } } } } matched.set(this, found); return found; } private _removeTrigger(trigger: Trigger, visited: Set<Node>): boolean { if (visited.has(this)) { return false; } visited.add(this); let removed = false; // Remove from allTriggers and triggers const allTriggerIndex = this._allTriggers.findIndex((item) => item === trigger); if (allTriggerIndex >= 0) { // We found the trigger somewhere in the tree this._allTriggers.splice(allTriggerIndex, 1); removed = true; const triggerIndex = this._triggers.findIndex((item) => item === trigger); if (triggerIndex >= 0) { this._triggers.splice(triggerIndex, 1); for (const candidate of this._allTriggers) { let add = true; for (const existing of this._triggers) { const reln = candidate.relationship(existing, this.tree.comparers); if (reln === RelationshipType.equal || reln === RelationshipType.generalizes) { add = false; break; } } if (add) { this._triggers.push(candidate); } } } } // Remove from any children let removals: Node[]; for (let i = 0; i < this._specializations.length; i++) { const child = this._specializations[i]; const childRemoved = child._removeTrigger(trigger, visited); if (childRemoved) { removed = true; } if (child.triggers.length === 0) { if (!removals) { removals = []; } removals.push(child); } } if (removals) { // Remove children if no triggers left for (const removal of removals) { const removedIndex = this._specializations.findIndex((item) => item === removal); if (removedIndex >= 0) { this._specializations.splice(removedIndex, 1); for (const specialization of removal.specializations) { let add = true; for (const parent of this._specializations) { const reln = parent.relationship(specialization); if (reln === RelationshipType.generalizes) { add = false; break; } } if (add) { this._specializations.push(specialization); } } } } } return removed; } private _addSpecialization(specialization: Node): boolean { let added = false; let removals: Node[]; let skip = false; for (let i = 0; i < this._specializations.length; i++) { const child = this._specializations[i]; const reln = specialization.relationship(child); if (reln === RelationshipType.equal) { skip = true; break; } if (reln === RelationshipType.generalizes) { if (!removals) { removals = []; } removals.push(child); } else if (reln === RelationshipType.specializes) { skip = true; break; } } if (!skip) { if (removals) { for (const removal of removals) { // Don't need to add back because specialization already has them const removed = this._specializations.findIndex((item) => item === removal); if (removed >= 0) { specialization._addSpecialization(this._specializations[removed]); this._specializations.splice(removed, 1); } } } this._specializations.push(specialization); added = true; } return added; } }
the_stack
import { Request } from 'express' import { BadRequestError, Commun, DaoFilter, EntityModel, EntityPermission, getEntityRef, getJoinProperty, getModelPropertyValue, getSchemaDefinitions, getSchemaValidator, isEntityRef, isSystemProperty, UnauthorizedError } from '..' import { EntityActionPermissions } from '../types' import { ClientError, NotFoundError } from '../errors' import { entityHooks } from '../entity/entityHooks' import { ApiEntityFilter, decodePaginationCursor, encodePaginationCursor, parseFilter, strToApiFilter } from '../utils/ApiUtils' import { ValidateFunction } from 'ajv' type RequestOptions = { findModelById?: boolean } type PageInfo = { startCursor?: string endCursor?: string hasPreviousPage?: boolean hasNextPage?: boolean } type AuthPermissions = { userId: string | null isAdmin: boolean } interface EntityListRequestedKeys { nodes?: object pageInfo?: PageInfo totalCount?: number } interface EntityListResult<T extends EntityModel> { items: T[] pageInfo: PageInfo totalCount?: number } const DEFAULT_PAGE_SIZE = 50 const MAX_PAGE_SIZE = 100 export class EntityController<T extends EntityModel> { protected createEntityValidator?: ValidateFunction protected updateEntityValidator?: ValidateFunction constructor (protected readonly entityName: string) {} protected get config () { return Commun.getEntityConfig<T>(this.entityName) } protected get dao () { return Commun.getEntityDao<T>(this.entityName) } async list (req: Request, requestedKeys?: 'all' | EntityListRequestedKeys): Promise<EntityListResult<T>> { const auth = await this.getAuthPermissions(req) if (this.config.permissions?.get !== 'own') { this.validateActionPermissions(auth, null, 'get') } const pageInfo: PageInfo = {} const sort: { [P in keyof T]?: 1 | -1 } = {} const orderBy = req.query.orderby || req.query.orderBy if (orderBy && typeof orderBy === 'string') { const [sortKey, sortDir] = orderBy.split(':') const dir = sortDir === 'asc' ? 1 : -1 if (sortKey === 'createdAt') { sort.id = dir } else { sort[sortKey as keyof T] = dir } } let filter: DaoFilter<T> = {} if (req.query.filter) { let entityFilter if (typeof req.query.filter === 'string') { entityFilter = strToApiFilter(req.query.filter, this.config.schema) } filter = parseFilter(entityFilter || req.query.filter as ApiEntityFilter, this.config.schema) as DaoFilter<T> } if (req.query.search && typeof req.query.search === 'string') { filter.$text = { $search: req.query.search } } let limit = Number(req.query.first) || DEFAULT_PAGE_SIZE if (limit > MAX_PAGE_SIZE) { limit = MAX_PAGE_SIZE } // if hasNextPage was requested, increase the limit in 1, but don't return that item const requestedHasNextPage = requestedKeys === 'all' || requestedKeys?.pageInfo?.hasNextPage if (requestedHasNextPage) { limit++ } let skip if (Number.isInteger(Number(req.query.last)) && Number(req.query.last) > 0) { skip = Number(req.query.last) } let before if (req.query.before && typeof req.query.before === 'string') { before = decodePaginationCursor<T>(req.query.before.trim()) } let after if (req.query.after && typeof req.query.after === 'string') { after = decodePaginationCursor<T>(req.query.after.trim()) } const populate = this.getPopulateFromRequest(req) const queryResult = await this.dao.findAndReturnCursor(filter, { sort, limit, skip, before, after }) const models = queryResult.items if (requestedHasNextPage && models.length === limit) { models.pop() pageInfo.hasNextPage = true } const modelPermissions = models.map(model => this.hasValidPermissions(auth, model, 'get', this.config.permissions)) const modelsWithValidPermissions = models.filter((_, i) => modelPermissions[i]) const items = await Promise.all(modelsWithValidPermissions.map(model => this.prepareModelResponse(req, auth, model, populate))) if (items.length) { pageInfo.startCursor = encodePaginationCursor(items[0], sort) pageInfo.endCursor = encodePaginationCursor(items[items.length - 1], sort) } if (requestedKeys === 'all' || requestedKeys?.pageInfo) { pageInfo.hasPreviousPage = !!skip || !!after pageInfo.hasNextPage = pageInfo.hasNextPage || false } const entityListResult: EntityListResult<T> = { items, pageInfo, } if (typeof requestedKeys === 'object' && requestedKeys.totalCount) { entityListResult.totalCount = await queryResult.cursor.count() } return entityListResult } async get (req: Request, options: RequestOptions = {}): Promise<{ item: T }> { const model = await this.findModelByApiKey(req, options) if (!model) { throw new NotFoundError() } const auth = await this.getAuthPermissions(req) this.validateActionPermissions(auth, model, 'get') await entityHooks.run(this.entityName, 'beforeGet', model, req) const item = await this.prepareModelResponse(req, auth, model, this.getPopulateFromRequest(req)) await entityHooks.run(this.entityName, 'afterGet', model, req) return { item } } async create (req: Request): Promise<{ item: T }> { const auth = await this.getAuthPermissions(req) this.validateActionPermissions(auth, null, 'create') const model = await this.getModelFromBodyRequest(req, auth, 'create') await entityHooks.run(this.entityName, 'beforeCreate', model, req) try { const insertedModel = await this.dao.insertOne(model) await entityHooks.run(this.entityName, 'afterCreate', insertedModel, req) return { item: await this.prepareModelResponse(req, auth, insertedModel, this.getPopulateFromRequest(req)) } } catch (e) { if (e.code === 11000) { throw new ClientError('Duplicated key', 400) } throw e } } async update (req: Request, options: RequestOptions = {}): Promise<{ item: T }> { const model = await this.findModelByApiKey(req, options) if (!model) { throw new NotFoundError() } const auth = await this.getAuthPermissions(req) this.validateActionPermissions(auth, model, 'update') await entityHooks.run(this.entityName, 'beforeUpdate', model, req) const modelData = await this.getModelFromBodyRequest(req, auth, 'update', model) try { const updatedItem = await this.dao.updateOne(model.id!, modelData) await entityHooks.run(this.entityName, 'afterUpdate', updatedItem, req) return { item: await this.prepareModelResponse(req, auth, updatedItem, this.getPopulateFromRequest(req)) } } catch (e) { if (e.code === 11000) { throw new ClientError('Duplicated key', 400) } throw e } } async delete (req: Request, options: RequestOptions = {}): Promise<{ result: boolean }> { const model = await this.findModelByApiKey(req, options) if (!model) { return { result: true } } const auth = await this.getAuthPermissions(req) this.validateActionPermissions(auth, model, 'delete') await entityHooks.run(this.entityName, 'beforeDelete', model, req) const result = await this.dao.deleteOne(model.id!) await entityHooks.run(this.entityName, 'afterDelete', model, req) return { result } } protected findModelByApiKey (req: Request, options: RequestOptions) { if (options.findModelById || !this.config.apiKey || this.config.apiKey === 'id') { return this.dao.findOneById(req.params.id) } const attrKey = this.config.apiKey const property = this.config.schema?.properties?.[attrKey] let value: string | number | boolean if (typeof property === 'boolean' || property?.type === 'boolean') { value = Boolean(req.params.id) } else if (property?.type === 'number') { value = Number(req.params.id) } else { value = req.params.id } return this.dao.findOne({ [attrKey]: value } as DaoFilter<T>) } protected async getModelFromBodyRequest (req: Request, auth: AuthPermissions, action: 'create' | 'update', persistedModel?: T): Promise<T> { const model: T = {} as T const definitions = getSchemaDefinitions() this.config.schema.definitions = { ...definitions, ...(this.config.schema.definitions || {}), } let validationResult let validator: ValidateFunction if (action === 'create') { validator = this.getCreateEntityValidator() validationResult = validator(req.body) } else { validator = this.getUpdateEntityValidator() validationResult = validator(req.body) } if (!validationResult) { const errorMessage = (validator.errors || []) .map(error => { let errorName = error.dataPath || this.entityName if (errorName.startsWith('.')) { errorName = errorName.substr(1) } return errorName + ' ' + error.message }).join(', ') throw new BadRequestError(errorMessage ? errorMessage : 'Invalid request data') } for (const [key, property] of Object.entries(this.config.schema.properties || {})) { const permissions = { ...this.config.permissions, ...this.config.permissions?.properties?.[key], } if (typeof property === 'boolean') { continue } const validPermissions = this.hasValidPermissions(auth, persistedModel || null, action, permissions) const shouldSetValue = action === 'create' || (!property.readOnly && req.body[key] !== undefined) const settingUser = property.$ref === '#user' && action === 'create' const settingEvalProperty = property.format === 'eval' if (settingEvalProperty) { delete req.body[key] } if ((validPermissions && shouldSetValue) || settingUser || settingEvalProperty) { const value = await getModelPropertyValue({ entityName: this.entityName, property, key, data: req.body, authUserId: req.auth?.id, ignoreDefault: action === 'update', }) if (value !== undefined) { model[key as keyof T] = value } } } return model } protected getCreateEntityValidator (): ValidateFunction { if (!this.createEntityValidator) { // Remove system generated properties from required const required = this.config.schema.required || [] for (const [key, property] of Object.entries(this.config.schema.properties || {})) { if (isSystemProperty(property)) { const index = required.indexOf(key) required.splice(index, 1) } } const createSchema = { ...this.config.schema, required, } this.createEntityValidator = getSchemaValidator({ useDefaults: true, }, createSchema) } return this.createEntityValidator } protected getUpdateEntityValidator (): ValidateFunction { if (!this.updateEntityValidator) { const updateSchema = { ...this.config.schema, required: [], } this.updateEntityValidator = getSchemaValidator({ useDefaults: false, }, updateSchema) } return this.updateEntityValidator } protected async prepareModelResponse ( req: Request, auth: AuthPermissions, model: T, populate: { [P in keyof T]?: any } = {} ): Promise<T> { const item: { [key in keyof T]: any } = {} as T const properties = Object.entries(this.config.schema.properties || {}) // Prepare properties for (const [key, property] of properties) { if (typeof property === 'boolean') { continue } const permissions = { ...this.config.permissions, ...(this.config.permissions?.properties?.[key] || {}), properties: undefined, } if (this.hasValidPermissions(auth, model, 'get', permissions)) { const modelKey = key as keyof T if (modelKey === 'id' || !isEntityRef(property)) { item[modelKey] = model[modelKey] === undefined || model[modelKey] === null ? property!.default : model[modelKey] } else if (!populate[modelKey] || !model[modelKey]) { item[modelKey] = model[modelKey] ? { id: model[modelKey] } : undefined } else { const populateEntityName = getEntityRef(property)! const populatedItem = await Commun.getEntityDao(populateEntityName).findOneById('' + model[modelKey]) if (populatedItem) { item[modelKey] = await Commun.getEntityController(populateEntityName) .prepareModelResponse(req, auth, populatedItem, {}) } else { item[modelKey] = { id: model[modelKey] } } } if (item[modelKey] === undefined) { delete item[modelKey] } } } // Prepare joinProperties for (const [key, joinProperty] of Object.entries(this.config.joinProperties || {})) { if (this.hasValidPermissions(auth, model, 'get', { ...this.config.permissions, ...joinProperty.permissions } )) { const joinedProperty = await getJoinProperty(joinProperty, model, req.auth?.id) if (joinedProperty) { const joinAttrController = Commun.getEntityController(joinProperty.entity) if (Array.isArray(joinedProperty)) { item[key as keyof T] = await Promise.all(joinedProperty.map(attr => joinAttrController.prepareModelResponse(req, auth, attr))) } else { item[key as keyof T] = await joinAttrController.prepareModelResponse(req, auth, joinedProperty) } } } } return item } protected getPopulateFromRequest (req: Request) { const populate: { [P in keyof T]?: any } = {} if (req.query.populate && typeof req.query.populate === 'string') { const populateKeys = req.query.populate.split(';') for (const key of populateKeys) { populate[key as keyof T] = true } } return populate } protected validateActionPermissions (auth: AuthPermissions, model: T | null, action: keyof EntityActionPermissions) { if (!this.hasValidPermissions(auth, model, action, this.config.permissions)) { throw new UnauthorizedError() } } protected hasValidPermissions ( auth: AuthPermissions, model: T | null, action: keyof EntityActionPermissions, permissions?: EntityActionPermissions ) { if (!permissions?.[action]) { return false } const permission = permissions[action] const hasAnyoneAccess = Array.isArray(permission) ? permission.includes('anyone') : permission === 'anyone' if (hasAnyoneAccess) { return true } if (!auth.userId) { return false } const hasUserAccess = Array.isArray(permission) ? permission.includes('user') : permission === 'user' if (hasUserAccess) { return true } const hasOwnAccess = Array.isArray(permission) ? permission.includes('own') : permission === 'own' if (hasOwnAccess && model) { const userPropsEntries = Object.entries(this.config.schema.properties || {}) .find(([key, property]) => { if (typeof property === 'boolean') { return false } if (this.config.schema.$id === '#entity/user') { return key === 'id' } else { return property.$ref === '#user' } }) if (userPropsEntries?.[0]) { const userId = '' + model[userPropsEntries[0] as keyof T] if (userId && userId === auth.userId) { return true } } } const hasSystemOnlyAccess = Array.isArray(permission) ? !(permission as EntityPermission[]).find(permission => permission !== 'system') : permission === 'system' if (!hasSystemOnlyAccess) { return auth.isAdmin } return false } protected async getAuthPermissions (req: Request): Promise<AuthPermissions> { if (!req.auth?.id) { return { userId: null, isAdmin: false, } } const user = await Commun.getEntityDao<EntityModel & { admin: boolean }>('users').findOneById(req.auth.id) if (!user?.id) { return { userId: null, isAdmin: false, } } return { userId: user.id, isAdmin: user.admin, } } }
the_stack
import { Component, IComponentSettings, IComponentPrivate, DataItem, IComponentEvents, IComponentDataItem } from "../../core/render/Component"; import { List } from "../../core/util/List"; import { Color } from "../../core/util/Color"; import { percentInterpolate } from "../../core/util/Animation"; import { Percent } from "../../core/util/Percent"; import * as $array from "../../core/util/Array"; import * as $type from "../../core/util/Type"; import * as $time from "../../core/util/Time"; import type { Root } from "../../core/Root"; import { p100 } from "../../core/util/Percent"; import type { Chart } from "./Chart"; import type { Bullet } from "./Bullet"; import { Container } from "../../core/render/Container"; import type { Graphics } from "../../core/render/Graphics"; import type { ILegendDataItem } from "./Legend"; import type { Template } from "../../core/util/Template"; import type { Sprite } from "../../core/render/Sprite"; import { Label } from "../../core/render/Label"; //import { Animations } from "../../core/util/Animation"; /** * Defines interface for a heat rule. * * @see {@link https://www.amcharts.com/docs/v5/concepts/settings/heat-rules/} for more info */ export interface IHeatRule { /** * Target template. */ target: Template<any>; /** * The setting value to use for items if the lowest value. */ min: any; /** * The setting value to use for items if the highest value. */ max: any; /** * Which data field to use when determining item's value. */ dataField: string; /** * A setting key to set. */ key?: string; /** * Custom lowest value. */ minValue?: number; /** * Custom highest value. */ maxValue?: number; /** * Use logarithmic scale when calculating intermediate setting values. * * @default false */ logarithmic?: boolean; /** * A custom function that will set target element's settings. * * Can be used to do custom manipulation on complex objects requiring more * than modifying a setting. */ customFunction?: (target: Sprite, minValue: number, maxValue: number, value?: any) => void; } export interface ISeriesDataItem extends IComponentDataItem { id?: string; value?: number; /** * @ignore */ valueWorking?:number; valueChange?: number; valueChangePercent?: number; valueChangeSelection?: number; valueChangeSelectionPercent?: number; valueChangePrevious?: number; valueChangePreviousPercent?: number; /** * @ignore */ valueWorkingOpen?: number; /** * @ignore */ valueWorkingClose?: number; } export interface ISeriesSettings extends IComponentSettings { /** * Name of the series. */ name?: string; /** * A key to look up in data for an id of the data item. */ idField?: string; /** * A key to look up in data for a numeric value of the data item. * * Some series use it to display its elements. It can also be used in heat * rules. */ valueField?: string; /** * A text template to be used for label in legend. */ legendLabelText?: string; /** * A text template to be used for value label in legend. */ legendValueText?: string; /** * If set to `true` the series initial animation will be played item by item * rather than all at once. * * @see {@link https://www.amcharts.com/docs/v5/concepts/animations/#Animation_of_series} for more info */ sequencedInterpolation?:boolean; /** * A delay in milliseconds to wait before starting animation of next data * item. * * @see {@link https://www.amcharts.com/docs/v5/concepts/animations/#Animation_of_series} for more info */ sequencedDelay?:number; /** * A list of heat rules to apply on series elements. * * @see {@link https://www.amcharts.com/docs/v5/concepts/settings/heat-rules/} for more info */ heatRules?:IHeatRule[]; /** * If set to `true`, series will calculate aggregate values, e.g. change * percent, high, low, etc. * * Do not enable unless you are using such aggregate values in tooltips, * display data fields, heat rules, or similar. */ calculateAggregates?: boolean; /** * Series stroke color. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/series/#Series_colors} for more info */ stroke?: Color; /** * Series fill color. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/series/#Series_colors} for more info */ fill?: Color; /** * A data item representing series in a [[Legend]]. * * @readonly */ legendDataItem?: DataItem<ILegendDataItem>; } export interface ISeriesPrivate extends IComponentPrivate { /** * @ignore */ chart?: Chart; startIndex?: number; endIndex?: number; valueAverage?: number; valueCount?: number; valueSum?: number; valueAbsoluteSum?: number; valueLow?: number; valueHigh?: number; valueOpen?: number; valueClose?: number; } export interface ISeriesEvents extends IComponentEvents { } /** * A base class for all series. */ export abstract class Series extends Component { public static className: string = "Series"; public static classNames: Array<string> = Component.classNames.concat([Series.className]); declare public _settings: ISeriesSettings; declare public _privateSettings: ISeriesPrivate; declare public _dataItemSettings: ISeriesDataItem; declare public _events: ISeriesEvents; protected _aggregatesCalculated: boolean = false; protected _selectionAggregatesCalculated: boolean = false; protected _dataProcessed: boolean = false; protected _psi: number | undefined; protected _pei: number | undefined; /** * A chart series belongs to. */ public chart:Chart | undefined; /** * List of bullets to use for the series. * * @see {@link https://www.amcharts.com/docs/v5/concepts/common-elements/bullets/} for more info */ public bullets: List<<D extends DataItem<this["_dataItemSettings"]>>(root: Root, series:Series, dataItem: D) => Bullet | undefined> = new List(); /** * A [[Container]] series' bullets are stored in. * * @default Container.new() */ public readonly bulletsContainer: Container = Container.new(this._root, {width:p100, height:p100, position:"absolute"}); protected _afterNew() { this.valueFields.push("value"); super._afterNew(); this._disposers.push(this.bullets.events.onAll((change) => { if (change.type === "clear") { this._handleBullets(this.dataItems); } else if (change.type === "push") { this._handleBullets(this.dataItems); } else if (change.type === "setIndex") { this._handleBullets(this.dataItems); } else if (change.type === "insertIndex") { this._handleBullets(this.dataItems); } else if (change.type === "removeIndex") { this._handleBullets(this.dataItems); } else if (change.type === "moveIndex") { this._handleBullets(this.dataItems); } else { throw new Error("Unknown IListEvent type"); } })); } protected _dispose(){ this.bulletsContainer.dispose(); // can be in a different parent super._dispose(); } public startIndex():number { let len = this.dataItems.length; return Math.min(this.getPrivate("startIndex", 0), len); } public endIndex():number { let len = this.dataItems.length; return Math.min(this.getPrivate("endIndex", len), len) } protected _handleBullets(dataItems:Array<DataItem<this["_dataItemSettings"]>>){ $array.each(dataItems, (dataItem)=>{ const bullets = dataItem.bullets; if(bullets){ $array.each(bullets, (bullet)=>{ bullet.dispose(); }) dataItem.bullets = undefined; } }) this.markDirtyValues(); } /** * Looks up and returns a data item by its ID. * * @param id ID * @return Data item */ public getDataItemById(id: string): DataItem<this["_dataItemSettings"]> | undefined { return $array.find(this.dataItems, (dataItem: any) => { return dataItem.get("id") == id; }) } protected _makeBullets(dataItem: DataItem<this["_dataItemSettings"]>) { if(this._shouldMakeBullet(dataItem)){ dataItem.bullets = []; this.bullets.each((bulletFunction) => { this._makeBullet(dataItem, bulletFunction); }) } } protected _shouldMakeBullet(_dataItem: DataItem<this["_dataItemSettings"]>):boolean{ return true; } protected _makeBullet(dataItem: DataItem<this["_dataItemSettings"]>, bulletFunction:(root: Root, series:Series, dataItem: DataItem<this["_dataItemSettings"]>) => Bullet | undefined, index?:number):Bullet | undefined{ const bullet = bulletFunction(this._root, this, dataItem); if(bullet){ let sprite = bullet.get("sprite"); if (sprite) { sprite._setDataItem(dataItem); sprite.setRaw("position", "absolute"); this.bulletsContainer.children.push(sprite); } bullet._index = index; bullet.series = this; dataItem.bullets!.push(bullet); } return bullet; } public _clearDirty() { super._clearDirty(); this._aggregatesCalculated = false; this._selectionAggregatesCalculated = false; } public _prepareChildren(){ super._prepareChildren(); let startIndex = this.startIndex(); let endIndex = this.endIndex(); const calculateAggregates = this.get("calculateAggregates"); if(calculateAggregates){ if (this._valuesDirty && !this._dataProcessed) { if (!this._aggregatesCalculated) { this._calculateAggregates(0, this.dataItems.length); this._aggregatesCalculated = true; } } if ((this._psi != startIndex || this._pei != endIndex) && !this._selectionAggregatesCalculated) { if (startIndex === 0 && endIndex === this.dataItems.length && this._aggregatesCalculated) { // void } else { this._calculateAggregates(startIndex, endIndex); } this._selectionAggregatesCalculated = true; } } if(this.isDirty("tooltip")){ let tooltip = this.get("tooltip"); if(tooltip){ tooltip.hide(0); tooltip.set("tooltipTarget", this); } } if (this.isDirty("fill") || this.isDirty("stroke")) { let markerRectangle: Graphics | undefined; const legendDataItem = this.get("legendDataItem"); if (legendDataItem) { markerRectangle = legendDataItem.get("markerRectangle"); if (markerRectangle) { if (this.isDirty("stroke")) { let stroke = this.get("stroke"); markerRectangle.set("stroke", stroke); } if (this.isDirty("fill")) { let fill = this.get("fill"); markerRectangle.set("fill", fill); } } } this.updateLegendMarker(undefined); } if (this.bullets.length > 0) { let startIndex = this.startIndex(); let endIndex = this.endIndex(); for (let i = startIndex; i < endIndex; i++) { let dataItem = this.dataItems[i]; if (!dataItem.bullets) { this._makeBullets(dataItem); } } } } protected _calculateAggregates(startIndex: number, endIndex: number) { let fields = this._valueFields; if (!fields) { throw new Error("No value fields are set for the series."); } const sum: { [index: string]: number } = {}; const absSum: { [index: string]: number } = {}; const count: { [index: string]: number } = {}; const low: { [index: string]: number } = {}; const high: { [index: string]: number } = {}; const open: { [index: string]: number } = {}; const close: { [index: string]: number } = {}; const average: { [index: string]: number } = {}; const previous: { [index: string]: number } = {}; $array.each(fields, (key) => { sum[key] = 0; absSum[key] = 0; count[key] = 0; }) $array.each(fields, (key) => { let change = key + "Change"; let changePercent = key + "ChangePercent"; let changePrevious = key + "ChangePrevious"; let changePreviousPercent = key + "ChangePreviousPercent"; let changeSelection = key + "ChangeSelection"; let ChangeSelectionPercent = key + "ChangeSelectionPercent"; for (let i = startIndex; i < endIndex; i++) { const dataItem = this.dataItems[i]; let value = dataItem.get(<any>key) if (value != null) { count[key]++; sum[key] += value; absSum[key] += Math.abs(value); average[key] = sum[key] / count[key]; if (low[key] > value || low[key] == null) { low[key] = value; } if (high[key] < value || high[key] == null) { high[key] = value; } close[key] = value; if (open[key] == null) { open[key] = value; previous[key] = value; } if (startIndex === 0) { dataItem.setRaw(<any>(change), value - open[key]); dataItem.setRaw(<any>(changePercent), (value - open[key]) / open[key] * 100); } dataItem.setRaw(<any>(changePrevious), value - previous[key]); dataItem.setRaw(<any>(changePreviousPercent), (value - previous[key]) / previous[key] * 100); dataItem.setRaw(<any>(changeSelection), value - open[key]); dataItem.setRaw(<any>(ChangeSelectionPercent), (value - open[key]) / open[key] * 100); previous[key] = value; } } }) $array.each(fields, (key) => { this.setPrivate(<any>(key + "AverageSelection"), average[key]); this.setPrivate(<any>(key + "CountSelection"), count[key]); this.setPrivate(<any>(key + "SumSelection"), sum[key]); this.setPrivate(<any>(key + "AbsoluteSumSelection"), absSum[key]); this.setPrivate(<any>(key + "LowSelection"), low[key]); this.setPrivate(<any>(key + "HighSelection"), high[key]); this.setPrivate(<any>(key + "OpenSelection"), open[key]); this.setPrivate(<any>(key + "CloseSelection"), close[key]); }) if (startIndex === 0 && endIndex === this.dataItems.length) { $array.each(fields, (key) => { this.setPrivate(<any>(key + "Average"), average[key]); this.setPrivate(<any>(key + "Count"), count[key]); this.setPrivate(<any>(key + "Sum"), sum[key]); this.setPrivate(<any>(key + "AbsoluteSum"), absSum[key]); this.setPrivate(<any>(key + "Low"), low[key]); this.setPrivate(<any>(key + "High"), high[key]); this.setPrivate(<any>(key + "Open"), open[key]); this.setPrivate(<any>(key + "Close"), close[key]); }) } } public _updateChildren() { super._updateChildren(); this._psi = this.startIndex(); this._pei = this.endIndex(); // Apply heat rules if (this._valuesDirty && this.get("heatRules") != null) { const rules = this.get("heatRules", []); $array.each(rules, (rule) => { const minValue = rule.minValue || this.getPrivate(<any>(rule.dataField + "Low")) || 0; const maxValue = rule.maxValue || this.getPrivate(<any>(rule.dataField + "High")) || 0; $array.each(rule.target._entities, (target) => { const value = target.dataItem.get(rule.dataField); if (!$type.isNumber(value)) { return; } let percent: number; if (rule.logarithmic) { percent = (Math.log(value) * Math.LOG10E - Math.log(minValue) * Math.LOG10E) / ((Math.log(maxValue) * Math.LOG10E - Math.log(minValue) * Math.LOG10E)); } else { percent = (value - minValue) / (maxValue - minValue); } if ($type.isNumber(value) && (!$type.isNumber(percent) || Math.abs(percent) == Infinity)) { percent = 0.5; } // fixes problems if all values are the same let propertyValue; if ($type.isNumber(rule.min)) { propertyValue = rule.min + (rule.max - rule.min) * percent; } else if (rule.min instanceof Color) { propertyValue = Color.interpolate(percent, rule.min, rule.max); } else if (rule.min instanceof Percent) { propertyValue = percentInterpolate(percent, rule.min, rule.max); } if (rule.customFunction) { rule.customFunction.call(this, target, minValue, maxValue, value); } else { target.set(rule.key, propertyValue); } }); }); } if (this.bullets.length > 0) { let count = this.dataItems.length; let startIndex = this.startIndex(); let endIndex = this.endIndex(); if(endIndex < count){ endIndex++; } if(startIndex > 0){ startIndex--; } for (let i = 0; i < startIndex; i++) { this._hideBullets(this.dataItems[i]); } for (let i = startIndex; i < endIndex; i++) { this._positionBullets(this.dataItems[i]); } for (let i = endIndex; i < count; i++) { this._hideBullets(this.dataItems[i]); } } } public _positionBullets(dataItem: DataItem<this["_dataItemSettings"]>){ if(dataItem.bullets){ $array.each(dataItem.bullets, (bullet) => { this._positionBullet(bullet); const sprite = bullet.get("sprite"); if(bullet.get("dynamic")){ if(sprite){ sprite._markDirtyKey("fill" as any); sprite.markDirtySize(); } if(sprite instanceof Container){ sprite.walkChildren((child)=>{ child._markDirtyKey("fill" as any); child.markDirtySize(); }) } } if(sprite instanceof Label && sprite.get("populateText" as any)){ sprite.text.markDirtyText(); } }) } } protected _hideBullets(dataItem: DataItem<this["_dataItemSettings"]>) { if (dataItem.bullets) { $array.each(dataItem.bullets, (bullet) => { let sprite = bullet.get("sprite"); if (sprite) { sprite.setPrivate("visible", false); } }) } } public _positionBullet(_bullet: Bullet) { } public _placeBulletsContainer(chart:Chart){ chart.bulletsContainer.children.moveValue(this.bulletsContainer); } public _removeBulletsContainer(){ const bulletsContainer = this.bulletsContainer; if(bulletsContainer.parent){ bulletsContainer.parent.children.removeValue(bulletsContainer) } } /** * @ignore */ public disposeDataItem(dataItem: DataItem<this["_dataItemSettings"]>) { const bullets = dataItem.bullets; if(bullets){ $array.each(bullets, (bullet)=>{ bullet.dispose(); }) } } protected _getItemReaderLabel(): string { return ""; } /** * Shows series's data item. * * @param dataItem Data item * @param duration Animation duration in milliseconds * @return Promise */ public async showDataItem(dataItem: DataItem<this["_dataItemSettings"]>, duration?: number): Promise<void> { const promises = [super.showDataItem(dataItem, duration)]; const bullets = dataItem.bullets; if(bullets){ $array.each(bullets, (bullet)=>{ promises.push(bullet.get("sprite").show(duration)); }) } await Promise.all(promises); } /** * Hides series's data item. * * @param dataItem Data item * @param duration Animation duration in milliseconds * @return Promise */ public async hideDataItem(dataItem: DataItem<this["_dataItemSettings"]>, duration?: number): Promise<void> { const promises = [super.hideDataItem(dataItem, duration)]; const bullets = dataItem.bullets; if(bullets){ $array.each(bullets, (bullet)=>{ promises.push(bullet.get("sprite").hide(duration)); }) } await Promise.all(promises); } protected async _sequencedShowHide(show: boolean, duration?: number): Promise<void> { if (this.get("sequencedInterpolation")) { if (!$type.isNumber(duration)) { duration = this.get("interpolationDuration", 0); } if (duration > 0) { const startIndex = this.startIndex(); const endIndex = this.endIndex(); await Promise.all($array.map(this.dataItems, async (dataItem, i) => { let realDuration = duration || 0; if (i < startIndex - 10 || i > endIndex + 10) { realDuration = 0; } //let delay = this.get("sequencedDelay", 0) * i + realDuration * (i - startIndex) / (endIndex - startIndex); let delay = this.get("sequencedDelay", 0) + realDuration / (endIndex - startIndex); await $time.sleep(delay * (i - startIndex)); if (show) { await this.showDataItem(dataItem, realDuration); } else { await this.hideDataItem(dataItem, realDuration); } })); } else { await Promise.all($array.map(this.dataItems, (dataItem) => { if (show) { return this.showDataItem(dataItem, 0); } else { return this.hideDataItem(dataItem, 0); } })); } } } /** * @ignore */ public updateLegendValue(dataItem: DataItem<this["_dataItemSettings"]>) { const legendDataItem = dataItem.get("legendDataItem" as any) as DataItem<ILegendDataItem>; if (legendDataItem) { const valueLabel = legendDataItem.get("valueLabel"); if (valueLabel) { const text = valueLabel.text; let txt = ""; valueLabel._setDataItem(dataItem); txt = this.get("legendValueText", text.get("text", "")); valueLabel.set("text", txt); text.markDirtyText(); } const label = legendDataItem.get("label"); if (label) { const text = label.text; let txt = ""; label._setDataItem(dataItem); txt = this.get("legendLabelText", text.get("text", "")); label.set("text", txt); text.markDirtyText(); } } } /** * @ignore */ public updateLegendMarker(_dataItem?: DataItem<this["_dataItemSettings"]>) { } protected _onHide(){ super._onHide(); const tooltip = this.getTooltip(); if(tooltip){ tooltip.hide(); } } /** * @ignore */ public hoverDataItem(_dataItem: DataItem<this["_dataItemSettings"]>) { } /** * @ignore */ public unhoverDataItem(_dataItem: DataItem<this["_dataItemSettings"]>) { } }
the_stack
const PACKAGE_ID: string = "tst-reflect"; /** * Kind of type */ export enum TypeKind { /** * Interface */ Interface, /** * Class */ Class, /** * Native JavaScript/TypeScript type */ Native, /** * Container for other types in case of types union or intersection */ Container, /** * Type reference created during type checking * @description Usually Array<...>, ReadOnly<...> etc. */ TransientTypeReference, /** * Some specific object * @description Eg. "{ foo: string, bar: boolean }" */ Object, /** * Some subtype of string, number, boolean * @example <caption>type Foo = "hello world" | "hello"</caption> * String "hello world" is literal type and it is subtype of string. * * <caption>type TheOnlyTrue = true;</caption> * Same as true is literal type and it is subtype of boolean. */ LiteralType, /** * Fixed lenght arrays literals * @example <caption>type Coords = [x: number, y: number, z: number];</caption> */ Tuple, /** * Generic parameter type * @description Represent generic type parameter of generic types. Eg. it is TType of class Animal<TType> {}. */ TypeParameter, /** * Conditional type */ ConditionalType = 9, } /** * @internal */ export interface ConditionalTypeDescription { /** * Extends type */ e: Type; /** * True type */ tt: Type; /** * False type */ ft: Type; } export interface ConditionalType { /** * Extends type */ extends: Type; /** * True type */ trueType: Type; /** * False type */ falseType: Type; } /** * @internal */ export interface ParameterDescription { n: string; t: Type; o: boolean; } /** * @internal */ export interface PropertyDescription { n: string; t: Type; d?: Array<DecoratorDescription>; } /** * Property description */ export interface Property { /** * Property name */ name: string; /** * Property type */ type: Type; /** * Property decorators */ decorators: Array<Decorator>; } /** * @internal */ export interface DecoratorDescription { n: string; fn: string; } /** * Decoration description */ export interface Decorator { /** * Decorator name */ name: string; /** * Decorator full name */ fullName?: string; } /** * Method parameter description */ export interface MethodParameter { /** * Parameter name */ name: string; /** * Parameter type */ type: Type; /** * Parameter is optional */ optional: boolean; } /** * @internal */ export interface ConstructorDescription { params: Array<ParameterDescription> } /** * Constructor description object */ export interface Constructor { /** * Constructor parameters */ parameters: Array<MethodParameter> } /** * @internal */ export interface TypeProperties { /** * Type name */ n?: string; /** * Type fullname */ fn?: string; /** * TypeKind */ k: TypeKind; /** * Constructors */ ctors?: Array<ConstructorDescription>; /** * Properties */ props?: Array<PropertyDescription>; /** * Decorators */ decs?: Array<DecoratorDescription>; /** * Generic type parameters */ tp?: Array<Type>; /** * Is union type */ union?: boolean; /** * Is intersection type */ inter?: boolean; /** * Unified or intersecting types */ types?: Array<Type>; /** * Ctor getter */ ctor?: () => Function; /** * Extended base type */ bt?: Type; /** * Implemented interface */ iface?: Type; /** * Literal value */ v?: any /** * Type arguments */ args?: Array<Type> /** * Default type */ def?: Type, /** * Constraining type */ con?: Type, /** * Conditional type description */ ct?: ConditionalTypeDescription } const typesMetaCache: { [key: number]: Type } = {}; /** * Object representing TypeScript type in memory */ export class Type { public static readonly Object: Type; private readonly _ctor?: () => Function; private readonly _kind: TypeKind; private readonly _name: string; private readonly _fullName: string; private readonly _isUnion: boolean; private readonly _isIntersection: boolean; private readonly _types?: Array<Type>; private readonly _properties: Array<Property>; private readonly _decorators: Array<Decorator>; private readonly _constructors: Array<Constructor>; private readonly _typeParameters: Array<Type>; private readonly _baseType?: Type; private readonly _interface?: Type; private readonly _literalValue?: any; private readonly _typeArgs: Array<Type>; private readonly _conditionalType?: ConditionalType; private readonly _genericTypeConstraint?: Type; private readonly _genericTypeDefault?: Type; /** * Internal Type constructor * @internal */ constructor(description: TypeProperties) { if (new.target != TypeActivator) { throw new Error("You cannot create instance of Type manually!"); } this._name = description.n || ""; this._fullName = description.fn || description.n || ""; this._kind = description.k; this._constructors = description.ctors?.map(Type.mapConstructors) || []; this._properties = description.props?.map(Type.mapProperties) || []; this._decorators = description.decs?.map(Type.mapDecorators) || []; this._typeParameters = description.tp || []; this._ctor = description.ctor; this._baseType = description.bt ?? (description.ctor == Object ? undefined : Type.Object); this._interface = description.iface; this._isUnion = description.union || false; this._isIntersection = description.inter || false; this._types = description.types; this._literalValue = description.v; this._typeArgs = description.args || []; this._conditionalType = description.ct ? { extends: description.ct.e, trueType: description.ct.tt, falseType: description.ct.ft } : undefined; this._genericTypeConstraint = description.con; this._genericTypeDefault = description.def; } /** * @internal * @param typeId */ public static _getTypeMeta(typeId: number) { const type = typesMetaCache[typeId]; if (!type) { throw new Error(`Unknown type identifier '${typeId}'. Metadata not found.`); } return type; } /** * @internal * @param typeId * @param type */ public static _storeTypeMeta(typeId: number, type: Type) { typesMetaCache[typeId] = type; } /** * @internal * @param d */ private static mapDecorators(d: DecoratorDescription): Decorator { return ({ name: d.n, fullName: d.fn }); } /** * @internal * @param p */ private static mapProperties(p: PropertyDescription): Property { return ({ name: p.n, type: p.t, decorators: p.d?.map(Type.mapDecorators) || [] }); } /** * @internal * @param c */ private static mapConstructors(c: ConstructorDescription): Constructor { return ({ parameters: c.params.map(p => ({ name: p.n, type: p.t, optional: p.o })) }); } // noinspection JSUnusedGlobalSymbols /** * Returns information about generic conditional type. */ get condition(): ConditionalType | undefined { return this._conditionalType; } // noinspection JSUnusedGlobalSymbols /** * Returns a value indicating whether the Type is container for unified Types or not */ get union(): boolean { return this._isUnion; } // noinspection JSUnusedGlobalSymbols /** * Returns a value indicating whether the Type is container for intersecting Types or not */ get intersection(): boolean { return this._isIntersection; } // noinspection JSUnusedGlobalSymbols /** * List of underlying types in case Type is union or intersection */ get types(): Array<Type> | undefined { return this._types; } // noinspection JSUnusedGlobalSymbols /** * Constructor function in case Type is class */ get ctor(): Function | undefined { return this._ctor?.(); } // noinspection JSUnusedGlobalSymbols /** * Base type * @description Base type from which this type extends from or undefined if type is Object. */ get baseType(): Type | undefined { return this._baseType; } // noinspection JSUnusedGlobalSymbols /** * Get type full-name * @description Contains file path base to project root */ get fullName(): string { return this._fullName; } // noinspection JSUnusedGlobalSymbols /** * Get type name */ get name(): string { return this._name; } // noinspection JSUnusedGlobalSymbols /** * Get kind of type */ get kind(): TypeKind { return this._kind; } // noinspection JSUnusedGlobalSymbols /** * Returns true if types are equals * @param type */ is(type: Type) { return this._fullName == type._fullName; } // noinspection JSUnusedGlobalSymbols /** * Returns a value indicating whether the Type is a class or not */ isClass(): boolean { return this.kind == TypeKind.Class; } // noinspection JSUnusedGlobalSymbols /** * Returns a value indicating whether the Type is a interface or not */ isInterface(): boolean { return this.kind == TypeKind.Interface; } // noinspection JSUnusedGlobalSymbols /** * Returns a value indicating whether the Type is an literal or not */ isLiteral(): boolean { return this._kind == TypeKind.LiteralType; } // noinspection JSUnusedGlobalSymbols /** * Get underlying value in case of literal type */ getLiteralValue(): any { return this._literalValue; } // noinspection JSUnusedGlobalSymbols /** * Returns a value indicating whether the Type is an object literal or not */ isObjectLiteral(): boolean { return this._kind == TypeKind.Object; } // noinspection JSUnusedGlobalSymbols /** * Returns array of properties */ getTypeParameters(): Array<Type> { return this._typeParameters; } // noinspection JSUnusedGlobalSymbols /** * Return type arguments in case of generic type */ getTypeArguments(): Array<Type> { return this._typeArgs; } // noinspection JSUnusedGlobalSymbols /** * Returns constructor description when Type is a class */ getConstructors(): Array<Constructor> | undefined { if (!this.isClass()) { return undefined; } return this._constructors; } // noinspection JSUnusedGlobalSymbols /** * Returns interface which this type implements */ getInterface(): Type | undefined { return this._interface; } // noinspection JSUnusedGlobalSymbols /** * Returns array of properties */ getProperties(): Array<Property> { return this._properties; } // noinspection JSUnusedGlobalSymbols /** * Returns array of decorators */ getDecorators(): Array<Decorator> { return this._decorators; } // noinspection JSUnusedGlobalSymbols /** * Returns true if this type is assignable to target type * @param target */ isAssignableTo(target: Type): boolean { return this.fullName == target.fullName || this._baseType?.isAssignableTo(target) || this._interface?.isAssignableTo(target) || false; } /** * Check if this type is a string */ isString(): boolean { return (this.kind == TypeKind.Native || this.kind == TypeKind.LiteralType) && this.name == "string"; } /** * Check if this type is a number */ isNumber(): boolean { return (this.kind == TypeKind.Native || this.kind == TypeKind.LiteralType) && this.name == "number"; } /** * Check if this type is a boolean */ isBoolean(): boolean { return (this.kind == TypeKind.Native || this.kind == TypeKind.LiteralType) && this.name == "boolean"; } /** * Check if this type is an array */ isArray(): boolean { return (this.kind == TypeKind.Native || this.kind == TypeKind.LiteralType) && this.name == "Array"; } } class TypeActivator extends Type { } (Type as any).Object = Reflect.construct(Type, [ { n: "Object", fn: "Object", ctor: Object, k: TypeKind.Native } ], TypeActivator); /** * Returns Type of generic parameter */ export function getType<T>(): Type | undefined // TODO: Uncomment and use this line. Waiting for TypeScript issue to be resolved. https://github.com/microsoft/TypeScript/issues/46155 // export function getType<T = void>(..._: (T extends void ? ["You must provide a type parameter"] : [])): Type | undefined /** @internal */ export function getType<T>(description?: TypeProperties | number | string, typeId?: number): Type | undefined { // Return type from storage if (typeof description == "number") { return Type._getTypeMeta(description); } // Construct Type instance if (description && description.constructor === Object) { const type = Reflect.construct(Type, [description], TypeActivator); // Store Type if it has ID if (typeId) { Type._storeTypeMeta(typeId, type); } return type; } return undefined; } getType.__tst_reflect__ = true; /** * Class decorator which marks classes to be processed and included in metadata lib file. * @reflectDecorator */ export function reflect<TType>() { getType<TType>(); return function<T>(Constructor: { new(...args: any[]): T }) { }; } /** * To identify functions by package */ export const TYPE_ID_PROPERTY_NAME = "__tst_reflect__"; /** * Name of JSDoc comment marking method as it use type of generic parameter. */ export const REFLECT_GENERIC_DECORATOR = "reflectGeneric"; /** * Name of JSDoc comment marking function as decorator. * @type {string} */ export const REFLECT_DECORATOR_DECORATOR = "reflectDecorator"; /** * Name of the getType() function */ export const GET_TYPE_FNC_NAME = "getType";
the_stack
import { IDisposable } from '@lumino/disposable'; import { LabIcon } from '@jupyterlab/ui-components'; import { NotebookPanel, NotebookActions } from '@jupyterlab/notebook'; import { MarkdownCell } from '@jupyterlab/cells'; import CodeMirror from 'codemirror'; import { IRenderMime } from '@jupyterlab/rendermime-interfaces'; import { FloatingWindow } from './floating'; import { StickyContent, ContentType } from './content'; import { MyIcons } from './icons'; /** * Class that implements the Markdown cell in StickyLand. */ export class StickyMarkdown implements IDisposable { stickyContent!: StickyContent; node!: HTMLElement; toolbar!: HTMLElement; cellNode!: HTMLElement; originalCell!: MarkdownCell; cell!: MarkdownCell; renderer!: IRenderMime.IRenderer; notebook!: NotebookPanel; codemirror!: CodeMirror.Editor; isDisposed = false; floatingWindow!: FloatingWindow; isFloating = false; /** * Factory function for StickyMarkdown when creating if from an existing cell * through dragging * @param stickyContent The sticky content that contains this markdown cell * @param cell The existing markdown cell * @param notebook The current notebook * @returns A new StickyMarkdown object */ static createFromExistingCell( stickyContent: StickyContent, cell: MarkdownCell, notebook: NotebookPanel ): StickyMarkdown { const md = new StickyMarkdown(); md.stickyContent = stickyContent; md.notebook = notebook; // Clone the cell md.originalCell = cell; md.cell = md.originalCell.clone(); // Collapse the original cell if (!md.originalCell.inputHidden) { md.originalCell.inputHidden = true; } // Save a reference to the cell's renderer (private) // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore md.renderer = md.cell._renderer; // Add a markdown cell element md.node = document.createElement('div'); md.node.classList.add('sticky-md'); // Need to add tabindex so it can receive keyboard events md.node.setAttribute('tabindex', '0'); md.stickyContent.contentNode.appendChild(md.node); // Add a toolbar md.toolbar = md.createToolbar(md.toolBarItems); md.stickyContent.headerNode.appendChild(md.toolbar); // Clean the markdown cell // Need to append the node to DOM first so we can do the cleaning md.cellNode = md.cell.node; md.cellNode.classList.add('hidden'); md.node.appendChild(md.cellNode); // Bind the Codemirror const codeMirrorNode = md.cell.node.querySelector('.CodeMirror') as unknown; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore md.codemirror = codeMirrorNode.CodeMirror as CodeMirror.Editor; // Bind events md.bindEventHandlers(); // Clean the unnecessary elements from the node clone md.cleanCellClone(); return md; } /** * Factory function for StickyMarkdown when creating if from a new markdown * cell. This function would append a new markdown cell to the main notebook. * @param stickyContent The sticky content that contains this markdown cell * @param notebook The current notebook * @returns A new StickyMarkdown object */ static createFromNewCell( stickyContent: StickyContent, notebook: NotebookPanel ): StickyMarkdown { // Append a new markdown cell to the main notebook NotebookActions.insertBelow(notebook.content); NotebookActions.changeCellType(notebook.content, 'markdown'); const newCell = notebook.content.activeCell as MarkdownCell; // Activate the original active cell notebook.content.activeCellIndex = notebook.content.activeCellIndex - 1; // Construct StickyMarkdown using the new cell as an existing cell return this.createFromExistingCell(stickyContent, newCell, notebook); } /** * Strip unnecessary elements from the nodes before appending it to stickyland */ cleanCellClone = () => { // Remove the left region (prompt and collapser), header and footer this.cellNode.querySelector('.jp-Cell-inputCollapser')?.remove(); this.cellNode.querySelector('.jp-InputArea-prompt')?.remove(); this.cellNode.querySelector('.jp-CellHeader')?.remove(); this.cellNode.querySelector('.jp-CellFooter')?.remove(); // Add class name to the rendered region this.cellNode .querySelector('.jp-MarkdownOutput') ?.classList.add('sticky-md-output'); this.cellNode.classList.add('sticky-md-cell'); this.cellNode.classList.remove('hidden'); // Render the latex on the clone node this.renderLatex(); }; /** * Bind event handlers for sticky markdown cell. */ bindEventHandlers = () => { // Double click the rendered view should trigger editor this.node.addEventListener('dblclick', (e: MouseEvent) => { e.preventDefault(); e.stopPropagation(); if (this.cell.rendered) { this.enterEditor(); } }); // Click on the rendered view should focus the current element this.node.addEventListener('click', (e: MouseEvent) => { if (this.cell.rendered) { this.node.focus(); } }); // Bind keyboard short cuts this.node.addEventListener('keydown', (e: KeyboardEvent) => { if (e.key === 'Enter') { if (e.shiftKey || e.ctrlKey) { // [Shift + enter] or [control + enter] render the markdown cell if (!this.cell.rendered) { this.quitEditor(); } e.preventDefault(); e.stopPropagation(); } else { // [Enter] in rendered mode triggers the editor if (this.cell.rendered) { this.enterEditor(); e.preventDefault(); e.stopPropagation(); } } } }); }; /** * Create a toolbar element * @param items List of toolbar item names and onclick handlers */ createToolbar = ( items: { name: string; title: string; icon: LabIcon; onClick: (e: Event) => any; }[] ): HTMLElement => { const toolbar = document.createElement('div'); toolbar.classList.add('sticky-toolbar', 'jp-Toolbar'); // Add buttons into the toolbar items.forEach(d => { const item = document.createElement('div'); item.classList.add('jp-ToolbarButton', 'jp-Toolbar-item'); toolbar.appendChild(item); const itemElem = document.createElement('button'); itemElem.classList.add( 'jp-ToolbarButtonComponent', 'button', 'jp-Button', 'toolbar-button', 'bp3-button', 'bp3-minimal', `button-${d.name}` ); itemElem.setAttribute('title', d.title); itemElem.addEventListener('click', d.onClick); item.appendChild(itemElem); // Add icon to the button const iconSpan = document.createElement('span'); iconSpan.classList.add('jp-ToolbarButtonComponent-icon'); itemElem.appendChild(iconSpan); d.icon.element({ container: iconSpan }); }); return toolbar; }; /** * Helper function to enter the editor mode. */ enterEditor = () => { // Trigger the editor this.cell.rendered = false; // Move the cursor on the first line before the first character this.cell.editor.focus(); this.cell.editor.setCursorPosition({ line: 0, column: 0 }); }; /** * Helper function to quit the editor mode. */ quitEditor = () => { // Trigger the rendered output this.cell.rendered = true; // Focus the cell node so we can listen to keyboard events this.node.focus(); /** * Since we are not attaching the renderer widget to any other widget, the * onAttach method is never called, so the latex typesetter is never called * We need to manually call it after rendering the node */ this.renderLatex(); }; /** * A helper function to force render latex after timeout. * @param timeout Call the latex renderer after `timeout` ms */ renderLatex = (timeout = 100) => { /** * Since we are not attaching the renderer widget to any other widget, the * onAttach method is never called, so the latex typesetter is never called * We need to manually call it after rendering the node * https://github.com/jupyterlab/jupyterlab/blob/d48e0c04efb786561137fb20773fc15788507f0a/packages/rendermime/src/widgets.ts#L225 */ setTimeout(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore this.renderer.latexTypesetter?.typeset(this.renderer.node); }, timeout); }; /** * Float the current code cell. */ float = () => { // Create the floating window and put content from stickyland to the floating // window this.floatingWindow = new FloatingWindow(ContentType.Markdown, this); // Finally, toggle the `isFloating` property this.isFloating = true; }; editClicked = (event: Event) => { event.preventDefault(); event.stopPropagation(); // Show the editing area if (this.cell.rendered) { this.enterEditor(); } }; runClicked = (event: Event) => { event.preventDefault(); event.stopPropagation(); // Render the markdown if (!this.cell.rendered) { this.quitEditor(); } }; launchClicked = (event: Event) => { event.preventDefault(); event.stopPropagation(); this.float(); }; closeClicked = () => { // Show the original cell this.originalCell.inputHidden = false; // TEMP: replace the current content with the dropzone this.stickyContent.showDropzone(); // Remove the code cell this.dispose(); }; toolBarItems = [ { name: 'run', title: 'Run the cell', icon: MyIcons.runIcon, onClick: this.runClicked }, { name: 'edit', title: 'Edit the cell', icon: MyIcons.editIcon, onClick: this.editClicked }, { name: 'launch', title: 'Make the cell float', icon: MyIcons.launchIcon, onClick: this.launchClicked } ]; dispose() { this.node.remove(); this.toolbar.remove(); this.isDisposed = true; } }
the_stack
import { SongDocument } from "./SongDocument"; import { HTML } from "imperative-html/dist/esm/elements-strict"; import { ColorConfig } from "./ColorConfig"; import { InputBox } from "./HTMLWrapper"; import { ChangeChannelOrder, ChangeChannelName, ChangeChannelCount } from "./changes"; import { Config } from "../synth/SynthConfig"; import { SongEditor } from "./SongEditor"; //namespace beepbox { export class MuteEditor { private readonly _buttons: HTMLDivElement[] = []; private readonly _channelCounts: HTMLDivElement[] = []; private readonly _channelNameDisplay: HTMLDivElement = HTML.div({ style: `background-color: ${ColorConfig.uiWidgetFocus}; white-space:nowrap; display: none; transform:translate(20px); width: auto; pointer-events: none; position: absolute; border-radius: 0.2em; z-index: 2;`, "color": ColorConfig.primaryText }, ""); public readonly _channelNameInput: InputBox = new InputBox(HTML.input({ style: `color: ${ColorConfig.primaryText}; background-color: ${ColorConfig.uiWidgetFocus}; margin-top: -2px; display: none; width: 6em; position: absolute; border-radius: 0.2em; z-index: 2;`, "color": ColorConfig.primaryText }, ""), this._doc, (oldValue: string, newValue: string) => new ChangeChannelName(this._doc, oldValue, newValue)); private readonly _channelDropDown: HTMLSelectElement = HTML.select({ style: "width: 0px; left: 19px; height: 19px; position:absolute; opacity:0" }, HTML.option({ value: "rename" }, "Rename..."), HTML.option({ value: "chnUp" }, "Move Channel Up"), HTML.option({ value: "chnDown" }, "Move Channel Down"), HTML.option({ value: "chnMute" }, "Mute Channel"), HTML.option({ value: "chnSolo" }, "Solo Channel"), HTML.option({ value: "chnInsert" }, "Insert Channel Below"), HTML.option({ value: "chnDelete" }, "Delete This Channel"), ); public readonly container: HTMLElement = HTML.div({ class: "muteEditor", style: "position: relative; margin-top: " + Config.barEditorHeight + "px;" }, this._channelNameDisplay, this._channelNameInput.input, this._channelDropDown); private _editorHeight: number = 128; private _renderedChannelCount: number = 0; private _renderedPitchChannels: number = 0; private _renderedNoiseChannels: number = 0; private _renderedModChannels: number = 0; private _renderedChannelHeight: number = -1; private _channelDropDownChannel: number = 0; private _channelDropDownOpen: boolean = false; private _channelDropDownLastState: boolean = false; constructor(private _doc: SongDocument, private _editor: SongEditor) { this.container.addEventListener("click", this._onClick); this.container.addEventListener("mousemove", this._onMouseMove); this.container.addEventListener("mouseleave", this._onMouseLeave); this._channelDropDown.selectedIndex = -1; this._channelDropDown.addEventListener("change", this._channelDropDownHandler); this._channelDropDown.addEventListener("mousedown", this._channelDropDownGetOpenedPosition); this._channelDropDown.addEventListener("blur", this._channelDropDownBlur); this._channelDropDown.addEventListener("click", this._channelDropDownClick); this._channelNameInput.input.addEventListener("change", this._channelNameInputHide); this._channelNameInput.input.addEventListener("blur", this._channelNameInputHide); this._channelNameInput.input.addEventListener("mousedown", this._channelNameInputClicked); this._channelNameInput.input.addEventListener("input", this._channelNameInputWhenInput); } private _channelNameInputWhenInput = (): void => { let newValue = this._channelNameInput.input.value; if (newValue.length > 15) { this._channelNameInput.input.value = newValue.substring(0, 15); } } private _channelNameInputClicked = (event: MouseEvent): void => { event.stopPropagation(); } private _channelNameInputHide = (): void => { this._channelNameInput.input.style.setProperty("display", "none"); this._channelNameDisplay.style.setProperty("display", "none"); } private _channelDropDownClick = (event: MouseEvent): void => { this._channelDropDownOpen = !this._channelDropDownLastState; this._channelDropDownGetOpenedPosition(event); //console.log("click " + this._channelDropDownOpen); } private _channelDropDownBlur = (): void => { this._channelDropDownOpen = false; this._channelNameDisplay.style.setProperty("display", "none"); //console.log("blur " + this._channelDropDownOpen); } private _channelDropDownGetOpenedPosition = (event: MouseEvent): void => { this._channelDropDownLastState = this._channelDropDownOpen; this._channelDropDownChannel = Math.floor(Math.min(this._renderedChannelCount, Math.max(0, parseInt(this._channelDropDown.style.getPropertyValue("top")) / this._renderedChannelHeight))); this._doc.muteEditorChannel = this._channelDropDownChannel; this._channelNameDisplay.style.setProperty("display", ""); // Check if channel is at limit, in which case another can't be inserted if ((this._channelDropDownChannel < this._doc.song.pitchChannelCount && this._doc.song.pitchChannelCount == Config.pitchChannelCountMax) || (this._channelDropDownChannel >= this._doc.song.pitchChannelCount && this._channelDropDownChannel < this._doc.song.pitchChannelCount + this._doc.song.noiseChannelCount && this._doc.song.noiseChannelCount == Config.noiseChannelCountMax) || (this._channelDropDownChannel >= this._doc.song.pitchChannelCount + this._doc.song.noiseChannelCount && this._doc.song.modChannelCount == Config.modChannelCountMax)) { this._channelDropDown.options[5].disabled = true; } else { this._channelDropDown.options[5].disabled = false; } // Also check if a channel is eligible to move up or down based on the song's channel settings. if (this._channelDropDownChannel == 0 || this._channelDropDownChannel == this._doc.song.pitchChannelCount || this._channelDropDownChannel == this._doc.song.pitchChannelCount + this._doc.song.noiseChannelCount) { this._channelDropDown.options[1].disabled = true; } else { this._channelDropDown.options[1].disabled = false; } if (this._channelDropDownChannel == this._doc.song.pitchChannelCount - 1 || this._channelDropDownChannel == this._doc.song.pitchChannelCount + this._doc.song.noiseChannelCount - 1 || this._channelDropDownChannel == this._doc.song.getChannelCount() - 1) { this._channelDropDown.options[2].disabled = true; } else { this._channelDropDown.options[2].disabled = false; } // Also, can't delete the last pitch channel. if (this._doc.song.pitchChannelCount == 1 && this._channelDropDownChannel == 0) { this._channelDropDown.options[6].disabled = true; } else { this._channelDropDown.options[6].disabled = false; } } private _channelDropDownHandler = (event: Event): void => { this._channelNameDisplay.style.setProperty("display", "none"); this._channelDropDown.style.setProperty("display", "none"); this._channelDropDownOpen = false; event.stopPropagation(); //console.log("handler " + this._channelDropDownOpen); switch (this._channelDropDown.value) { case "rename": this._channelNameInput.input.style.setProperty("display", ""); this._channelNameInput.input.style.setProperty("transform", this._channelNameDisplay.style.getPropertyValue("transform")); if (this._channelNameDisplay.textContent != null) { this._channelNameInput.input.value = this._channelNameDisplay.textContent; } else { this._channelNameInput.input.value = ""; } this._channelNameInput.input.select(); break; case "chnUp": this._doc.record(new ChangeChannelOrder(this._doc, this._channelDropDownChannel, this._channelDropDownChannel - 1)); break; case "chnDown": this._doc.record(new ChangeChannelOrder(this._doc, this._channelDropDownChannel, this._channelDropDownChannel + 1)); break; case "chnMute": this._doc.song.channels[this._channelDropDownChannel].muted = !this._doc.song.channels[this._channelDropDownChannel].muted; this.render(); break; case "chnSolo": { // Check for any channel not matching solo pattern let shouldSolo: boolean = false; for (let channel: number = 0; channel < this._doc.song.pitchChannelCount + this._doc.song.noiseChannelCount; channel++) { if (this._doc.song.channels[channel].muted == (channel == this._channelDropDownChannel)) { shouldSolo = true; channel = this._doc.song.pitchChannelCount + this._doc.song.noiseChannelCount; } } if (shouldSolo) { for (let channel: number = 0; channel < this._doc.song.pitchChannelCount + this._doc.song.noiseChannelCount; channel++) { this._doc.song.channels[channel].muted = (channel != this._channelDropDownChannel); } } else { for (let channel: number = 0; channel < this._doc.song.pitchChannelCount + this._doc.song.noiseChannelCount; channel++) { this._doc.song.channels[channel].muted = false; } } this.render(); break; } case "chnInsert": { // Add a channel at the end, then swap it in. let newPitchChannelCount: number = this._doc.song.pitchChannelCount; let newNoiseChannelCount: number = this._doc.song.noiseChannelCount; let newModChannelCount: number = this._doc.song.modChannelCount; let swapIndex: number; if (this._channelDropDownChannel < this._doc.song.pitchChannelCount) { newPitchChannelCount++; swapIndex = newPitchChannelCount; } else if (this._channelDropDownChannel < this._doc.song.pitchChannelCount + this._doc.song.noiseChannelCount) { newNoiseChannelCount++; swapIndex = newPitchChannelCount + newNoiseChannelCount; } else { newModChannelCount++; swapIndex = newPitchChannelCount + newNoiseChannelCount + newModChannelCount; } this._doc.record(new ChangeChannelCount(this._doc, newPitchChannelCount, newNoiseChannelCount, newModChannelCount)); for (let channel: number = swapIndex - 1; channel > this._channelDropDownChannel + 1; channel--) { this._doc.record(new ChangeChannelOrder(this._doc, channel - 1, channel), true); } break; } case "chnDelete": { let newPitchChannelCount: number = this._doc.song.pitchChannelCount; let newNoiseChannelCount: number = this._doc.song.noiseChannelCount; let newModChannelCount: number = this._doc.song.modChannelCount; if (this._channelDropDownChannel < this._doc.song.pitchChannelCount) { // Removing pitch channel, swap to the end since ChangeChannelCount expects a channel array of the previous size. newPitchChannelCount--; for (let channel: number = this._channelDropDownChannel; channel < newPitchChannelCount; channel++) { this._doc.record(new ChangeChannelOrder(this._doc, channel, channel + 1), channel != this._channelDropDownChannel); } } else if (this._channelDropDownChannel >= this._doc.song.pitchChannelCount && this._channelDropDownChannel < this._doc.song.pitchChannelCount + this._doc.song.noiseChannelCount) { // Removing noise channel, swap to the end since ChangeChannelCount expects a channel array of the previous size. newNoiseChannelCount--; for (let channel: number = this._channelDropDownChannel; channel < newPitchChannelCount + newNoiseChannelCount; channel++) { this._doc.record(new ChangeChannelOrder(this._doc, channel, channel + 1), channel != this._channelDropDownChannel); } } else { // Removing mod channel, swap to the end since ChangeChannelCount expects a channel array of the previous size. newModChannelCount--; for (let channel: number = this._channelDropDownChannel; channel < newPitchChannelCount + newNoiseChannelCount + newModChannelCount; channel++) { this._doc.record(new ChangeChannelOrder(this._doc, channel, channel + 1), channel != this._channelDropDownChannel); } } this._doc.record(new ChangeChannelCount(this._doc, newPitchChannelCount, newNoiseChannelCount, newModChannelCount), true); break; } } if (this._channelDropDown.value != "rename") this._editor.refocusStage(); this._channelDropDown.selectedIndex = -1; } private _onClick = (event: MouseEvent): void => { const index = this._buttons.indexOf(<HTMLDivElement>event.target); if (index == -1) return; let xPos: number = event.clientX - this._buttons[0].getBoundingClientRect().left; if (xPos < 21.0) { this._doc.song.channels[index].muted = !this._doc.song.channels[index].muted; } this._doc.notifier.changed(); } private _onMouseMove = (event: MouseEvent): void => { const index = this._buttons.indexOf(<HTMLDivElement>event.target); if (index == -1) { if (!this._channelDropDownOpen && event.target != this._channelNameDisplay && event.target != this._channelDropDown) { this._channelNameDisplay.style.setProperty("display", "none"); this._channelDropDown.style.setProperty("display", "none"); this._channelDropDown.style.setProperty("width", "0px"); } return; } let xPos: number = event.clientX - this._buttons[0].getBoundingClientRect().left; if (xPos >= 21.0) { if (!this._channelDropDownOpen) { // Mouse over chn. number this._channelDropDown.style.setProperty("display", ""); var height = this._doc.getChannelHeight(); this._channelNameDisplay.style.setProperty("transform", "translate(20px, " + (height / 4 + height * index) + "px)"); if (this._doc.song.channels[index].name != "") { this._channelNameDisplay.textContent = this._doc.song.channels[index].name; this._channelNameDisplay.style.setProperty("display", ""); } else { if (index < this._doc.song.pitchChannelCount) { this._channelNameDisplay.textContent = "Pitch " + (index + 1); } else if (index < this._doc.song.pitchChannelCount + this._doc.song.noiseChannelCount) { this._channelNameDisplay.textContent = "Noise " + (index - this._doc.song.pitchChannelCount + 1); } else { this._channelNameDisplay.textContent = "Mod " + (index - this._doc.song.pitchChannelCount - this._doc.song.noiseChannelCount + 1); } // The name set will only show up when this becomes visible, e.g. when the dropdown is opened. this._channelNameDisplay.style.setProperty("display", "none"); } this._channelDropDown.style.top = (Config.barEditorHeight - 2 + index * this._renderedChannelHeight) + "px"; this._channelDropDown.style.setProperty("width", "15px"); } } else { if (!this._channelDropDownOpen) { this._channelNameDisplay.style.setProperty("display", "none"); this._channelDropDown.style.setProperty("display", "none"); this._channelDropDown.style.setProperty("width", "0px"); } } } private _onMouseLeave = (event: MouseEvent): void => { if (!this._channelDropDownOpen) { this._channelNameDisplay.style.setProperty("display", "none"); this._channelDropDown.style.setProperty("width", "0px"); } } public onKeyUp(event: KeyboardEvent): void { switch (event.keyCode) { case 27: // esc this._channelDropDownOpen = false; //console.log("close"); this._channelNameDisplay.style.setProperty("display", "none"); break; case 13: // enter this._channelDropDownOpen = false; //console.log("close"); this._channelNameDisplay.style.setProperty("display", "none"); break; default: break; } } public render(): void { if (!this._doc.enableChannelMuting) return; const channelHeight = this._doc.getChannelHeight(); if (this._renderedChannelCount != this._doc.song.getChannelCount()) { for (let y: number = this._renderedChannelCount; y < this._doc.song.getChannelCount(); y++) { const channelCountText: HTMLDivElement = HTML.div({ class: "noSelection muteButtonText", style: "display: table-cell; vertical-align: middle; text-align: center; -webkit-user-select: none; -webkit-touch-callout: none; -moz-user-select: none; -ms-user-select: none; user-select: none; pointer-events: none; width: 12px; height: 20px; transform: translate(0px, 1px);" }); const muteButton: HTMLDivElement = HTML.div({ class: "mute-button", style: `display: block; pointer-events: none; width: 16px; height: 20px; transform: translate(2px, 1px);` }); const muteContainer: HTMLDivElement = HTML.div({ style: "align-items: center; height: 20px; margin: 0px; display: table; flex-direction: row; justify-content: space-between;" }, [ muteButton, channelCountText, ]); this.container.appendChild(muteContainer); this._buttons[y] = muteContainer; this._channelCounts[y] = channelCountText; } for (let y: number = this._doc.song.getChannelCount(); y < this._renderedChannelCount; y++) { this.container.removeChild(this._buttons[y]); } this._buttons.length = this._doc.song.getChannelCount(); } for (let y: number = 0; y < this._doc.song.getChannelCount(); y++) { if (this._doc.song.channels[y].muted) { this._buttons[y].children[0].classList.add("muted"); if (y < this._doc.song.pitchChannelCount) this._channelCounts[y].style.color = ColorConfig.trackEditorBgPitchDim; else if (y < this._doc.song.pitchChannelCount + this._doc.song.noiseChannelCount) this._channelCounts[y].style.color = ColorConfig.trackEditorBgNoiseDim; else this._channelCounts[y].style.color = ColorConfig.trackEditorBgModDim; } else { this._buttons[y].children[0].classList.remove("muted"); if (y < this._doc.song.pitchChannelCount) this._channelCounts[y].style.color = ColorConfig.trackEditorBgPitch; else if (y < this._doc.song.pitchChannelCount + this._doc.song.noiseChannelCount) this._channelCounts[y].style.color = ColorConfig.trackEditorBgNoise; else this._channelCounts[y].style.color = ColorConfig.trackEditorBgMod; } } if (this._renderedChannelHeight != channelHeight || this._renderedChannelCount != this._doc.song.getChannelCount()) { for (let y: number = 0; y < this._doc.song.getChannelCount(); y++) { this._buttons[y].style.marginTop = ((channelHeight - 20) / 2) + "px"; this._buttons[y].style.marginBottom = ((channelHeight - 20) / 2) + "px"; } } if (this._renderedModChannels != this._doc.song.modChannelCount || this._renderedChannelCount != this._doc.song.getChannelCount()) { for (let y: number = 0; y < this._doc.song.getChannelCount(); y++) { if (y < this._doc.song.pitchChannelCount + this._doc.song.noiseChannelCount) { this._buttons[y].children[0].classList.remove("modMute"); } else { this._buttons[y].children[0].classList.add("modMute"); } } } if (this._renderedModChannels != this._doc.song.modChannelCount || this._renderedPitchChannels != this._doc.song.pitchChannelCount || this._renderedNoiseChannels != this._doc.song.noiseChannelCount) { for (let y: number = 0; y < this._doc.song.getChannelCount(); y++) { if (y < this._doc.song.pitchChannelCount) { let val: number = (y + 1); this._channelCounts[y].textContent = val + ""; this._channelCounts[y].style.fontSize = (val >= 10) ? "xx-small" : "inherit"; } else if (y < this._doc.song.pitchChannelCount + this._doc.song.noiseChannelCount) { let val: number = (y - this._doc.song.pitchChannelCount + 1); this._channelCounts[y].textContent = val + ""; this._channelCounts[y].style.fontSize = (val >= 10) ? "xx-small" : "inherit"; } else { let val: number = (y - this._doc.song.pitchChannelCount - this._doc.song.noiseChannelCount + 1); this._channelCounts[y].textContent = val + ""; this._channelCounts[y].style.fontSize = (val >= 10) ? "xx-small" : "inherit"; } } this._renderedPitchChannels = this._doc.song.pitchChannelCount; this._renderedNoiseChannels = this._doc.song.noiseChannelCount; this._renderedModChannels = this._doc.song.modChannelCount; } if (this._renderedChannelHeight != channelHeight || this._renderedChannelCount != this._doc.song.getChannelCount()) { this._renderedChannelHeight = channelHeight; this._renderedChannelCount = this._doc.song.getChannelCount(); this._editorHeight = Config.barEditorHeight + this._doc.song.getChannelCount() * channelHeight; this._channelNameDisplay.style.setProperty("display", "none"); this.container.style.height = this._editorHeight + "px"; if (this._renderedChannelHeight < 27) { this._channelNameDisplay.style.setProperty("margin-top", "-2px"); this._channelDropDown.style.setProperty("margin-top", "-4px"); this._channelNameInput.input.style.setProperty("margin-top", "-4px"); } else if (this._renderedChannelHeight < 30) { this._channelNameDisplay.style.setProperty("margin-top", "-1px"); this._channelDropDown.style.setProperty("margin-top", "-3px"); this._channelNameInput.input.style.setProperty("margin-top", "-3px"); } else { this._channelNameDisplay.style.setProperty("margin-top", "0px"); this._channelDropDown.style.setProperty("margin-top", "0px"); this._channelNameInput.input.style.setProperty("margin-top", "-2px"); } } } } //}
the_stack
import { AbsoluteDayOfMonthTransition } from "./AbsoluteDayOfMonthTransition"; import { EwsServiceXmlWriter } from "../../Core/EwsServiceXmlWriter"; import { ExchangeService } from "../../Core/ExchangeService"; import { IOutParam } from "../../Interfaces/IOutParam"; import { RelativeDayOfMonthTransition } from "./RelativeDayOfMonthTransition"; import { ServiceLocalException } from "../../Exceptions/ServiceLocalException"; import { StringHelper } from "../../ExtensionMethods"; import { Strings } from "../../Strings"; import { TimeZoneDefinition } from "./TimeZoneDefinition"; import { TimeZoneInfo } from "../../TimeZoneInfo"; import { TimeZonePeriod } from "./TimeZonePeriod"; import { TimeZoneTransitionGroup } from "./TimeZoneTransitionGroup"; import { TypeContainer } from "../../TypeContainer"; import { XmlAttributeNames } from "../../Core/XmlAttributeNames"; import { XmlElementNames } from "../../Core/XmlElementNames"; import { XmlNamespace } from "../../Enumerations/XmlNamespace"; import { ComplexProperty } from "../ComplexProperty"; /** * @internal Represents the base class for all time zone transitions. */ export class TimeZoneTransition extends ComplexProperty { private static readonly PeriodTarget: string = "Period"; private static readonly GroupTarget: string = "Group"; private timeZoneDefinition: TimeZoneDefinition; private targetPeriod: TimeZonePeriod; private targetGroup: TimeZoneTransitionGroup; /** * @internal Gets the target period of the transition. */ get TargetPeriod(): TimeZonePeriod { return this.targetPeriod; } /** * @internal Gets the target transition group of the transition. */ get TargetGroup(): TimeZoneTransitionGroup { return this.targetGroup; } /** * @internal Initializes a new instance of the **TimeZoneTransition** class. * * @param {TimeZoneDefinition} timeZoneDefinition The time zone definition the transition will belong to. */ constructor(timeZoneDefinition: TimeZoneDefinition); /** * @internal Initializes a new instance of the **TimeZoneTransition** class. * * @param {TimeZoneDefinition} timeZoneDefinition The time zone definition the transition will belong to. * @param {TimeZoneTransitionGroup} targetGroup The transition group the transition will target. */ constructor(timeZoneDefinition: TimeZoneDefinition, targetGroup: TimeZoneTransitionGroup); /** * @internal Initializes a new instance of the **TimeZoneTransition** class. * * @param {TimeZoneDefinition} timeZoneDefinition The time zone definition the transition will belong to. * @param {TimeZonePeriod} targetPeriod The period the transition will target. */ constructor(timeZoneDefinition: TimeZoneDefinition, targetPeriod: TimeZonePeriod); constructor(timeZoneDefinition: TimeZoneDefinition, targetPeriodOrGroup?: TimeZonePeriod | TimeZoneTransitionGroup) { super(); this.timeZoneDefinition = timeZoneDefinition; if (targetPeriodOrGroup instanceof TimeZonePeriod) { this.targetPeriod = targetPeriodOrGroup; } else if (targetPeriodOrGroup instanceof TimeZoneTransitionGroup) { this.targetGroup = targetPeriodOrGroup; } } /** * @internal Creates a time zone period transition of the appropriate type given an XML element name. * * @param {TimeZoneDefinition} timeZoneDefinition The time zone definition to which the transition will belong. * @param {string} xmlElementName The XML element name. * @return {TimeZoneTransition} A TimeZonePeriodTransition instance. */ static Create(timeZoneDefinition: TimeZoneDefinition, xmlElementName: string): TimeZoneTransition { switch (xmlElementName) { case XmlElementNames.AbsoluteDateTransition: return new TypeContainer.AbsoluteDateTransition(timeZoneDefinition); case XmlElementNames.RecurringDayTransition: return new TypeContainer.RelativeDayOfMonthTransition(timeZoneDefinition); case XmlElementNames.RecurringDateTransition: return new TypeContainer.AbsoluteDayOfMonthTransition(timeZoneDefinition); case XmlElementNames.Transition: return new TimeZoneTransition(timeZoneDefinition); default: throw new ServiceLocalException( StringHelper.Format( Strings.UnknownTimeZonePeriodTransitionType, xmlElementName)); } } /** * @internal Creates a time zone transition based on the specified transition time. * * @param {TimeZoneDefinition} timeZoneDefinition The time zone definition that will own the transition. * @param {TimeZonePeriod} targetPeriod The period the transition will target. * @param {TimeZoneInfo.TransitionTime} transitionTime The transition time to initialize from. * @return {TimeZoneTransition} A TimeZoneTransition. */ static CreateTimeZoneTransition(timeZoneDefinition: TimeZoneDefinition, targetPeriod: TimeZonePeriod, transitionTime: TimeZoneInfo.TransitionTime): TimeZoneTransition { var transition: TimeZoneTransition; if (transitionTime.IsFixedDateRule) { transition = new TypeContainer.AbsoluteDayOfMonthTransition(timeZoneDefinition, targetPeriod); } else { transition = new TypeContainer.RelativeDayOfMonthTransition(timeZoneDefinition, targetPeriod); } transition.InitializeFromTransitionTime(transitionTime); return transition; } /** * @internal Creates a time zone transition time. * @virtual * * @return {TimeZoneInfo.TransitionTime} A TimeZoneInfo.TransitionTime. */ CreateTransitionTime(): TimeZoneInfo.TransitionTime { throw new ServiceLocalException(Strings.InvalidOrUnsupportedTimeZoneDefinition); } /** * @internal Gets the name of the XML element. * * @return {string} XML element name. */ GetXmlElementName(): string { return XmlElementNames.Transition; } /** * @internal Initializes this transition based on the specified transition time. * @virtual * * @param {TimeZoneInfo.TransitionTime} transitionTime The transition time to initialize from. */ InitializeFromTransitionTime(transitionTime: TimeZoneInfo.TransitionTime): void { } /** * @internal Loads service object from XML. * * @param {any} jsObject Json Object converted from XML. * @param {ExchangeService} service The service. */ LoadFromXmlJsObject(jsObject: any, service: ExchangeService): void { for (var key in jsObject) { switch (key) { case XmlElementNames.To: let targetKind: string = jsObject[key][XmlAttributeNames.Kind]; let targetId: string = jsObject[key][XmlElementNames.To]; switch (targetKind) { case TimeZoneTransition.PeriodTarget: let targetPeriod: IOutParam<TimeZonePeriod> = { outValue: null } if (!this.timeZoneDefinition.Periods.tryGetValue(targetId, targetPeriod)) { throw new ServiceLocalException( StringHelper.Format( Strings.PeriodNotFound, targetId)); } else { this.targetPeriod = targetPeriod.outValue; } break; case TimeZoneTransition.GroupTarget: let targetGroup: IOutParam<TimeZoneTransitionGroup> = { outValue: null } if (!this.timeZoneDefinition.TransitionGroups.tryGetValue(targetId, targetGroup)) { throw new ServiceLocalException( StringHelper.Format( Strings.TransitionGroupNotFound, targetId)); } else { this.targetGroup = targetGroup.outValue; } break; default: throw new ServiceLocalException(Strings.UnsupportedTimeZonePeriodTransitionTarget); } break; } } } /** * @internal Writes elements to XML. * * @param {EwsServiceXmlWriter} writer The writer. */ WriteElementsToXml(writer: EwsServiceXmlWriter): void { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.To); if (this.targetPeriod != null) { writer.WriteAttributeValue(XmlAttributeNames.Kind, TimeZoneTransition.PeriodTarget); writer.WriteValue(this.targetPeriod.Id, XmlElementNames.To); } else { writer.WriteAttributeValue(XmlAttributeNames.Kind, TimeZoneTransition.GroupTarget); writer.WriteValue(this.targetGroup.Id, XmlElementNames.To); } writer.WriteEndElement(); // To } /** * @internal Writes to XML. * * @param {EwsServiceXmlWriter} writer The writer. */ WriteToXml(writer: EwsServiceXmlWriter): void { super.WriteToXml(writer, this.GetXmlElementName()); } } export module TimeZoneTransition { export var AbsoluteDateTransition; export var AbsoluteDayOfMonthTransition; export var RelativeDayOfMonthTransition; }
the_stack
import { LitElement, html, customElement, property, TemplateResult, css, PropertyValues } from 'lit-element'; import { HomeAssistant, hasAction, ActionHandlerEvent, handleAction, LovelaceCardEditor, getLovelace, } from 'custom-card-helpers'; import { styleMap, StyleInfo } from 'lit-html/directives/style-map'; import 'fa-icons'; import sharedStyle from './sharedStyle'; import './editor'; import { HarmonyCardConfig, HarmonyActivityConfig, HarmonyButtonConfig } from './types'; import { actionHandler } from './action-handler-directive'; import { CARD_VERSION, DEFAULT_BUTTONS } from './const'; import { localize } from './localize/localize'; import * as deepmerge from 'deepmerge'; /* eslint no-console: 0 */ console.info( `%c HARMONY-CARD \n%c ${localize('common.version')} ${CARD_VERSION} `, 'color: orange; font-weight: bold; background: black', 'color: white; font-weight: bold; background: dimgray', ); @customElement('harmony-card') export class HarmonyCard extends LitElement { public static async getConfigElement(): Promise<LovelaceCardEditor> { return document.createElement('harmony-card-editor') as LovelaceCardEditor; } public static getStubConfig(): object { return {}; } // TODO Add any properities that should cause your element to re-render here @property() public hass?: HomeAssistant; @property() private _config?: HarmonyCardConfig; public setConfig(config: HarmonyCardConfig): void { // TODO Check for required fields and that they are of the proper format if (!config || config.show_error) { throw new Error(localize('common.invalid_configuration')); } if (!config.entity || config.entity.split('.')[0] !== 'remote') { throw new Error('Specify an entity from within the remote domain for a harmony hub.'); } if (config.test_gui) { getLovelace().setEditMode(true); } this._config = { name: '', ...config, }; } protected preventBubbling(e) { // e.preventDefault(); e.stopPropagation(); e.cancelBubble = true; } protected deviceCommand(e, device: string | undefined, cmd: string) { this.preventBubbling(e); if (null == device) { return; } this.hass?.callService("remote", "send_command", { entity_id: this._config?.entity, command: cmd, device: device }); } protected harmonyCommand(e, activity: string) { this.preventBubbling(e); if (null == activity || activity == "off" || activity == 'turn_off') { this.hass?.callService("remote", "turn_off", { entity_id: this._config?.entity }); } else { this.hass?.callService("remote", "turn_on", { entity_id: this._config?.entity, activity: activity }); } } protected volumeCommand(e, command: string, attributes?: any) { this.preventBubbling(e); if (this._config?.volume_entity) { var baseAttributes = { entity_id: this._config?.volume_entity }; this.hass?.callService("media_player", command, Object.assign(baseAttributes, attributes || {})); } } protected shouldUpdate(changedProps: PropertyValues): boolean { // has config changes if (changedProps.has('config')) { return true; } return this.hasEntityChanged(this, changedProps, 'entity'); } // Check if Entity changed private hasEntityChanged( element: any, changedProps: PropertyValues, entityName ): boolean { if (element._config!.entity) { const oldHass = changedProps.get('hass') as HomeAssistant | undefined; if (oldHass) { // check if state changed if (oldHass.states[element._config![entityName]] !== element.hass!.states[element._config![entityName]]) { return true; } } return true; } else { return false; } } protected render(): TemplateResult | void { if (!this._config || !this.hass) { return html``; } // TODO Check for stateObj or other necessary things and render a warning if missing if (this._config.show_warning) { return html` <ha-card> <div class="warning">${localize('common.show_warning')}</div> </ha-card> `; } var hubState = this.hass.states[this._config.entity]; var hubPowerState = hubState.state; var currentActivity = hubState.attributes.current_activity; var currentActivityConfig = this._config.activities.find(activity => activity.name === currentActivity); var currentDevice = currentActivityConfig?.device; var buttonConfig = this.computeButtonConfig(this._config, currentActivityConfig); return html` <ha-card style=${this.computeStyles()} .header=${this._config.name} @action=${this._handleAction} .actionHandler=${actionHandler({ hasHold: hasAction(this._config.hold_action), hasDoubleClick: hasAction(this._config.double_tap_action), })} tabindex="0" aria-label=${`Harmony: ${this._config.entity}`} > <div class="card-content"> ${this.renderActivityButtons(this._config, hubPowerState, currentActivity)} ${this.renderVolumeControls(this.hass, this._config, buttonConfig, currentActivityConfig)} ${this.renderKeyPad(this._config, buttonConfig, currentActivityConfig, currentDevice)} <div class="play-pause"> ${this.renderIconButton(buttonConfig['skip_back'], currentDevice)} ${this.renderIconButton(buttonConfig['play'], currentDevice)} ${this.renderIconButton(buttonConfig['pause'], currentDevice)} ${this.renderIconButton(buttonConfig['skip_forward'], currentDevice)} </div> <div class="remote"> ${this.renderIconButton(buttonConfig['dpad_left'], currentDevice, { 'grid-column': '1', 'grid-row': '2' })} ${this.renderIconButton(buttonConfig['dpad_right'], currentDevice, { 'grid-column': '3', 'grid-row': '2' })} ${this.renderIconButton(buttonConfig['dpad_up'], currentDevice, { 'grid-column': '2', 'grid-row': '1' })} ${this.renderIconButton(buttonConfig['dpad_down'], currentDevice, { 'grid-column': '2', 'grid-row': '3' })} ${this.renderIconButton(buttonConfig['dpad_center'], currentDevice, { 'grid-column': '2', 'grid-row': '2' })} </div> <div class="xbox-buttons"> ${this.renderIconButton(buttonConfig['xbox'], currentDevice, { 'grid-column': '1', 'grid-row': '2' })} ${this.renderIconButton(buttonConfig['back'], currentDevice, { 'grid-column': '2', 'grid-row': '2' })} ${this.renderIconButton(buttonConfig['a'], currentDevice, { 'grid-column': '4', 'grid-row': '2' })} ${this.renderIconButton(buttonConfig['b'], currentDevice, { 'grid-column': '5', 'grid-row': '2' })} ${this.renderIconButton(buttonConfig['x'], currentDevice, { 'grid-column': '6', 'grid-row': '2' })} ${this.renderIconButton(buttonConfig['y'], currentDevice, { 'grid-column': '7', 'grid-row': '2' })} </div> </div> </ha-card> `; } private renderActivityButtons(config: HarmonyCardConfig, hubPowerState: string, currentActivity: string) { if (typeof config.hide_activities !== 'undefined' && config.hide_activities) { return html``; } const iconClass = config.show_activities_icons ? 'activities-icons' : ''; return html` <div class="activities ${iconClass}"> ${this.renderActivityButton(hubPowerState === 'off', 'turn_off', 'off', config.show_activities_icons, 'mdi:power')} ${config.activities.map( activity => html` ${this.renderActivityButton( currentActivity === activity.name, activity.name, activity.name, config.show_activities_icons, activity.icon, )} `, )} </div> `; } private renderActivityButton(outlined: boolean, command: string, label: string, showIcon = false, icon?: string,): TemplateResult { return html` ${showIcon && icon ? html` <ha-icon-button icon="${icon}" ?outlined="${outlined}" @click="${e => this.harmonyCommand(e, command)}" @touchstart="${e => this.preventBubbling(e)}" ></ha-icon-button> ` : html` <mwc-button ?outlined="${outlined}" label="${label}" @click="${e => this.harmonyCommand(e, command)}" @touchstart="${e => this.preventBubbling(e)}" ></mwc-button> `} `; } private renderKeyPad(config: HarmonyCardConfig, buttonConfig: { [key: string]: HarmonyButtonConfig }, currentActivityConfig: HarmonyActivityConfig | undefined, device?: string) { if (typeof currentActivityConfig?.hide_keyPad != 'undefined' && !currentActivityConfig?.hide_keyPad) { return this.renderKeyPadButton(buttonConfig, device); } else if (typeof config.hide_keyPad != 'undefined' && !config.hide_keyPad) { return this.renderKeyPadButton(buttonConfig, device); } return html``; } private renderKeyPadButton(buttonConfig: { [key: string]: HarmonyButtonConfig }, device?: string) { return html` <div class="remote"> ${this.renderIconButton(buttonConfig['1'], device, { 'grid-column': '1', 'grid-row': '1' })} ${this.renderIconButton(buttonConfig['2'], device, { 'grid-column': '2', 'grid-row': '1' })} ${this.renderIconButton(buttonConfig['3'], device, { 'grid-column': '3', 'grid-row': '1' })} ${this.renderIconButton(buttonConfig['4'], device, { 'grid-column': '1', 'grid-row': '2' })} ${this.renderIconButton(buttonConfig['5'], device, { 'grid-column': '2', 'grid-row': '2' })} ${this.renderIconButton(buttonConfig['6'], device, { 'grid-column': '3', 'grid-row': '2' })} ${this.renderIconButton(buttonConfig['7'], device, { 'grid-column': '1', 'grid-row': '3' })} ${this.renderIconButton(buttonConfig['8'], device, { 'grid-column': '2', 'grid-row': '3' })} ${this.renderIconButton(buttonConfig['9'], device, { 'grid-column': '3', 'grid-row': '3' })} ${this.renderIconButton(buttonConfig['0'], device, { 'grid-column': '2', 'grid-row': '4' })} </div> `; } private renderIconButton(buttonConfig: HarmonyButtonConfig, device?: string, styles?: StyleInfo) { if (buttonConfig.hide === true) { return html``; } var buttonStyles = Object.assign(styles || {}, { color: buttonConfig.color }); return html` <ha-icon-button icon="${buttonConfig.icon}" style="${styleMap(buttonStyles)}" @click="${e => this.deviceCommand(e, buttonConfig.device || device, buttonConfig.command || '')}" @touchstart="${e => this.preventBubbling(e)}"> </ha-icon-button> `; } private renderVolumeControls(hass: HomeAssistant, config: HarmonyCardConfig, buttonConfig: { [key: string]: HarmonyButtonConfig }, currentActivityConfig: HarmonyActivityConfig | undefined) { if (currentActivityConfig?.volume_entity) { return this.renderMediaPlayerVolumeControls(hass, currentActivityConfig?.volume_entity, buttonConfig); } else if (currentActivityConfig?.volume_device) { return this.renderDeviceVolumeControls(currentActivityConfig?.volume_device, buttonConfig); } else if (config.volume_entity) { return this.renderMediaPlayerVolumeControls(hass, config.volume_entity, buttonConfig); } else if (config.volume_device) { return this.renderDeviceVolumeControls(config.volume_device, buttonConfig); } return html``; } private renderMediaPlayerVolumeControls(hass: HomeAssistant, volumeMediaPlayer: string, buttonConfig: { [key: string]: HarmonyButtonConfig }) { var volume_state = hass.states[volumeMediaPlayer]; var volume = volume_state.attributes.volume_level; var muted = volume_state.attributes.is_volume_muted; var volumeDownStyle = Object.assign({} as StyleInfo, { color: buttonConfig['volume_down'].color }); var volumeUpStyle = Object.assign({} as StyleInfo, { color: buttonConfig['volume_up'].color }); var volumeMuteStyle = Object.assign({} as StyleInfo, { color: buttonConfig['volume_mute'].color }); return html` <div class="volume-controls"> <ha-icon-button style="${styleMap(volumeDownStyle)}" icon="${buttonConfig['volume_down'].icon}" @click="${e => this.volumeCommand(e, 'volume_down')}" @touchstart="${e => this.preventBubbling(e)}"></ha-icon-button> <ha-icon-button style="${styleMap(volumeUpStyle)}" icon="${buttonConfig['volume_up'].icon}" @click="${e => this.volumeCommand(e, 'volume_up')}" @touchstart="${e => this.preventBubbling(e)}"></ha-icon-button> <paper-slider @change=${e => this.volumeCommand(e, 'volume_set', { volume_level: e.target.value / 100 })} @click=${e => e.stopPropagation()} @touchstart="${e => this.preventBubbling(e)}" ?disabled=${muted} min=0 max=100 value=${volume * 100} dir=${'ltr'} ignore-bar-touch pin> </paper-slider> <ha-icon-button style="${styleMap(volumeMuteStyle)}" icon="${buttonConfig['volume_mute'].icon}" @click="${e => this.volumeCommand(e, 'volume_mute', { is_volume_muted: true })}" @touchstart="${e => this.preventBubbling(e)}"></ha-icon-button> </div>`; } private renderDeviceVolumeControls(device: string, buttonConfig: { [key: string]: HarmonyButtonConfig }) { return html` <div class="volume-controls"> ${this.renderIconButton(buttonConfig['volume_down'], device)} ${this.renderIconButton(buttonConfig['volume_up'], device)} ${this.renderIconButton(buttonConfig['volume_mute'], device)} </div>`; } private _handleAction(ev: ActionHandlerEvent): void { if (this.hass && this._config && ev.detail.action) { handleAction(this, this.hass, this._config, ev.detail.action); } } private computeStyles() { var scale = this._config?.scale || 1; return styleMap({ '--mmp-unit': `${40 * scale}px`, '--mdc-icon-size': `${24 * scale}px` }); } private computeButtonConfig(config: HarmonyCardConfig, currentActivityConfig?: HarmonyActivityConfig): { [key: string]: HarmonyButtonConfig } { // overwrite in the card button config let buttonConfig = deepmerge.default(DEFAULT_BUTTONS, config.buttons || {}); // layer in the activity button config if (currentActivityConfig) { buttonConfig = deepmerge.default(buttonConfig, currentActivityConfig.buttons || {}); } return buttonConfig; } static get styles() { return [ css` .warning { display: block; color: black; background-color: #fce588; padding: 8px; } div { font-size:16px; }`, sharedStyle ]; } }
the_stack
export const ConsoleLogs = { 1368866505: '()', 1309416733: '(int)', 4122065833: '(uint)', 1093685164: '(string)', 843419373: '(bool)', 741264322: '(address)', 199720790: '(bytes)', 1847107880: '(bytes1)', 3921027734: '(bytes2)', 763578662: '(bytes3)', 3764340945: '(bytes4)', 2793701517: '(bytes5)', 2927928721: '(bytes6)', 1322614312: '(bytes7)', 1334060334: '(bytes8)', 2428341456: '(bytes9)', 20780939: '(bytes10)', 67127854: '(bytes11)', 2258660029: '(bytes12)', 2488442420: '(bytes13)', 2456219775: '(bytes14)', 3667227872: '(bytes15)', 1717330180: '(bytes16)', 866084666: '(bytes17)', 3302112666: '(bytes18)', 1584093747: '(bytes19)', 1367925737: '(bytes20)', 3923391840: '(bytes21)', 3589990556: '(bytes22)', 2879508237: '(bytes23)', 4055063348: '(bytes24)', 193248344: '(bytes25)', 4172368369: '(bytes26)', 976705501: '(bytes27)', 3358255854: '(bytes28)', 1265222613: '(bytes29)', 3994207469: '(bytes30)', 3263516050: '(bytes31)', 666357637: '(bytes32)', 1812949376: '(uint,uint)', 262402885: '(uint,string)', 510514412: '(uint,bool)', 1491830284: '(uint,address)', 2534451664: '(string,uint)', 1264337527: '(string,string)', 3283441205: '(string,bool)', 832238387: '(string,address)', 910912146: '(bool,uint)', 2414527781: '(bool,string)', 705760899: '(bool,bool)', 2235320393: '(bool,address)', 574869411: '(address,uint)', 1973388987: '(address,string)', 1974863315: '(address,bool)', 3673216170: '(address,address)', 3884059252: '(uint,uint,uint)', 2104037094: '(uint,uint,string)', 1733758967: '(uint,uint,bool)', 3191032091: '(uint,uint,address)', 1533929535: '(uint,string,uint)', 1062716053: '(uint,string,string)', 1185403086: '(uint,string,bool)', 529592906: '(uint,string,address)', 1515034914: '(uint,bool,uint)', 2332955902: '(uint,bool,string)', 3587091680: '(uint,bool,bool)', 1112473535: '(uint,bool,address)', 2286109610: '(uint,address,uint)', 3464692859: '(uint,address,string)', 2060456590: '(uint,address,bool)', 2104993307: '(uint,address,address)', 2526862595: '(string,uint,uint)', 2750793529: '(string,uint,string)', 4043501061: '(string,uint,bool)', 3817119609: '(string,uint,address)', 4083337817: '(string,string,uint)', 753761519: '(string,string,string)', 2967534005: '(string,string,bool)', 2515337621: '(string,string,address)', 689682896: '(string,bool,uint)', 3801674877: '(string,bool,string)', 2232122070: '(string,bool,bool)', 2469116728: '(string,bool,address)', 130552343: '(string,address,uint)', 3773410639: '(string,address,string)', 3374145236: '(string,address,bool)', 4243355104: '(string,address,address)', 995886048: '(bool,uint,uint)', 3359211184: '(bool,uint,string)', 464374251: '(bool,uint,bool)', 3302110471: '(bool,uint,address)', 3224906412: '(bool,string,uint)', 2960557183: '(bool,string,string)', 3686056519: '(bool,string,bool)', 2509355347: '(bool,string,address)', 2954061243: '(bool,bool,uint)', 626391622: '(bool,bool,string)', 1349555864: '(bool,bool,bool)', 276362893: '(bool,bool,address)', 3950005167: '(bool,address,uint)', 3734671984: '(bool,address,string)', 415876934: '(bool,address,bool)', 3530962535: '(bool,address,address)', 2273710942: '(address,uint,uint)', 3136907337: '(address,uint,string)', 3846889796: '(address,uint,bool)', 2548867988: '(address,uint,address)', 484110986: '(address,string,uint)', 4218888805: '(address,string,string)', 3473018801: '(address,string,bool)', 4035396840: '(address,string,address)', 742821141: '(address,bool,uint)', 555898316: '(address,bool,string)', 3951234194: '(address,bool,bool)', 4044790253: '(address,bool,address)', 1815506290: '(address,address,uint)', 7426238: '(address,address,string)', 4070990470: '(address,address,bool)', 25986242: '(address,address,address)', 1554033982: '(uint,uint,uint,uint)', 2024634892: '(uint,uint,uint,string)', 1683143115: '(uint,uint,uint,bool)', 3766828905: '(uint,uint,uint,address)', 949229117: '(uint,uint,string,uint)', 2080582194: '(uint,uint,string,string)', 2989403910: '(uint,uint,string,bool)', 1127384482: '(uint,uint,string,address)', 1818524812: '(uint,uint,bool,uint)', 4024028142: '(uint,uint,bool,string)', 2495495089: '(uint,uint,bool,bool)', 3776410703: '(uint,uint,bool,address)', 1628154048: '(uint,uint,address,uint)', 3600994782: '(uint,uint,address,string)', 2833785006: '(uint,uint,address,bool)', 3398671136: '(uint,uint,address,address)', 3221501959: '(uint,string,uint,uint)', 2730232985: '(uint,string,uint,string)', 2270850606: '(uint,string,uint,bool)', 2877020669: '(uint,string,uint,address)', 1995203422: '(uint,string,string,uint)', 1474103825: '(uint,string,string,string)', 310782872: '(uint,string,string,bool)', 3432549024: '(uint,string,string,address)', 2763295359: '(uint,string,bool,uint)', 2370346144: '(uint,string,bool,string)', 1371286465: '(uint,string,bool,bool)', 2037328032: '(uint,string,bool,address)', 2565338099: '(uint,string,address,uint)', 4170733439: '(uint,string,address,string)', 4181720887: '(uint,string,address,bool)', 2141537675: '(uint,string,address,address)', 1451396516: '(uint,bool,uint,uint)', 3906845782: '(uint,bool,uint,string)', 3534472445: '(uint,bool,uint,bool)', 1329595790: '(uint,bool,uint,address)', 2438978344: '(uint,bool,string,uint)', 2754870525: '(uint,bool,string,string)', 879671495: '(uint,bool,string,bool)', 1231956916: '(uint,bool,string,address)', 3173363033: '(uint,bool,bool,uint)', 831186331: '(uint,bool,bool,string)', 1315722005: '(uint,bool,bool,bool)', 1392910941: '(uint,bool,bool,address)', 1102442299: '(uint,bool,address,uint)', 2721084958: '(uint,bool,address,string)', 2449150530: '(uint,bool,address,bool)', 2263728396: '(uint,bool,address,address)', 3399106228: '(uint,address,uint,uint)', 1054063912: '(uint,address,uint,string)', 435581801: '(uint,address,uint,bool)', 4256361684: '(uint,address,uint,address)', 2697204968: '(uint,address,string,uint)', 2373420580: '(uint,address,string,string)', 581204390: '(uint,address,string,bool)', 3420819197: '(uint,address,string,address)', 2064181483: '(uint,address,bool,uint)', 1676730946: '(uint,address,bool,string)', 2116501773: '(uint,address,bool,bool)', 3056677012: '(uint,address,bool,address)', 2587672470: '(uint,address,address,uint)', 2034490470: '(uint,address,address,string)', 22350596: '(uint,address,address,bool)', 1430734329: '(uint,address,address,address)', 149837414: '(string,uint,uint,uint)', 2773406909: '(string,uint,uint,string)', 4147936829: '(string,uint,uint,bool)', 3201771711: '(string,uint,uint,address)', 2697245221: '(string,uint,string,uint)', 1821956834: '(string,uint,string,string)', 3919545039: '(string,uint,string,bool)', 3144824297: '(string,uint,string,address)', 1427009269: '(string,uint,bool,uint)', 1993105508: '(string,uint,bool,string)', 3816813520: '(string,uint,bool,bool)', 3847527825: '(string,uint,bool,address)', 1481210622: '(string,uint,address,uint)', 844415720: '(string,uint,address,string)', 285649143: '(string,uint,address,bool)', 3939013249: '(string,uint,address,address)', 3587119056: '(string,string,uint,uint)', 2366909661: '(string,string,uint,string)', 3864418506: '(string,string,uint,bool)', 1565476480: '(string,string,uint,address)', 2681211381: '(string,string,string,uint)', 3731419658: '(string,string,string,string)', 739726573: '(string,string,string,bool)', 1834430276: '(string,string,string,address)', 2256636538: '(string,string,bool,uint)', 1585754346: '(string,string,bool,string)', 1081628777: '(string,string,bool,bool)', 3279013851: '(string,string,bool,address)', 1250010474: '(string,string,address,uint)', 3944480640: '(string,string,address,string)', 1556958775: '(string,string,address,bool)', 1134328815: '(string,string,address,address)', 1572859960: '(string,bool,uint,uint)', 1119461927: '(string,bool,uint,string)', 1019590099: '(string,bool,uint,bool)', 1909687565: '(string,bool,uint,address)', 885731469: '(string,bool,string,uint)', 2821114603: '(string,bool,string,string)', 1066037277: '(string,bool,string,bool)', 3764542249: '(string,bool,string,address)', 2155164136: '(string,bool,bool,uint)', 2636305885: '(string,bool,bool,string)', 2304440517: '(string,bool,bool,bool)', 1905304873: '(string,bool,bool,address)', 685723286: '(string,bool,address,uint)', 764294052: '(string,bool,address,string)', 2508990662: '(string,bool,address,bool)', 870964509: '(string,bool,address,address)', 3668153533: '(string,address,uint,uint)', 1280700980: '(string,address,uint,string)', 1522647356: '(string,address,uint,bool)', 2741431424: '(string,address,uint,address)', 2405583849: '(string,address,string,uint)', 609847026: '(string,address,string,string)', 1595265676: '(string,address,string,bool)', 2864486961: '(string,address,string,address)', 3318856587: '(string,address,bool,uint)', 72663161: '(string,address,bool,string)', 2038975531: '(string,address,bool,bool)', 573965245: '(string,address,bool,address)', 1857524797: '(string,address,address,uint)', 2148146279: '(string,address,address,string)', 3047013728: '(string,address,address,bool)', 3985582326: '(string,address,address,address)', 853517604: '(bool,uint,uint,uint)', 3657852616: '(bool,uint,uint,string)', 2753397214: '(bool,uint,uint,bool)', 4049711649: '(bool,uint,uint,address)', 1098907931: '(bool,uint,string,uint)', 3542771016: '(bool,uint,string,string)', 2446522387: '(bool,uint,string,bool)', 2781285673: '(bool,uint,string,address)', 3554563475: '(bool,uint,bool,uint)', 3067439572: '(bool,uint,bool,string)', 2650928961: '(bool,uint,bool,bool)', 1114097656: '(bool,uint,bool,address)', 3399820138: '(bool,uint,address,uint)', 403247937: '(bool,uint,address,string)', 1705899016: '(bool,uint,address,bool)', 2318373034: '(bool,uint,address,address)', 2387273838: '(bool,string,uint,uint)', 2007084013: '(bool,string,uint,string)', 549177775: '(bool,string,uint,bool)', 1529002296: '(bool,string,uint,address)', 1574643090: '(bool,string,string,uint)', 392356650: '(bool,string,string,string)', 508266469: '(bool,string,string,bool)', 2547225816: '(bool,string,string,address)', 2372902053: '(bool,string,bool,uint)', 1211958294: '(bool,string,bool,string)', 3697185627: '(bool,string,bool,bool)', 1401816747: '(bool,string,bool,address)', 453743963: '(bool,string,address,uint)', 316065672: '(bool,string,address,string)', 1842623690: '(bool,string,address,bool)', 724244700: '(bool,string,address,address)', 1181212302: '(bool,bool,uint,uint)', 1348569399: '(bool,bool,uint,string)', 2874982852: '(bool,bool,uint,bool)', 201299213: '(bool,bool,uint,address)', 395003525: '(bool,bool,string,uint)', 1830717265: '(bool,bool,string,string)', 3092715066: '(bool,bool,string,bool)', 4188875657: '(bool,bool,string,address)', 3259532109: '(bool,bool,bool,uint)', 719587540: '(bool,bool,bool,string)', 992632032: '(bool,bool,bool,bool)', 2352126746: '(bool,bool,bool,address)', 1620281063: '(bool,bool,address,uint)', 2695133539: '(bool,bool,address,string)', 3231908568: '(bool,bool,address,bool)', 4102557348: '(bool,bool,address,address)', 2617143996: '(bool,address,uint,uint)', 2691192883: '(bool,address,uint,string)', 4002252402: '(bool,address,uint,bool)', 1760647349: '(bool,address,uint,address)', 194640930: '(bool,address,string,uint)', 2805734838: '(bool,address,string,string)', 3804222987: '(bool,address,string,bool)', 1870422078: '(bool,address,string,address)', 1287000017: '(bool,address,bool,uint)', 1248250676: '(bool,address,bool,string)', 1788626827: '(bool,address,bool,bool)', 474063670: '(bool,address,bool,address)', 1384430956: '(bool,address,address,uint)', 3625099623: '(bool,address,address,string)', 1180699616: '(bool,address,address,bool)', 487903233: '(bool,address,address,address)', 1024368100: '(address,uint,uint,uint)', 2301889963: '(address,uint,uint,string)', 3964381346: '(address,uint,uint,bool)', 519451700: '(address,uint,uint,address)', 4111650715: '(address,uint,string,uint)', 2119616147: '(address,uint,string,string)', 2751614737: '(address,uint,string,bool)', 3698927108: '(address,uint,string,address)', 1770996626: '(address,uint,bool,uint)', 2391690869: '(address,uint,bool,string)', 4272018778: '(address,uint,bool,bool)', 602229106: '(address,uint,bool,address)', 2782496616: '(address,uint,address,uint)', 1567749022: '(address,uint,address,string)', 4051804649: '(address,uint,address,bool)', 3961816175: '(address,uint,address,address)', 2764647008: '(address,string,uint,uint)', 1561552329: '(address,string,uint,string)', 2116357467: '(address,string,uint,bool)', 3755464715: '(address,string,uint,address)', 2706362425: '(address,string,string,uint)', 1560462603: '(address,string,string,string)', 900007711: '(address,string,string,bool)', 2689478535: '(address,string,string,address)', 3877655068: '(address,string,bool,uint)', 3154862590: '(address,string,bool,string)', 1595759775: '(address,string,bool,bool)', 542667202: '(address,string,bool,address)', 2350461865: '(address,string,address,uint)', 4158874181: '(address,string,address,string)', 233909110: '(address,string,address,bool)', 221706784: '(address,string,address,address)', 3255869470: '(address,bool,uint,uint)', 2606272204: '(address,bool,uint,string)', 2244855215: '(address,bool,uint,bool)', 227337758: '(address,bool,uint,address)', 2652011374: '(address,bool,string,uint)', 1197235251: '(address,bool,string,string)', 1353532957: '(address,bool,string,bool)', 436029782: '(address,bool,string,address)', 3484780374: '(address,bool,bool,uint)', 3754205928: '(address,bool,bool,string)', 3401856121: '(address,bool,bool,bool)', 3476636805: '(address,bool,bool,address)', 3698398930: '(address,bool,address,uint)', 769095910: '(address,bool,address,string)', 2801077007: '(address,bool,address,bool)', 1711502813: '(address,bool,address,address)', 1425929188: '(address,address,uint,uint)', 2647731885: '(address,address,uint,string)', 3270936812: '(address,address,uint,bool)', 3603321462: '(address,address,uint,address)', 69767936: '(address,address,string,uint)', 566079269: '(address,address,string,string)', 1863997774: '(address,address,string,bool)', 2406706454: '(address,address,string,address)', 2513854225: '(address,address,bool,uint)', 2858762440: '(address,address,bool,string)', 752096074: '(address,address,bool,bool)', 2669396846: '(address,address,bool,address)', 3982404743: '(address,address,address,uint)', 4161329696: '(address,address,address,string)', 238520724: '(address,address,address,bool)', 1717301556: '(address,address,address,address)' }
the_stack
import { $Object, } from '../types/object.js'; import { $Function, $BuiltinFunction, $GetPrototypeFromConstructor, } from '../types/function.js'; import { ExecutionContext, Realm, } from '../realm.js'; import { $AnyNonEmpty, $AnyNonEmptyNonError, $AnyObject, CompletionType, $Any, } from '../types/_shared.js'; import { $Undefined, } from '../types/undefined.js'; import { $IteratorRecord, $GetIterator, $IteratorStep, $IteratorValue, $IteratorClose, } from './iteration.js'; import { $Error, $TypeError, } from '../types/error.js'; import { $Call, $Construct, $Invoke, $SpeciesConstructor, } from '../operations.js'; import { $List, } from '../types/list.js'; import { Job, } from '../job.js'; import { $$ESModuleOrScript, } from '../ast/modules.js'; import { $Empty, } from '../types/empty.js'; import { $FunctionPrototype, } from './function.js'; import { $ValueRecord, $GetSpecies, } from './_shared.js'; import { $CreateArrayFromList, } from '../exotics/array.js'; import { $String, } from '../types/string.js'; // http://www.ecma-international.org/ecma-262/#sec-promise-abstract-operations // #region 25.6.1 Promise Abstract Operation // http://www.ecma-international.org/ecma-262/#sec-promisecapability-records // 25.6.1.1 PromiseCapability Records export class $PromiseCapability { public '[[Promise]]': $PromiseInstance | $Undefined; public '[[Resolve]]': $Function | $Undefined; public '[[Reject]]': $Function | $Undefined; public get isUndefined(): false { return false; } public get isAbrupt(): false { return false; } public constructor( promise: $PromiseInstance | $Undefined, resolve: $Function | $Undefined, reject: $Function | $Undefined, ) { this['[[Promise]]'] = promise; this['[[Resolve]]'] = resolve; this['[[Reject]]'] = reject; } } // http://www.ecma-international.org/ecma-262/#sec-ifabruptrejectpromise // 25.6.1.1.1 IfAbruptRejectPromise ( value , capability ) export function $IfAbruptRejectPromise( ctx: ExecutionContext, value: $Any | $IteratorRecord, capability: $PromiseCapability, ): $Any | $IteratorRecord { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. If value is an abrupt completion, then if (value.isAbrupt) { // 1. a. Perform ? Call(capability.[[Reject]], undefined, « value.[[Value]] »). const $CallResult = $Call(ctx, capability['[[Reject]]'], intrinsics.undefined, new $List(value)); if ($CallResult.isAbrupt) { return $CallResult; } // 1. b. Return capability.[[Promise]]. return capability['[[Promise]]']; } // 2. Else if value is a Completion Record, set value to value.[[Value]]. return value; } export const enum PromiseReactionType { Fulfill = 1, Reject = 2, } // http://www.ecma-international.org/ecma-262/#sec-promisereaction-records // 25.6.1.2 PromiseReaction Records export class $PromiseReaction { public readonly '[[Capability]]': $PromiseCapability | $Undefined; public readonly '[[Type]]': PromiseReactionType; public readonly '[[Handler]]': $Function | $Undefined; public constructor( capability: $PromiseCapability | $Undefined, type: PromiseReactionType, handler: $Function | $Undefined, ) { this['[[Capability]]'] = capability; this['[[Type]]'] = type; this['[[Handler]]'] = handler; } public is(other: $PromiseReaction): boolean { return this === other; } } // http://www.ecma-international.org/ecma-262/#sec-createresolvingfunctions // 25.6.1.3 CreateResolvingFunctions ( promise ) export class $PromiseResolvingFunctions { public readonly '[[Resolve]]': $PromiseResolveFunction; public readonly '[[Reject]]': $PromiseRejectFunction; public constructor( realm: Realm, promise: $PromiseInstance, ) { // 1. Let alreadyResolved be a new Record { [[Value]]: false }. const alreadyResolved = new $ValueRecord<boolean>(false); // 2. Let stepsResolve be the algorithm steps defined in Promise Resolve Functions (25.6.1.3.2). // 3. Let resolve be CreateBuiltinFunction(stepsResolve, « [[Promise]], [[AlreadyResolved]] »). // 4. Set resolve.[[Promise]] to promise. // 5. Set resolve.[[AlreadyResolved]] to alreadyResolved. this['[[Resolve]]'] = new $PromiseResolveFunction(realm, promise, alreadyResolved); // 6. Let stepsReject be the algorithm steps defined in Promise Reject Functions (25.6.1.3.1). // 7. Let reject be CreateBuiltinFunction(stepsReject, « [[Promise]], [[AlreadyResolved]] »). // 8. Set reject.[[Promise]] to promise. // 9. Set reject.[[AlreadyResolved]] to alreadyResolved. this['[[Reject]]'] = new $PromiseRejectFunction(realm, promise, alreadyResolved); // 10. Return a new Record { [[Resolve]]: resolve, [[Reject]]: reject }. } } // http://www.ecma-international.org/ecma-262/#sec-promise-reject-functions // 25.6.1.3.1 Promise Reject Functions export class $PromiseRejectFunction extends $BuiltinFunction<'PromiseRejectFunction'> { public '[[Promise]]': $PromiseInstance; public '[[AlreadyResolved]]': $ValueRecord<boolean>; public constructor( realm: Realm, promise: $PromiseInstance, alreadyResolved: $ValueRecord<boolean>, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, 'PromiseRejectFunction', intrinsics['%FunctionPrototype%']); this['[[Promise]]'] = promise; this['[[AlreadyResolved]]'] = alreadyResolved; } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [reason]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (reason === void 0) { reason = intrinsics.undefined; } // 1. Let F be the active function object. const F = this; // 2. Assert: F has a [[Promise]] internal slot whose value is an Object. // 3. Let promise be F.[[Promise]]. const promise = F['[[Promise]]']; // 4. Let alreadyResolved be F.[[AlreadyResolved]]. const alreadyResolved = F['[[AlreadyResolved]]']; // 5. If alreadyResolved.[[Value]] is true, return undefined. if (alreadyResolved['[[Value]]']) { return intrinsics.undefined; } // 6. Set alreadyResolved.[[Value]] to true. alreadyResolved['[[Value]]'] = true; // 7. Return RejectPromise(promise, reason). return $RejectPromise(ctx, promise, reason); } } // http://www.ecma-international.org/ecma-262/#sec-promise-resolve-functions // 25.6.1.3.2 Promise Resolve Functions export class $PromiseResolveFunction extends $BuiltinFunction<'PromiseResolveFunction'> { public '[[Promise]]': $PromiseInstance; public '[[AlreadyResolved]]': $ValueRecord<boolean>; public constructor( realm: Realm, promise: $PromiseInstance, alreadyResolved: $ValueRecord<boolean>, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, 'PromiseResolveFunction', intrinsics['%FunctionPrototype%']); this['[[Promise]]'] = promise; this['[[AlreadyResolved]]'] = alreadyResolved; } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [resolution]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (resolution === void 0) { resolution = intrinsics.undefined; } // 1. Let F be the active function object. const F = this; // 2. Assert: F has a [[Promise]] internal slot whose value is an Object. // 3. Let promise be F.[[Promise]]. const promise = F['[[Promise]]']; // 4. Let alreadyResolved be F.[[AlreadyResolved]]. const alreadyResolved = F['[[AlreadyResolved]]']; // 5. If alreadyResolved.[[Value]] is true, return undefined. if (alreadyResolved['[[Value]]']) { return intrinsics.undefined; } // 6. Set alreadyResolved.[[Value]] to true. alreadyResolved['[[Value]]'] = true; // 7. If SameValue(resolution, promise) is true, then if (resolution.is(promise)) { // 7. a. Let selfResolutionError be a newly created TypeError object. const selfResolutionError = new $TypeError(realm, `Failed to resolve self`); // ? // 7. b. Return RejectPromise(promise, selfResolutionError). return $RejectPromise(ctx, promise, selfResolutionError); } // 8. If Type(resolution) is not Object, then if (!resolution.isObject) { // 8. a. Return FulfillPromise(promise, resolution). return $FulfillPromise(ctx, promise, resolution); } // 9. Let then be Get(resolution, "then"). const then = resolution['[[Get]]'](ctx, intrinsics.then, resolution); // 10. If then is an abrupt completion, then if (then.isAbrupt) { // 10. a. Return RejectPromise(promise, then.[[Value]]). return $RejectPromise(ctx, promise, then); } // 11. Let thenAction be then.[[Value]]. // 12. If IsCallable(thenAction) is false, then if (!then.isFunction) { // 12. a. Return FulfillPromise(promise, resolution). return $FulfillPromise(ctx, promise, resolution); } // 13. Perform EnqueueJob("PromiseJobs", PromiseResolveThenableJob, « promise, resolution, thenAction »). const mos = ctx.ScriptOrModule; if (mos.isNull) { throw new Error(`No ScriptOrModule found in this realm`); } realm.PromiseJobs.EnqueueJob(ctx, new PromiseResolveThenableJob(realm, mos, promise, resolution, then)); // 14. Return undefined. return new $Undefined(realm); } } // http://www.ecma-international.org/ecma-262/#sec-fulfillpromise // 25.6.1.4 FulfillPromise ( promise , value ) export function $FulfillPromise( ctx: ExecutionContext, promise: $PromiseInstance, value: $AnyNonEmpty, ) { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Assert: The value of promise.[[PromiseState]] is "pending". // 2. Let reactions be promise.[[PromiseFulfillReactions]]. const reactions = promise['[[PromiseFulfillReactions]]']!; // 3. Set promise.[[PromiseResult]] to value. promise['[[PromiseResult]]'] = value; // 4. Set promise.[[PromiseFulfillReactions]] to undefined. promise['[[PromiseFulfillReactions]]'] = void 0; // 5. Set promise.[[PromiseRejectReactions]] to undefined. promise['[[PromiseRejectReactions]]'] = void 0; // 6. Set promise.[[PromiseState]] to "fulfilled". promise['[[PromiseState]]'] = PromiseState.fulfilled; // 7. Return TriggerPromiseReactions(reactions, value). return $TriggerPromiseReactions(ctx, reactions, value); } // http://www.ecma-international.org/ecma-262/#sec-newpromisecapability // 25.6.1.5 NewPromiseCapability ( C ) export function $NewPromiseCapability( ctx: ExecutionContext, C: $AnyObject, ): $PromiseCapability | $Error { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. If IsConstructor(C) is false, throw a TypeError exception. if (!C.isFunction) { return new $TypeError(realm, `Expected constructor, but got: ${C}`); } // 2. NOTE: C is assumed to be a constructor function that supports the parameter conventions of the Promise constructor (see 25.6.3.1). // 3. Let promiseCapability be a new PromiseCapability { [[Promise]]: undefined, [[Resolve]]: undefined, [[Reject]]: undefined }. const promiseCapability = new $PromiseCapability(intrinsics.undefined, intrinsics.undefined, intrinsics.undefined); // 4. Let steps be the algorithm steps defined in GetCapabilitiesExecutor Functions. // 5. Let executor be CreateBuiltinFunction(steps, « [[Capability]] »). // 6. Set executor.[[Capability]] to promiseCapability. const executor = new $GetCapabilitiesExecutor(realm, promiseCapability); // 7. Let promise be ? Construct(C, « executor »). const promise = $Construct(ctx, C as $Function, new $List(executor), intrinsics.undefined) as $PromiseInstance; // 8. If IsCallable(promiseCapability.[[Resolve]]) is false, throw a TypeError exception. if (!promiseCapability['[[Resolve]]'].isFunction) { return new $TypeError(realm, `Expected [[Resolve]] to be callable, but got: ${promiseCapability['[[Resolve]]']}`); } // 9. If IsCallable(promiseCapability.[[Reject]]) is false, throw a TypeError exception. if (!promiseCapability['[[Reject]]'].isFunction) { return new $TypeError(realm, `Expected [[Reject]] to be callable, but got: ${promiseCapability['[[Reject]]']}`); } // 10. Set promiseCapability.[[Promise]] to promise. promiseCapability['[[Promise]]'] = promise; // 11. Return promiseCapability. return promiseCapability; } // http://www.ecma-international.org/ecma-262/#sec-getcapabilitiesexecutor-functions // 25.6.1.5.1 GetCapabilitiesExecutor Functions export class $GetCapabilitiesExecutor extends $BuiltinFunction<'GetCapabilitiesExecutor'> { public '[[Capability]]': $PromiseCapability; public constructor( realm: Realm, capability: $PromiseCapability, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, 'GetCapabilitiesExecutor', intrinsics['%FunctionPrototype%']); this['[[Capability]]'] = capability; } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [resolve, reject]: $List<$Function | $Undefined>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (resolve === void 0) { resolve = intrinsics.undefined; } if (reject === void 0) { reject = intrinsics.undefined; } // 1. Let F be the active function object. const F = this; // 2. Assert: F has a [[Capability]] internal slot whose value is a PromiseCapability Record. // 3. Let promiseCapability be F.[[Capability]]. const promiseCapability = F['[[Capability]]']; // 4. If promiseCapability.[[Resolve]] is not undefined, throw a TypeError exception. if (!promiseCapability['[[Resolve]]'].isUndefined) { return new $TypeError(realm, `[[Resolve]] is already defined`); } // 5. If promiseCapability.[[Reject]] is not undefined, throw a TypeError exception. if (!promiseCapability['[[Reject]]'].isUndefined) { return new $TypeError(realm, `[[Reject]] is already defined`); } // 6. Set promiseCapability.[[Resolve]] to resolve. promiseCapability['[[Resolve]]'] = resolve; // 7. Set promiseCapability.[[Reject]] to reject. promiseCapability['[[Reject]]'] = reject; // 8. Return undefined. return intrinsics.undefined; } } // http://www.ecma-international.org/ecma-262/#sec-rejectpromise // 25.6.1.7 RejectPromise ( promise , reason ) export function $RejectPromise( ctx: ExecutionContext, promise: $PromiseInstance, reason: $AnyNonEmpty, ): $Undefined { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Assert: The value of promise.[[PromiseState]] is "pending". // 2. Let reactions be promise.[[PromiseRejectReactions]]. const reactions = promise['[[PromiseRejectReactions]]']!; // 3. Set promise.[[PromiseResult]] to reason. promise['[[PromiseResult]]'] = reason; // 4. Set promise.[[PromiseFulfillReactions]] to undefined. promise['[[PromiseFulfillReactions]]'] = void 0; // 5. Set promise.[[PromiseRejectReactions]] to undefined. promise['[[PromiseRejectReactions]]'] = void 0; // 6. Set promise.[[PromiseState]] to "rejected". promise['[[PromiseState]]'] = PromiseState.rejected; // 7. If promise.[[PromiseIsHandled]] is false, perform HostPromiseRejectionTracker(promise, "reject"). if (!promise['[[PromiseIsHandled]]']) { $HostPromiseRejectionTracker(ctx, promise, PromiseRejectionOperation.reject); } // 8. Return TriggerPromiseReactions(reactions, reason). return $TriggerPromiseReactions(ctx, reactions, reason); } // http://www.ecma-international.org/ecma-262/#sec-triggerpromisereactions // 25.6.1.8 TriggerPromiseReactions ( reactions , argument ) export function $TriggerPromiseReactions( ctx: ExecutionContext, reactions: $List<$PromiseReaction>, argument: $AnyNonEmpty, ): $Undefined { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; const promiseJobs = realm.PromiseJobs; const mos = ctx.ScriptOrModule; if (mos.isNull) { throw new Error(`No ScriptOrModule found in this realm`); } // 1. For each reaction in reactions, in original insertion order, do for (const reaction of reactions) { // 1. a. Perform EnqueueJob("PromiseJobs", PromiseReactionJob, « reaction, argument »). promiseJobs.EnqueueJob(ctx, new PromiseReactionJob(realm, mos, reaction, argument)); } // 2. Return undefined. return new $Undefined(realm); } export const enum PromiseRejectionOperation { reject = 1, handle = 2, } // http://www.ecma-international.org/ecma-262/#sec-host-promise-rejection-tracker // 25.6.1.9 HostPromiseRejectionTracker ( promise , operation ) export function $HostPromiseRejectionTracker( ctx: ExecutionContext, promise: $PromiseInstance, operation: PromiseRejectionOperation, ) { ctx.logger.error(`Promise rejected: ${promise}`); } // #endregion // http://www.ecma-international.org/ecma-262/#sec-promise-jobs // #region 25.6.2 Promise Jobs export class PromiseReactionJob extends Job { public constructor( realm: Realm, scriptOrModule: $$ESModuleOrScript, public readonly reaction: $PromiseReaction, public readonly argument: $AnyNonEmpty, ) { super(realm.logger.root, realm, scriptOrModule); } // http://www.ecma-international.org/ecma-262/#sec-promisereactionjob // 25.6.2.1 PromiseReactionJob ( reaction , argument ) public Run(ctx: ExecutionContext): $Any { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; this.logger.debug(`Run(#${ctx.id})`); const reaction = this.reaction; const argument = this.argument; // 1. Assert: reaction is a PromiseReaction Record. // 2. Let promiseCapability be reaction.[[Capability]]. const promiseCapability = reaction['[[Capability]]']; // 3. Let type be reaction.[[Type]]. const type = reaction['[[Type]]']; // 4. Let handler be reaction.[[Handler]]. const handler = reaction['[[Handler]]']; let handlerResult: $AnyNonEmpty; // 5. If handler is undefined, then if (handler.isUndefined) { // 5. a. If type is "Fulfill", let handlerResult be NormalCompletion(argument). if (type === PromiseReactionType.Fulfill) { handlerResult = argument; } // 5. b. Else, else { // 5. b. i. Assert: type is "Reject". // 5. b. ii. Let handlerResult be ThrowCompletion(argument). handlerResult = argument.ToCompletion(CompletionType.throw, intrinsics.empty); } } // 6. Else, let handlerResult be Call(handler, undefined, « argument »). else { handlerResult = $Call(ctx, handler, intrinsics.undefined, new $List(argument)); } // 7. If promiseCapability is undefined, then if (promiseCapability.isUndefined) { // 7. a. Assert: handlerResult is not an abrupt completion. // 7. b. Return NormalCompletion(empty). return new $Empty(realm); } let status: $AnyNonEmpty; // 8. If handlerResult is an abrupt completion, then if (handlerResult.isAbrupt) { // 8. a. Let status be Call(promiseCapability.[[Reject]], undefined, « handlerResult.[[Value]] »). status = $Call(ctx, promiseCapability['[[Reject]]'], intrinsics.undefined, new $List(handlerResult)); } // 9. Else, else { // 9. a. Let status be Call(promiseCapability.[[Resolve]], undefined, « handlerResult.[[Value]] »). status = $Call(ctx, promiseCapability['[[Resolve]]'], intrinsics.undefined, new $List(handlerResult)); } // 10. Return Completion(status). return status; } } export class PromiseResolveThenableJob extends Job { public constructor( realm: Realm, scriptOrModule: $$ESModuleOrScript, public readonly promiseToResolve: $PromiseInstance, public readonly thenable: $AnyNonEmptyNonError, public readonly then: $AnyNonEmptyNonError, ) { super(realm.logger.root, realm, scriptOrModule); } // http://www.ecma-international.org/ecma-262/#sec-promiseresolvethenablejob // 25.6.2.2 PromiseResolveThenableJob ( promiseToResolve , thenable , then ) public Run(ctx: ExecutionContext): $Any { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; this.logger.debug(`Run(#${ctx.id})`); const promiseToResolve = this.promiseToResolve; const thenable = this.thenable; const then = this.then; // 1. Let resolvingFunctions be CreateResolvingFunctions(promiseToResolve). const resolvingFunctions = new $PromiseResolvingFunctions(realm, promiseToResolve); // 2. Let thenCallResult be Call(then, thenable, « resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]] »). const thenCallResult = $Call(ctx, then, thenable, new $List<$Object>(resolvingFunctions['[[Resolve]]'], resolvingFunctions['[[Reject]]'])); // 3. If thenCallResult is an abrupt completion, then if (thenCallResult.isAbrupt) { // 3. a. Let status be Call(resolvingFunctions.[[Reject]], undefined, « thenCallResult.[[Value]] »). const status = $Call(ctx, resolvingFunctions['[[Reject]]'], intrinsics.undefined, new $List(thenCallResult)); // 3. b. Return Completion(status). return status; } // 4. Return Completion(thenCallResult). return thenCallResult; } } // #endregion // http://www.ecma-international.org/ecma-262/#sec-promise-constructor // #region 25.6.3 The Promise Constructor export class $PromiseConstructor extends $BuiltinFunction<'%Promise%'> { // http://www.ecma-international.org/ecma-262/#sec-promise.prototype // 25.6.4.2 Promise.prototype public get $prototype(): $PromisePrototype { return this.getProperty(this.realm['[[Intrinsics]]'].$prototype)['[[Value]]'] as $PromisePrototype; } public set $prototype(value: $PromisePrototype) { this.setDataProperty(this.realm['[[Intrinsics]]'].$prototype, value, false, false, false); } // http://www.ecma-international.org/ecma-262/#sec-promise.all // 25.6.4.1 Promise.all ( iterable ) public get all(): $Promise_all { return this.getProperty(this.realm['[[Intrinsics]]'].all)['[[Value]]'] as $Promise_all; } public set all(value: $Promise_all) { this.setDataProperty(this.realm['[[Intrinsics]]'].all, value); } // http://www.ecma-international.org/ecma-262/#sec-promise.race // 25.6.4.3 Promise.race ( iterable ) public get race(): $Promise_race { return this.getProperty(this.realm['[[Intrinsics]]'].race)['[[Value]]'] as $Promise_race; } public set race(value: $Promise_race) { this.setDataProperty(this.realm['[[Intrinsics]]'].race, value); } // http://www.ecma-international.org/ecma-262/#sec-promise.reject // 25.6.4.4 Promise.reject ( r ) public get reject(): $Promise_reject { return this.getProperty(this.realm['[[Intrinsics]]'].reject)['[[Value]]'] as $Promise_reject; } public set reject(value: $Promise_reject) { this.setDataProperty(this.realm['[[Intrinsics]]'].reject, value); } // http://www.ecma-international.org/ecma-262/#sec-promise.resolve // 25.6.4.5 Promise.resolve ( x ) public get resolve(): $Promise_resolve { return this.getProperty(this.realm['[[Intrinsics]]'].resolve)['[[Value]]'] as $Promise_resolve; } public set resolve(value: $Promise_resolve) { this.setDataProperty(this.realm['[[Intrinsics]]'].resolve, value, false, false, false); } // http://www.ecma-international.org/ecma-262/#sec-get-promise-@@species // 25.6.4.6 get Promise [ @@species ] public get ['@@species'](): $GetSpecies { return this.getProperty(this.realm['[[Intrinsics]]']['@@species'])['[[Value]]'] as $GetSpecies; } public set ['@@species'](value: $GetSpecies) { this.setDataProperty(this.realm['[[Intrinsics]]']['@@species'], value, false, false, false); } public constructor( realm: Realm, functionPrototype: $FunctionPrototype, ) { super(realm, '%Promise%', functionPrototype); } // http://www.ecma-international.org/ecma-262/#sec-promise-executor // 25.6.3.1 Promise ( executor ) public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [executor]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. If NewTarget is undefined, throw a TypeError exception. if (NewTarget.isUndefined) { return new $TypeError(realm, `Promise cannot be called as a function.`); } // 2. If IsCallable(executor) is false, throw a TypeError exception. if (executor === void 0 || !executor.isFunction) { return new $TypeError(realm, `The promise constructor requires an executor function`); } // 3. Let promise be ? OrdinaryCreateFromConstructor(NewTarget, "%PromisePrototype%", « [[PromiseState]], [[PromiseResult]], [[PromiseFulfillReactions]], [[PromiseRejectReactions]], [[PromiseIsHandled]] »). const promise = $PromiseInstance.Create(ctx, NewTarget); if (promise.isAbrupt) { return promise; } // 4. Set promise.[[PromiseState]] to "pending". promise['[[PromiseState]]'] = PromiseState.pending; // 5. Set promise.[[PromiseFulfillReactions]] to a new empty List. promise['[[PromiseFulfillReactions]]'] = new $List(); // 6. Set promise.[[PromiseRejectReactions]] to a new empty List. promise['[[PromiseRejectReactions]]'] = new $List(); // 7. Set promise.[[PromiseIsHandled]] to false. promise['[[PromiseIsHandled]]'] = false; // 8. Let resolvingFunctions be CreateResolvingFunctions(promise). const resolvingFunctions = new $PromiseResolvingFunctions(realm, promise); // 9. Let completion be Call(executor, undefined, « resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]] »). const completion = $Call( ctx, executor, intrinsics.undefined, new $List<$AnyNonEmpty>(resolvingFunctions['[[Resolve]]'], resolvingFunctions['[[Reject]]']), ); // 10. If completion is an abrupt completion, then if (completion.isAbrupt) { // 10. a. Perform ? Call(resolvingFunctions.[[Reject]], undefined, « completion.[[Value]] »). const $CallResult = $Call( ctx, resolvingFunctions['[[Reject]]'], intrinsics.undefined, new $List(completion), ); if ($CallResult.isAbrupt) { return $CallResult; } } // 11. Return promise. return promise; } } // http://www.ecma-international.org/ecma-262/#sec-properties-of-the-promise-constructor // 25.6.4 Properties of the Promise Constructor // http://www.ecma-international.org/ecma-262/#sec-promise.all // 25.6.4.1 Promise.all ( iterable ) export class $Promise_all extends $BuiltinFunction<'%Promise_all%'> { public constructor( realm: Realm, functionPrototype: $FunctionPrototype, ) { super(realm, '%Promise_all%', functionPrototype); } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [iterable]: $List<$AnyNonEmptyNonError>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (iterable === void 0) { iterable = intrinsics.undefined; } // 1. Let C be the this value. const C = thisArgument; // 2. If Type(C) is not Object, throw a TypeError exception. if (!C.isObject) { return new $TypeError(realm, `Expected 'this' to be an object, but got: ${C}`); } // 3. Let promiseCapability be ? NewPromiseCapability(C). const promiseCapability = $NewPromiseCapability(ctx, C); if (promiseCapability.isAbrupt) { return promiseCapability; } // 4. Let iteratorRecord be GetIterator(iterable). const iteratorRecord = $GetIterator(ctx, iterable); if (iteratorRecord.isAbrupt) { return iteratorRecord; } // TODO: we sure about this? spec doesn't say // 5. IfAbruptRejectPromise(iteratorRecord, promiseCapability). const maybeAbrupt = $IfAbruptRejectPromise(ctx, iteratorRecord, promiseCapability); if (maybeAbrupt.isAbrupt) { return maybeAbrupt; } // 6. Let result be PerformPromiseAll(iteratorRecord, C, promiseCapability). let result = PerformPromiseAll(ctx, iteratorRecord, C as $Function, promiseCapability) as $Any; // 7. If result is an abrupt completion, then if (result.isAbrupt) { // 7. a. If iteratorRecord.[[Done]] is false, set result to IteratorClose(iteratorRecord, result). if (iteratorRecord['[[Done]]'].isFalsey) { result = $IteratorClose(ctx, iteratorRecord, result); } // 7. b. IfAbruptRejectPromise(result, promiseCapability). const maybeAbrupt = $IfAbruptRejectPromise(ctx, result, promiseCapability); if (maybeAbrupt.isAbrupt) { return maybeAbrupt; } } // 8. Return Completion(result). return result as $AnyNonEmpty; // TODO: fix typings $Empty shenanigans } } // http://www.ecma-international.org/ecma-262/#sec-performpromiseall // 25.6.4.1.1 Runtime Semantics: PerformPromiseAll ( iteratorRecord , constructor , resultCapability ) function PerformPromiseAll( ctx: ExecutionContext, iteratorRecord: $IteratorRecord, constructor: $Function, resultCapability: $PromiseCapability, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Assert: IsConstructor(constructor) is true. // 2. Assert: resultCapability is a PromiseCapability Record. // 3. Let values be a new empty List. const values = new $List<$AnyNonEmptyNonError>(); // 4. Let remainingElementsCount be a new Record { [[Value]]: 1 }. const remainingElementsCount = new $ValueRecord<number>(1); // 5. Let index be 0. let index = 0; // 6. Repeat, while (true) { // 6. a. Let next be IteratorStep(iteratorRecord). const next = $IteratorStep(ctx, iteratorRecord); // 6. b. If next is an abrupt completion, set iteratorRecord.[[Done]] to true. // 6. c. ReturnIfAbrupt(next). if (next.isAbrupt) { iteratorRecord['[[Done]]'] = intrinsics.true; return next; } // 6. d. If next is false, then if (next.isFalsey) { // 6. d. i. Set iteratorRecord.[[Done]] to true. iteratorRecord['[[Done]]'] = intrinsics.true; // 6. d. ii. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1. // 6. d. iii. If remainingElementsCount.[[Value]] is 0, then if (--remainingElementsCount['[[Value]]'] === 0) { // 6. d. iii. 1. Let valuesArray be CreateArrayFromList(values). const valuesArray = $CreateArrayFromList(ctx, values); // 6. d. iii. 2. Perform ? Call(resultCapability.[[Resolve]], undefined, « valuesArray »). const $CallResult = $Call(ctx, resultCapability['[[Resolve]]'], intrinsics.undefined, new $List(valuesArray)); if ($CallResult.isAbrupt) { return $CallResult; } } // 6. d. iv. Return resultCapability.[[Promise]]. return resultCapability['[[Promise]]']; } // 6. e. Let nextValue be IteratorValue(next). const nextValue = $IteratorValue(ctx, next); // 6. f. If nextValue is an abrupt completion, set iteratorRecord.[[Done]] to true. // 6. g. ReturnIfAbrupt(nextValue). if (nextValue.isAbrupt) { iteratorRecord['[[Done]]'] = intrinsics.true; return nextValue; } // 6. h. Append undefined to values. values.push(new $Undefined(realm)); // 6. i. Let nextPromise be ? Invoke(constructor, "resolve", « nextValue »). const nextPromise = $Invoke(ctx, constructor, intrinsics.resolve, new $List(nextValue)) as $AnyNonEmpty; // TODO: fix $Empty typing shenanigans if (nextPromise.isAbrupt) { return nextPromise; } // 6. j. Let steps be the algorithm steps defined in Promise.all Resolve Element Functions. // 6. k. Let resolveElement be CreateBuiltinFunction(steps, « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] »). // 6. l. Set resolveElement.[[AlreadyCalled]] to a new Record { [[Value]]: false }. // 6. m. Set resolveElement.[[Index]] to index. // 6. n. Set resolveElement.[[Values]] to values. // 6. o. Set resolveElement.[[Capability]] to resultCapability. // 6. p. Set resolveElement.[[RemainingElements]] to remainingElementsCount. const resolveElement = new $Promise_all_ResolveElement( realm, new $ValueRecord<boolean>(false), index, values, resultCapability, remainingElementsCount, ); // 6. q. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] + 1. ++remainingElementsCount['[[Value]]']; // 6. r. Perform ? Invoke(nextPromise, "then", « resolveElement, resultCapability.[[Reject]] »). const $InvokeResult = $Invoke(ctx, nextPromise, intrinsics.then, new $List(resolveElement, resultCapability['[[Reject]]'])); if ($InvokeResult.isAbrupt) { return $InvokeResult; } // 6. s. Increase index by 1. ++index; } } // http://www.ecma-international.org/ecma-262/#sec-promise.all-resolve-element-functions // 25.6.4.1.2 Promise.all Resolve Element Functions export class $Promise_all_ResolveElement extends $BuiltinFunction<'Promise.all Resolve Element'> { public '[[AlreadyCalled]]': $ValueRecord<boolean>; public '[[Index]]': number; public '[[Values]]': $List<$AnyNonEmpty>; public '[[Capability]]': $PromiseCapability; public '[[RemainingElements]]': $ValueRecord<number>; public constructor( realm: Realm, alreadyCalled: $ValueRecord<boolean>, index: number, values: $List<$AnyNonEmpty>, capability: $PromiseCapability, remainingElements: $ValueRecord<number>, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, 'Promise.all Resolve Element', intrinsics['%FunctionPrototype%']); this['[[AlreadyCalled]]'] = alreadyCalled; this['[[Index]]'] = index; this['[[Values]]'] = values; this['[[Capability]]'] = capability; this['[[RemainingElements]]'] = remainingElements; } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [x]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (x === void 0) { x = intrinsics.undefined; } // 1. Let F be the active function object. const F = this; // 2. Let alreadyCalled be F.[[AlreadyCalled]]. const alreadyCalled = F['[[AlreadyCalled]]']; // 3. If alreadyCalled.[[Value]] is true, return undefined. if (alreadyCalled['[[Value]]']) { return intrinsics.undefined; } // 4. Set alreadyCalled.[[Value]] to true. alreadyCalled['[[Value]]'] = true; // 5. Let index be F.[[Index]]. const index = F['[[Index]]']; // 6. Let values be F.[[Values]]. const values = F['[[Values]]']; // 7. Let promiseCapability be F.[[Capability]]. const promiseCapability = F['[[Capability]]']; // 8. Let remainingElementsCount be F.[[RemainingElements]]. const remainingElementsCount = F['[[RemainingElements]]']; // 9. Set values[index] to x. values[index] = x; // 10. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1. // 11. If remainingElementsCount.[[Value]] is 0, then if (--remainingElementsCount['[[Value]]'] === 0) { // 11. a. Let valuesArray be CreateArrayFromList(values). const valuesArray = $CreateArrayFromList(ctx, values); // 11. b. Return ? Call(promiseCapability.[[Resolve]], undefined, « valuesArray »). return $Call(ctx, promiseCapability['[[Resolve]]'], intrinsics.undefined, new $List(valuesArray)); } // 12. Return undefined. return intrinsics.undefined; } } // http://www.ecma-international.org/ecma-262/#sec-promise.race // 25.6.4.3 Promise.race ( iterable ) export class $Promise_race extends $BuiltinFunction<'%Promise_race%'> { public constructor( realm: Realm, functionPrototype: $FunctionPrototype, ) { super(realm, '%Promise_race%', functionPrototype); } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [iterable]: $List<$AnyNonEmptyNonError>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (iterable === void 0) { iterable = intrinsics.undefined; } // 1. Let C be the this value. const C = thisArgument; // 2. If Type(C) is not Object, throw a TypeError exception. if (!C.isObject) { return new $TypeError(realm, `Expected 'this' to be an object, but got: ${C}`); } // 3. Let promiseCapability be ? NewPromiseCapability(C). const promiseCapability = $NewPromiseCapability(ctx, C); if (promiseCapability.isAbrupt) { return promiseCapability; } // 4. Let iteratorRecord be GetIterator(iterable). const iteratorRecord = $GetIterator(ctx, iterable); if (iteratorRecord.isAbrupt) { return iteratorRecord; } // TODO: we sure about this? spec doesn't say // 5. IfAbruptRejectPromise(iteratorRecord, promiseCapability). const maybeAbrupt = $IfAbruptRejectPromise(ctx, iteratorRecord, promiseCapability); if (maybeAbrupt.isAbrupt) { return maybeAbrupt; } // 6. Let result be PerformPromiseAll(iteratorRecord, C, promiseCapability). let result = PerformPromiseAll(ctx, iteratorRecord, C as $Function, promiseCapability) as $Any; // 7. If result is an abrupt completion, then if (result.isAbrupt) { // 7. a. If iteratorRecord.[[Done]] is false, set result to IteratorClose(iteratorRecord, result). if (iteratorRecord['[[Done]]'].isFalsey) { result = $IteratorClose(ctx, iteratorRecord, result); } // 7. b. IfAbruptRejectPromise(result, promiseCapability). const maybeAbrupt = $IfAbruptRejectPromise(ctx, result, promiseCapability); if (maybeAbrupt.isAbrupt) { return maybeAbrupt; } } // 8. Return Completion(result). return result as $AnyNonEmpty; // TODO: fix typings $Empty shenanigans } } // http://www.ecma-international.org/ecma-262/#sec-performpromiserace // 25.6.4.3.1 Runtime Semantics: PerformPromiseRace ( iteratorRecord , constructor , resultCapability ) export function $PerformPromiseRace( ctx: ExecutionContext, iteratorRecord: $IteratorRecord, constructor: $Function, resultCapability: $PromiseCapability, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Assert: IsConstructor(constructor) is true. // 2. Assert: resultCapability is a PromiseCapability Record. // 3. Repeat, while (true) { // 3. a. Let next be IteratorStep(iteratorRecord). const next = $IteratorStep(ctx, iteratorRecord); // 3. b. If next is an abrupt completion, set iteratorRecord.[[Done]] to true. // 3. c. ReturnIfAbrupt(next). if (next.isAbrupt) { iteratorRecord['[[Done]]'] = intrinsics.true; return next; } // 3. d. If next is false, then if (next.isFalsey) { // 3. d. i. Set iteratorRecord.[[Done]] to true. iteratorRecord['[[Done]]'] = intrinsics.true; // 3. d. ii. Return resultCapability.[[Promise]]. return resultCapability['[[Promise]]']; } // 3. e. Let nextValue be IteratorValue(next). const nextValue = $IteratorValue(ctx, next); // 3. f. If nextValue is an abrupt completion, set iteratorRecord.[[Done]] to true. // 3. g. ReturnIfAbrupt(nextValue). if (nextValue.isAbrupt) { iteratorRecord['[[Done]]'] = intrinsics.true; return nextValue; } // 3. h. Let nextPromise be ? Invoke(constructor, "resolve", « nextValue »). const nextPromise = $Invoke(ctx, constructor, intrinsics.resolve, new $List(nextValue)) as $AnyNonEmpty; // TODO: fix $Empty typing shenanigans if (nextPromise.isAbrupt) { return nextPromise; } // 3. i. Perform ? Invoke(nextPromise, "then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] »). const $InvokeResult = $Invoke(ctx, nextPromise, intrinsics.then, new $List(resultCapability['[[Resolve]]'], resultCapability['[[Reject]]'])); if ($InvokeResult.isAbrupt) { return $InvokeResult; } } } // http://www.ecma-international.org/ecma-262/#sec-promise.reject // 25.6.4.4 Promise.reject ( r ) export class $Promise_reject extends $BuiltinFunction<'%Promise_reject%'> { public constructor( realm: Realm, functionPrototype: $FunctionPrototype, ) { super(realm, '%Promise_reject%', functionPrototype); } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [r]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (r === void 0) { r = intrinsics.undefined; } // 1. Let C be the this value. const C = thisArgument; // 2. If Type(C) is not Object, throw a TypeError exception. if (!C.isObject) { return new $TypeError(realm, `Expected 'this' to be an object, but got: ${C}`); } // 3. Let promiseCapability be ? NewPromiseCapability(C). const promiseCapability = $NewPromiseCapability(ctx, C); if (promiseCapability.isAbrupt) { return promiseCapability; } // 4. Perform ? Call(promiseCapability.[[Reject]], undefined, « r »). const $CallResult = $Call(ctx, promiseCapability['[[Resolve]]'], intrinsics.undefined, new $List(r)); if ($CallResult.isAbrupt) { return $CallResult; } // 5. Return promiseCapability.[[Promise]]. return promiseCapability['[[Promise]]'] as $PromiseInstance; // TODO: verify if cast is safe } } // http://www.ecma-international.org/ecma-262/#sec-promise.resolve // 25.6.4.5 Promise.resolve ( x ) export class $Promise_resolve extends $BuiltinFunction<'%Promise_resolve%'> { public constructor( realm: Realm, functionPrototype: $FunctionPrototype, ) { super(realm, '%Promise_resolve%', functionPrototype); } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [x]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (x === void 0) { x = intrinsics.undefined; } // 1. Let C be the this value. const C = thisArgument; // 2. If Type(C) is not Object, throw a TypeError exception. if (!C.isObject) { return new $TypeError(realm, `Expected 'this' to be an object, but got: ${C}`); } // 3. Return ? PromiseResolve(C, x). return $PromiseResolve(ctx, C, x); } } // http://www.ecma-international.org/ecma-262/#sec-promise-resolve // 25.6.4.5.1 PromiseResolve ( C , x ) export function $PromiseResolve( ctx: ExecutionContext, C: $AnyObject, x: $AnyNonEmpty, ): $PromiseInstance | $Error { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Assert: Type(C) is Object. // 2. If IsPromise(x) is true, then if (x instanceof $PromiseInstance) { // 2. a. Let xConstructor be ? Get(x, "constructor"). const xConstructor = x['[[Get]]'](ctx, intrinsics.$constructor, x); // 2. b. If SameValue(xConstructor, C) is true, return x. if (xConstructor.is(C)) { return x; } } // 3. Let promiseCapability be ? NewPromiseCapability(C). const promiseCapability = $NewPromiseCapability(ctx, C); if (promiseCapability.isAbrupt) { return promiseCapability; } // 4. Perform ? Call(promiseCapability.[[Resolve]], undefined, « x »). const $CallResult = $Call(ctx, promiseCapability['[[Resolve]]'], intrinsics.undefined, new $List(x)); if ($CallResult.isAbrupt) { return $CallResult; } // 5. Return promiseCapability.[[Promise]]. return promiseCapability['[[Promise]]'] as $PromiseInstance; // TODO: verify if cast is safe } // #endregion // http://www.ecma-international.org/ecma-262/#sec-properties-of-the-promise-prototype-object // #region 25.6.5 Properties of the Promise Prototype Object export class $PromisePrototype extends $Object<'%PromisePrototype%'> { // http://www.ecma-international.org/ecma-262/#sec-promise.prototype.catch // 25.6.5.1 Promise.prototype.catch ( onRejected ) public get catch(): $PromiseProto_catch { return this.getProperty(this.realm['[[Intrinsics]]'].catch)['[[Value]]'] as $PromiseProto_catch; } public set catch(value: $PromiseProto_catch) { this.setDataProperty(this.realm['[[Intrinsics]]'].catch, value); } // http://www.ecma-international.org/ecma-262/#sec-promise.prototype.constructor // 25.6.5.2 Promise.prototype.constructor public get $constructor(): $PromiseConstructor { return this.getProperty(this.realm['[[Intrinsics]]'].$constructor)['[[Value]]'] as $PromiseConstructor; } public set $constructor(value: $PromiseConstructor) { this.setDataProperty(this.realm['[[Intrinsics]]'].$constructor, value); } // http://www.ecma-international.org/ecma-262/#sec-promise.prototype.finally // 25.6.5.3 Promise.prototype.finally ( onFinally ) public get finally(): $PromiseProto_finally { return this.getProperty(this.realm['[[Intrinsics]]'].finally)['[[Value]]'] as $PromiseProto_finally; } public set finally(value: $PromiseProto_finally) { this.setDataProperty(this.realm['[[Intrinsics]]'].finally, value); } // http://www.ecma-international.org/ecma-262/#sec-promise.prototype.then // 25.6.5.4 Promise.prototype.then ( onFulfilled , onRejected ) public get then(): $PromiseProto_then { return this.getProperty(this.realm['[[Intrinsics]]'].then)['[[Value]]'] as $PromiseProto_then; } public set then(value: $PromiseProto_then) { this.setDataProperty(this.realm['[[Intrinsics]]'].then, value); } // http://www.ecma-international.org/ecma-262/#sec-promise.prototype-@@tostringtag // 25.6.5.5 Promise.prototype [ @@toStringTag ] public get '@@toStringTag'(): $String<'Promise'> { return this.getProperty(this.realm['[[Intrinsics]]']['@@toStringTag'])['[[Value]]'] as $String<'Promise'>; } public set '@@toStringTag'(value: $String<'Promise'>) { this.setDataProperty(this.realm['[[Intrinsics]]']['@@toStringTag'], value, false, false, true); } public constructor( realm: Realm, proto: $FunctionPrototype, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, '%PromisePrototype%', proto, CompletionType.normal, intrinsics.empty); } } // http://www.ecma-international.org/ecma-262/#sec-promise.prototype.catch // 25.6.5.1 Promise.prototype.catch ( onRejected ) export class $PromiseProto_catch extends $BuiltinFunction<'%PromiseProto_catch%'> { public constructor( realm: Realm, proto: $FunctionPrototype, ) { super(realm, '%PromiseProto_catch%', proto); } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [onRejected]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (onRejected === void 0) { onRejected = intrinsics.undefined; } // 1. Let promise be the this value. const promise = thisArgument; // 2. Return ? Invoke(promise, "then", « undefined, onRejected »). return $Invoke(ctx, promise, intrinsics.then, new $List(intrinsics.undefined, onRejected)) as $AnyNonEmpty; // TODO: fix $Empty typings } } // http://www.ecma-international.org/ecma-262/#sec-promise.prototype.finally // 25.6.5.3 Promise.prototype.finally ( onFinally ) export class $PromiseProto_finally extends $BuiltinFunction<'%PromiseProto_finally%'> { public constructor( realm: Realm, proto: $FunctionPrototype, ) { super(realm, '%PromiseProto_finally%', proto); } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [onFinally]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (onFinally === void 0) { onFinally = intrinsics.undefined; } // 1. Let promise be the this value. const promise = thisArgument; // 2. If Type(promise) is not Object, throw a TypeError exception. if (!promise.isObject) { return new $TypeError(realm, `Expected 'this' to be an object, but got: ${promise}`); } // 3. Let C be ? SpeciesConstructor(promise, %Promise%). const C = $SpeciesConstructor(ctx, promise, intrinsics['%Promise%']); if (C.isAbrupt) { return C; } let thenFinally: $AnyNonEmpty; let catchFinally: $AnyNonEmpty; // 4. Assert: IsConstructor(C) is true. // 5. If IsCallable(onFinally) is false, then if (!onFinally.isFunction) { // 5. a. Let thenFinally be onFinally. thenFinally = onFinally; // 5. b. Let catchFinally be onFinally. catchFinally = onFinally; } // 6. Else, else { // 6. a. Let stepsThenFinally be the algorithm steps defined in Then Finally Functions. // 6. b. Let thenFinally be CreateBuiltinFunction(stepsThenFinally, « [[Constructor]], [[OnFinally]] »). // 6. c. Set thenFinally.[[Constructor]] to C. // 6. d. Set thenFinally.[[OnFinally]] to onFinally. thenFinally = new $ThenFinally(realm, C, onFinally); // 6. e. Let stepsCatchFinally be the algorithm steps defined in Catch Finally Functions. // 6. f. Let catchFinally be CreateBuiltinFunction(stepsCatchFinally, « [[Constructor]], [[OnFinally]] »). // 6. g. Set catchFinally.[[Constructor]] to C. // 6. h. Set catchFinally.[[OnFinally]] to onFinally. catchFinally = new $CatchFinally(realm, C, onFinally); } // 7. Return ? Invoke(promise, "then", « thenFinally, catchFinally »). return $Invoke(ctx, promise, intrinsics.then, new $List(thenFinally, catchFinally)) as $AnyNonEmpty; // TODO: fix typings $Empty shenanigans } } // http://www.ecma-international.org/ecma-262/#sec-thenfinallyfunctions // 25.6.5.3.1 Then Finally Functions export class $ThenFinally extends $BuiltinFunction<'Then Finally'> { public '[[Constructor]]': $Function; public '[[OnFinally]]': $AnyNonEmpty; public constructor( realm: Realm, constructor: $Function, onFinally: $AnyNonEmpty, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, 'Then Finally', intrinsics['%FunctionPrototype%']); this['[[Constructor]]'] = constructor; this['[[OnFinally]]'] = onFinally; } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [value]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (value === void 0) { value = intrinsics.undefined; } // 1. Let F be the active function object. const F = this; // 2. Let onFinally be F.[[OnFinally]]. const onFinally = F['[[OnFinally]]']; // 3. Assert: IsCallable(onFinally) is true. // 4. Let result be ? Call(onFinally, undefined). const result = $Call(ctx, onFinally, intrinsics.undefined, intrinsics.undefined); if (result.isAbrupt) { return result; } // 5. Let C be F.[[Constructor]]. const C = F['[[Constructor]]']; // 6. Assert: IsConstructor(C) is true. // 7. Let promise be ? PromiseResolve(C, result). const promise = $PromiseResolve(ctx, C, result); if (promise.isAbrupt) { return promise; } // 8. Let valueThunk be equivalent to a function that returns value. const valueThunk = new $ValueThunk(realm, value); // 9. Return ? Invoke(promise, "then", « valueThunk »). return $Invoke(ctx, promise, intrinsics.then, new $List(valueThunk)) as $AnyNonEmpty; // TODO: fix typings $Empty shenanigans } } export class $ValueThunk extends $BuiltinFunction<'ValueThunk'> { public readonly value: $AnyNonEmpty; public constructor( realm: Realm, value: $AnyNonEmpty, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, 'ValueThunk', intrinsics['%FunctionPrototype%']); this.value = value; } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, argumentsList: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { return this.value; } } // http://www.ecma-international.org/ecma-262/#sec-catchfinallyfunctions // 25.6.5.3.2 Catch Finally Functions export class $CatchFinally extends $BuiltinFunction<'Catch Finally'> { public '[[Constructor]]': $Function; public '[[OnFinally]]': $AnyNonEmpty; public constructor( realm: Realm, constructor: $Function, onFinally: $AnyNonEmpty, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, 'Catch Finally', intrinsics['%FunctionPrototype%']); this['[[Constructor]]'] = constructor; this['[[OnFinally]]'] = onFinally; } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [value]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (value === void 0) { value = intrinsics.undefined; } // 1. Let F be the active function object. const F = this; // 2. Let onFinally be F.[[OnFinally]]. const onFinally = F['[[OnFinally]]']; // 3. Assert: IsCallable(onFinally) is true. // 4. Let result be ? Call(onFinally, undefined). const result = $Call(ctx, onFinally, intrinsics.undefined, intrinsics.undefined); if (result.isAbrupt) { return result; } // 5. Let C be F.[[Constructor]]. const C = F['[[Constructor]]']; // 6. Assert: IsConstructor(C) is true. // 7. Let promise be ? PromiseResolve(C, result). const promise = $PromiseResolve(ctx, C, result); if (promise.isAbrupt) { return promise; } // 8. Let thrower be equivalent to a function that throws reason. const thrower = new $Thrower(realm, value); // 9. Return ? Invoke(promise, "then", « thrower »). return $Invoke(ctx, promise, intrinsics.then, new $List(thrower)) as $AnyNonEmpty; // TODO: fix typings $Empty shenanigans } } export class $Thrower extends $BuiltinFunction<'Thrower'> { public readonly reason: $AnyNonEmpty; public constructor( realm: Realm, reason: $AnyNonEmpty, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, 'Thrower', intrinsics['%FunctionPrototype%']); this.reason = reason; } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, argumentsList: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { // TODO: double check if this is the correct way to throw return this.reason.ToCompletion(CompletionType.throw, ctx.Realm['[[Intrinsics]]'].empty); } } // http://www.ecma-international.org/ecma-262/#sec-promise.prototype.then // 25.6.5.4 Promise.prototype.then ( onFulfilled , onRejected ) export class $PromiseProto_then extends $BuiltinFunction<'%PromiseProto_then%'> { public constructor( realm: Realm, proto: $FunctionPrototype, ) { super(realm, '%PromiseProto_then%', proto); } public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [onFulfilled, onRejected]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (onFulfilled === void 0) { onFulfilled = intrinsics.undefined; } if (onRejected === void 0) { onRejected = intrinsics.undefined; } // 1. Let promise be the this value. const promise = thisArgument; // 2. If IsPromise(promise) is false, throw a TypeError exception. if (!promise.isObject) { return new $TypeError(realm, `Expected 'this' to be an object, but got: ${promise}`); } // 3. Let C be ? SpeciesConstructor(promise, %Promise%). const C = $SpeciesConstructor(ctx, promise, intrinsics['%Promise%']); if (C.isAbrupt) { return C; } // 4. Let resultCapability be ? NewPromiseCapability(C). const resultCapability = $NewPromiseCapability(ctx, C); if (resultCapability.isAbrupt) { return resultCapability; } // 5. Return PerformPromiseThen(promise, onFulfilled, onRejected, resultCapability). return $PerformPromiseThen( ctx, // TODO: verify if this cast is safe promise as $PromiseInstance, onFulfilled, onRejected, resultCapability, ); } } // http://www.ecma-international.org/ecma-262/#sec-performpromisethen // 25.6.5.4.1 PerformPromiseThen ( promise , onFulfilled , onRejected [ , resultCapability ] ) export function $PerformPromiseThen( ctx: ExecutionContext, promise: $PromiseInstance, onFulfilled: $AnyNonEmpty, onRejected: $AnyNonEmpty, resultCapability?: $PromiseCapability | $Undefined, ): $PromiseInstance | $Undefined { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Assert: IsPromise(promise) is true. // 2. If resultCapability is present, then if (resultCapability !== void 0) { // 2. a. Assert: resultCapability is a PromiseCapability Record. } // 3. Else, else { // 3. a. Set resultCapability to undefined. resultCapability = intrinsics.undefined; } // 4. If IsCallable(onFulfilled) is false, then if (!onFulfilled.isFunction) { // 4. a. Set onFulfilled to undefined. onFulfilled = intrinsics.undefined; } // 5. If IsCallable(onRejected) is false, then if (!onRejected.isFunction) { // 5. a. Set onRejected to undefined. onRejected = intrinsics.undefined; } // 6. Let fulfillReaction be the PromiseReaction { [[Capability]]: resultCapability, [[Type]]: "Fulfill", [[Handler]]: onFulfilled }. const fulfillReaction = new $PromiseReaction( resultCapability, PromiseReactionType.Fulfill, onFulfilled as $Function | $Undefined, ); // 7. Let rejectReaction be the PromiseReaction { [[Capability]]: resultCapability, [[Type]]: "Reject", [[Handler]]: onRejected }. const rejectReaction = new $PromiseReaction( resultCapability, PromiseReactionType.Reject, onRejected as $Function | $Undefined, ); // 8. If promise.[[PromiseState]] is "pending", then if (promise['[[PromiseState]]'] === PromiseState.pending) { // 8. a. Append fulfillReaction as the last element of the List that is promise.[[PromiseFulfillReactions]]. promise['[[PromiseFulfillReactions]]']!.push(fulfillReaction); // 8. b. Append rejectReaction as the last element of the List that is promise.[[PromiseRejectReactions]]. promise['[[PromiseRejectReactions]]']!.push(rejectReaction); } // 9. Else if promise.[[PromiseState]] is "fulfilled", then else if (promise['[[PromiseState]]'] === PromiseState.fulfilled) { // 9. a. Let value be promise.[[PromiseResult]]. const value = promise['[[PromiseResult]]']!; // 9. b. Perform EnqueueJob("PromiseJobs", PromiseReactionJob, « fulfillReaction, value »). realm.PromiseJobs.EnqueueJob(ctx, new PromiseReactionJob(realm, ctx.ScriptOrModule as $$ESModuleOrScript, fulfillReaction, value)); } // 10. Else, else { // 10. a. Assert: The value of promise.[[PromiseState]] is "rejected". // 10. b. Let reason be promise.[[PromiseResult]]. const reason = promise['[[PromiseResult]]']!; // 10. c. If promise.[[PromiseIsHandled]] is false, perform HostPromiseRejectionTracker(promise, "handle"). if (!promise['[[PromiseIsHandled]]']) { $HostPromiseRejectionTracker(ctx, promise, PromiseRejectionOperation.handle); } // 10. d. Perform EnqueueJob("PromiseJobs", PromiseReactionJob, « rejectReaction, reason »). realm.PromiseJobs.EnqueueJob(ctx, new PromiseReactionJob(realm, ctx.ScriptOrModule as $$ESModuleOrScript, rejectReaction, reason)); } // 11. Set promise.[[PromiseIsHandled]] to true. promise['[[PromiseIsHandled]]'] = true; // 12. If resultCapability is undefined, then if (resultCapability === void 0 || resultCapability.isUndefined) { // 12. a. Return undefined. return intrinsics.undefined; } // 13. Else, else { // 13. a. Return resultCapability.[[Promise]]. return resultCapability['[[Promise]]']; } } // #endregion // http://www.ecma-international.org/ecma-262/#sec-properties-of-promise-instances // #region 25.6.6 Properties of Promise Instances export const enum PromiseState { pending = 1, fulfilled = 2, rejected = 3, } // http://www.ecma-international.org/ecma-262/#sec-properties-of-promise-instances // 25.6.6 Properties of Promise Instances export class $PromiseInstance extends $Object<'PromiseInstance'> { public '[[PromiseState]]': PromiseState; public '[[PromiseResult]]': $AnyNonEmpty | undefined; public '[[PromiseFulfillReactions]]': $List<$PromiseReaction> | undefined; public '[[PromiseRejectReactions]]': $List<$PromiseReaction> | undefined; public '[[PromiseIsHandled]]': boolean; private constructor( realm: Realm, proto: $PromisePrototype, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, 'PromiseInstance', proto, CompletionType.normal, intrinsics.empty); // 4. Set promise.[[PromiseState]] to "pending". this['[[PromiseState]]'] = PromiseState.pending; this['[[PromiseResult]]'] = void 0; // 5. Set promise.[[PromiseFulfillReactions]] to a new empty List. this['[[PromiseFulfillReactions]]'] = new $List(); // 6. Set promise.[[PromiseRejectReactions]] to a new empty List. this['[[PromiseRejectReactions]]'] = new $List(); // 7. Set promise.[[PromiseIsHandled]] to false. this['[[PromiseIsHandled]]'] = false; } public static Create( ctx: ExecutionContext, NewTarget: $Function, ): $PromiseInstance | $Error { const proto = $GetPrototypeFromConstructor(ctx, NewTarget, '%PromisePrototype%'); if (proto.isAbrupt) { return proto; } return new $PromiseInstance(ctx.Realm, proto); } } // #endregion
the_stack
import * as THREE from "three"; import { publishReplay, refCount, startWith, tap, } from "rxjs/operators"; import { Observable, of as observableOf, Subject, Subscription, } from "rxjs"; import { SubscriptionHolder } from "../util/SubscriptionHolder"; import { ImageTileEnt } from "../api/ents/ImageTileEnt"; import { TileRegionOfInterest } from "./interfaces/TileRegionOfInterest"; import { TileImageSize, TileCoords3D, TilePixelCoords2D, TileCoords2D, TileLevel, TILE_MIN_REQUEST_LEVEL, } from "./interfaces/TileTypes"; import { basicToTileCoords2D, cornersToTilesCoords2D, hasOverlap2D, clampedImageLevel, tileToPixelCoords2D, verifySize, baseImageLevel, } from "./TileMath"; import { TileLoader } from "./TileLoader"; import { TileStore } from "./TileStore"; /** * @class TextureProvider * * @classdesc Represents a provider of textures. */ export class TextureProvider { private readonly _loader: TileLoader; private readonly _store: TileStore; private readonly _subscriptions: Map<string, Subscription>; private readonly _urlSubscriptions: Map<number, Subscription>; private readonly _renderedLevel: Set<string>; private readonly _rendered: Map<string, TileCoords3D>; private readonly _created$: Observable<THREE.Texture>; private readonly _createdSubject$: Subject<THREE.Texture>; private readonly _hasSubject$: Subject<boolean>; private readonly _has$: Observable<boolean>; private readonly _updated$: Subject<boolean>; private readonly _holder: SubscriptionHolder; private readonly _size: TileImageSize; private readonly _imageId: string; private readonly _level: TileLevel; private _renderer: THREE.WebGLRenderer; private _render: { camera: THREE.OrthographicCamera; target: THREE.WebGLRenderTarget; }; private _background: HTMLImageElement; private _aborts: Function[]; private _disposed: boolean; /** * Create a new image texture provider instance. * * @param {string} imageId - The identifier of the image for which to request tiles. * @param {number} width - The full width of the original image. * @param {number} height - The full height of the original image. * @param {HTMLImageElement} background - Image to use as background. * @param {TileLoader} loader - Loader for retrieving tiles. * @param {TileStore} store - Store for saving tiles. * @param {THREE.WebGLRenderer} renderer - Renderer used for rendering tiles to texture. */ constructor( imageId: string, width: number, height: number, background: HTMLImageElement, loader: TileLoader, store: TileStore, renderer: THREE.WebGLRenderer) { const size = { h: height, w: width }; if (!verifySize(size)) { console.warn( `Original image size (${width}, ${height}) ` + `is invalid (${imageId}). Tiles will not be loaded.`); } this._imageId = imageId; this._size = size; this._level = { max: baseImageLevel(this._size), z: -1, }; this._holder = new SubscriptionHolder(); this._updated$ = new Subject<boolean>(); this._createdSubject$ = new Subject<THREE.Texture>(); this._created$ = this._createdSubject$ .pipe( publishReplay(1), refCount()); this._holder.push(this._created$.subscribe(() => { /*noop*/ })); this._hasSubject$ = new Subject<boolean>(); this._has$ = this._hasSubject$ .pipe( startWith(false), publishReplay(1), refCount()); this._holder.push(this._has$.subscribe(() => { /*noop*/ })); this._renderedLevel = new Set(); this._rendered = new Map(); this._subscriptions = new Map(); this._urlSubscriptions = new Map(); this._loader = loader; this._store = store; this._background = background; this._renderer = renderer; this._aborts = []; this._render = null; this._disposed = false; } /** * Get disposed. * * @returns {boolean} Value indicating whether provider has * been disposed. */ public get disposed(): boolean { return this._disposed; } /** * Get hasTexture$. * * @returns {Observable<boolean>} Observable emitting * values indicating when the existance of a texture * changes. */ public get hasTexture$(): Observable<boolean> { return this._has$; } /** * Get id. * * @returns {boolean} The identifier of the image for * which to render textures. */ public get id(): string { return this._imageId; } /** * Get textureUpdated$. * * @returns {Observable<boolean>} Observable emitting * values when an existing texture has been updated. */ public get textureUpdated$(): Observable<boolean> { return this._updated$; } /** * Get textureCreated$. * * @returns {Observable<boolean>} Observable emitting * values when a new texture has been created. */ public get textureCreated$(): Observable<THREE.Texture> { return this._created$; } /** * Abort all outstanding image tile requests. */ public abort(): void { this._subscriptions.forEach(sub => sub.unsubscribe()); this._subscriptions.clear(); for (const abort of this._aborts) { abort(); } this._aborts = []; } /** * Dispose the provider. * * @description Disposes all cached assets and * aborts all outstanding image tile requests. */ public dispose(): void { if (this._disposed) { console.warn(`Texture already disposed (${this._imageId})`); return; } this._urlSubscriptions.forEach(sub => sub.unsubscribe()); this._urlSubscriptions.clear(); this.abort(); if (this._render != null) { this._render.target.dispose(); this._render.target = null; this._render.camera = null; this._render = null; } this._store.dispose(); this._holder.unsubscribe(); this._renderedLevel.clear(); this._background = null; this._renderer = null; this._disposed = true; } /** * Set the region of interest. * * @description When the region of interest is set the * the tile level is determined and tiles for the region * are fetched from the store or the loader and renderedLevel * to the texture. * * @param {TileRegionOfInterest} roi - Spatial edges to cache. */ public setRegionOfInterest(roi: TileRegionOfInterest): void { if (!verifySize(this._size)) { return; } const virtualWidth = 1 / roi.pixelWidth; const virtualHeight = 1 / roi.pixelHeight; const level = clampedImageLevel( { h: virtualHeight, w: virtualWidth }, TILE_MIN_REQUEST_LEVEL, this._level.max); if (level !== this._level.z) { this.abort(); this._level.z = level; this._renderedLevel.clear(); this._rendered .forEach((tile, id) => { if (tile.z !== level) { return; } this._renderedLevel.add(id); }); } if (this._render == null) { this._initRender(); } const topLeft = basicToTileCoords2D( [roi.bbox.minX, roi.bbox.minY], this._size, this._level); const bottomRight = basicToTileCoords2D( [roi.bbox.maxX, roi.bbox.maxY], this._size, this._level); const tiles = cornersToTilesCoords2D( topLeft, bottomRight, this._size, this._level); this._fetchTiles(level, tiles); } /** * Retrieve an image tile. * * @description Retrieve an image tile and render it to the * texture. Add the tile to the store and emit to the updated * observable. * * @param {ImageTileEnt} tile - The tile ent. */ private _fetchTile(tile: ImageTileEnt): void { const getTile = this._loader.getImage$(tile.url); const tile$ = getTile[0]; const abort = getTile[1]; this._aborts.push(abort); const tileId = this._store.inventId(tile); const subscription = tile$.subscribe( (image: HTMLImageElement): void => { const pixels = tileToPixelCoords2D( tile, this._size, this._level); this._renderToTarget(pixels, image); this._subscriptions.delete(tileId); this._removeFromArray(abort, this._aborts); this._markRendered(tile); this._store.add(tileId, image); this._updated$.next(true); }, (error: Error): void => { this._subscriptions.delete(tileId); this._removeFromArray(abort, this._aborts); console.error(error); }); if (!subscription.closed) { this._subscriptions.set(tileId, subscription); } } /** * Fetch image tiles. * * @description Retrieve a image tiles and render them to the * texture. Retrieve from store if it exists, otherwise retrieve * from loader. * * @param {Array<TileCoords2D>} tiles - Array of tile coordinates to * retrieve. */ private _fetchTiles(level: number, tiles: TileCoords2D[]): void { const urls$ = this._store.hasURLLevel(level) ? observableOf(undefined) : this._loader .getURLs$(this._imageId, level) .pipe( tap(ents => { if (!this._store.hasURLLevel(level)) { this._store.addURLs(level, ents); } })); const subscription = urls$.subscribe( (): void => { if (level !== this._level.z) { return; } for (const tile of tiles) { const ent: ImageTileEnt = { x: tile.x, y: tile.y, z: level, url: null, }; const id = this._store.inventId(ent); if (this._renderedLevel.has(id) || this._subscriptions.has(id)) { continue; } if (this._store.has(id)) { const pixels = tileToPixelCoords2D( tile, this._size, this._level); this._renderToTarget( pixels, this._store.get(id)); this._markRendered(ent); this._updated$.next(true); continue; } ent.url = this._store.getURL(id); this._fetchTile(ent); } this._urlSubscriptions.delete(level); }, (error: Error): void => { this._urlSubscriptions.delete(level); console.error(error); }); if (!subscription.closed) { this._urlSubscriptions.set(level, subscription); } } private _initRender(): void { const dx = this._size.w / 2; const dy = this._size.h / 2; const near = -1; const far = 1; const camera = new THREE.OrthographicCamera(-dx, dx, dy, -dy, near, far); camera.position.z = 1; const gl = this._renderer.getContext(); const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); const backgroundSize = Math.max(this._size.w, this._size.h); const scale = maxTextureSize > backgroundSize ? 1 : maxTextureSize / backgroundSize; const targetWidth = Math.floor(scale * this._size.w); const targetHeight = Math.floor(scale * this._size.h); const target = new THREE.WebGLRenderTarget( targetWidth, targetHeight, { depthBuffer: false, format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter, stencilBuffer: false, }); this._render = { camera, target }; const pixels = tileToPixelCoords2D( { x: 0, y: 0 }, this._size, { max: this._level.max, z: 0 }); this._renderToTarget(pixels, this._background); this._createdSubject$.next(target.texture); this._hasSubject$.next(true); } /** * Mark a tile as rendered. * * @description Clears tiles marked as rendered in other * levels of the tile pyramid if they overlap the * newly rendered tile. * * @param {Arrary<number>} tile - The tile ent. */ private _markRendered(tile: ImageTileEnt): void { const others = Array.from(this._rendered.entries()) .filter( ([_, t]: [string, TileCoords3D]): boolean => { return t.z !== tile.z; }); for (const [otherId, other] of others) { if (hasOverlap2D(tile, other)) { this._rendered.delete(otherId); } } const id = this._store.inventId(tile); this._rendered.set(id, tile); this._renderedLevel.add(id); } /** * Remove an item from an array if it exists in array. * * @param {T} item - Item to remove. * @param {Array<T>} array - Array from which item should be removed. */ private _removeFromArray<T>(item: T, array: T[]): void { const index = array.indexOf(item); if (index !== -1) { array.splice(index, 1); } } /** * Render an image tile to the target texture. * * @param {ImageTileEnt} tile - Tile ent. * @param {HTMLImageElement} image - The image tile to render. */ private _renderToTarget( pixel: TilePixelCoords2D, image: HTMLImageElement): void { const texture = new THREE.Texture(image); texture.minFilter = THREE.LinearFilter; texture.needsUpdate = true; const geometry = new THREE.PlaneGeometry(pixel.w, pixel.h); const material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.FrontSide, }); const mesh = new THREE.Mesh(geometry, material); mesh.position.x = -this._size.w / 2 + pixel.x + pixel.w / 2; mesh.position.y = this._size.h / 2 - pixel.y - pixel.h / 2; const scene = new THREE.Scene(); scene.add(mesh); const target = this._renderer.getRenderTarget(); this._renderer.resetState(); this._renderer.setRenderTarget(this._render.target) this._renderer.render(scene, this._render.camera); this._renderer.setRenderTarget(target); scene.remove(mesh); geometry.dispose(); material.dispose(); texture.dispose(); } }
the_stack
import { Dict, Option } from '@glimmer/interfaces'; import { LOCAL_DEBUG } from '@glimmer/local-debug-flags'; import { assert, assign, deprecate, isPresent } from '@glimmer/util'; import { SourceLocation, SourcePosition, SYNTHETIC_LOCATION } from '../source/location'; import { Source } from '../source/source'; import { SourceSpan } from '../source/span'; import * as ASTv1 from './api'; import { PathExpressionImplV1 } from './legacy-interop'; let _SOURCE: Source | undefined; function SOURCE(): Source { if (!_SOURCE) { _SOURCE = new Source('', '(synthetic)'); } return _SOURCE; } // const SOURCE = new Source('', '(tests)'); // Statements export type BuilderHead = string | ASTv1.Expression; export type TagDescriptor = string | { name: string; selfClosing: boolean }; function buildMustache( path: BuilderHead | ASTv1.Literal, params?: ASTv1.Expression[], hash?: ASTv1.Hash, raw?: boolean, loc?: SourceLocation, strip?: ASTv1.StripFlags ): ASTv1.MustacheStatement { if (typeof path === 'string') { path = buildPath(path); } return { type: 'MustacheStatement', path, params: params || [], hash: hash || buildHash([]), escaped: !raw, trusting: !!raw, loc: buildLoc(loc || null), strip: strip || { open: false, close: false }, }; } function buildBlock( path: BuilderHead, params: Option<ASTv1.Expression[]>, hash: Option<ASTv1.Hash>, _defaultBlock: ASTv1.PossiblyDeprecatedBlock, _elseBlock?: Option<ASTv1.PossiblyDeprecatedBlock>, loc?: SourceLocation, openStrip?: ASTv1.StripFlags, inverseStrip?: ASTv1.StripFlags, closeStrip?: ASTv1.StripFlags ): ASTv1.BlockStatement { let defaultBlock: ASTv1.Block; let elseBlock: Option<ASTv1.Block> | undefined; if (_defaultBlock.type === 'Template') { if (LOCAL_DEBUG) { deprecate(`b.program is deprecated. Use b.blockItself instead.`); } defaultBlock = (assign({}, _defaultBlock, { type: 'Block' }) as unknown) as ASTv1.Block; } else { defaultBlock = _defaultBlock; } if (_elseBlock !== undefined && _elseBlock !== null && _elseBlock.type === 'Template') { if (LOCAL_DEBUG) { deprecate(`b.program is deprecated. Use b.blockItself instead.`); } elseBlock = (assign({}, _elseBlock, { type: 'Block' }) as unknown) as ASTv1.Block; } else { elseBlock = _elseBlock; } return { type: 'BlockStatement', path: buildPath(path), params: params || [], hash: hash || buildHash([]), program: defaultBlock || null, inverse: elseBlock || null, loc: buildLoc(loc || null), openStrip: openStrip || { open: false, close: false }, inverseStrip: inverseStrip || { open: false, close: false }, closeStrip: closeStrip || { open: false, close: false }, }; } function buildElementModifier( path: BuilderHead | ASTv1.Expression, params?: ASTv1.Expression[], hash?: ASTv1.Hash, loc?: Option<SourceLocation> ): ASTv1.ElementModifierStatement { return { type: 'ElementModifierStatement', path: buildPath(path), params: params || [], hash: hash || buildHash([]), loc: buildLoc(loc || null), }; } function buildPartial( name: ASTv1.PathExpression, params?: ASTv1.Expression[], hash?: ASTv1.Hash, indent?: string, loc?: SourceLocation ): ASTv1.PartialStatement { return { type: 'PartialStatement', name: name, params: params || [], hash: hash || buildHash([]), indent: indent || '', strip: { open: false, close: false }, loc: buildLoc(loc || null), }; } function buildComment(value: string, loc?: SourceLocation): ASTv1.CommentStatement { return { type: 'CommentStatement', value: value, loc: buildLoc(loc || null), }; } function buildMustacheComment(value: string, loc?: SourceLocation): ASTv1.MustacheCommentStatement { return { type: 'MustacheCommentStatement', value: value, loc: buildLoc(loc || null), }; } function buildConcat( parts: (ASTv1.TextNode | ASTv1.MustacheStatement)[], loc?: SourceLocation ): ASTv1.ConcatStatement { if (!isPresent(parts)) { throw new Error(`b.concat requires at least one part`); } return { type: 'ConcatStatement', parts: parts || [], loc: buildLoc(loc || null), }; } // Nodes export type ElementParts = | ['attrs', ...AttrSexp[]] | ['modifiers', ...ModifierSexp[]] | ['body', ...ASTv1.Statement[]] | ['comments', ...ElementComment[]] | ['as', ...string[]] | ['loc', SourceLocation]; export type PathSexp = string | ['path', string, LocSexp?]; export type ModifierSexp = | string | [PathSexp, LocSexp?] | [PathSexp, ASTv1.Expression[], LocSexp?] | [PathSexp, ASTv1.Expression[], Dict<ASTv1.Expression>, LocSexp?]; export type AttrSexp = [string, ASTv1.AttrNode['value'] | string, LocSexp?]; export type LocSexp = ['loc', SourceLocation]; export type ElementComment = ASTv1.MustacheCommentStatement | SourceLocation | string; export type SexpValue = | string | ASTv1.Expression[] | Dict<ASTv1.Expression> | LocSexp | PathSexp | undefined; export interface BuildElementOptions { attrs?: ASTv1.AttrNode[]; modifiers?: ASTv1.ElementModifierStatement[]; children?: ASTv1.Statement[]; comments?: ElementComment[]; blockParams?: string[]; loc?: SourceSpan; } function buildElement(tag: TagDescriptor, options: BuildElementOptions): ASTv1.ElementNode { let { attrs, blockParams, modifiers, comments, children, loc } = options; let tagName: string; // this is used for backwards compat, prior to `selfClosing` being part of the ElementNode AST let selfClosing = false; if (typeof tag === 'object') { selfClosing = tag.selfClosing; tagName = tag.name; } else if (tag.slice(-1) === '/') { tagName = tag.slice(0, -1); selfClosing = true; } else { tagName = tag; } return { type: 'ElementNode', tag: tagName, selfClosing: selfClosing, attributes: attrs || [], blockParams: blockParams || [], modifiers: modifiers || [], comments: (comments as ASTv1.MustacheCommentStatement[]) || [], children: children || [], loc: buildLoc(loc || null), }; } function buildAttr( name: string, value: ASTv1.AttrNode['value'], loc?: SourceLocation ): ASTv1.AttrNode { return { type: 'AttrNode', name: name, value: value, loc: buildLoc(loc || null), }; } function buildText(chars?: string, loc?: SourceLocation): ASTv1.TextNode { return { type: 'TextNode', chars: chars || '', loc: buildLoc(loc || null), }; } // Expressions function buildSexpr( path: BuilderHead, params?: ASTv1.Expression[], hash?: ASTv1.Hash, loc?: SourceLocation ): ASTv1.SubExpression { return { type: 'SubExpression', path: buildPath(path), params: params || [], hash: hash || buildHash([]), loc: buildLoc(loc || null), }; } function headToString(head: ASTv1.PathHead): { original: string; parts: string[] } { switch (head.type) { case 'AtHead': return { original: head.name, parts: [head.name] }; case 'ThisHead': return { original: `this`, parts: [] }; case 'VarHead': return { original: head.name, parts: [head.name] }; } } function buildHead( original: string, loc: SourceLocation ): { head: ASTv1.PathHead; tail: string[] } { let [head, ...tail] = original.split('.'); let headNode: ASTv1.PathHead; if (head === 'this') { headNode = { type: 'ThisHead', loc: buildLoc(loc || null), }; } else if (head[0] === '@') { headNode = { type: 'AtHead', name: head, loc: buildLoc(loc || null), }; } else { headNode = { type: 'VarHead', name: head, loc: buildLoc(loc || null), }; } return { head: headNode, tail, }; } function buildThis(loc: SourceLocation): ASTv1.PathHead { return { type: 'ThisHead', loc: buildLoc(loc || null), }; } function buildAtName(name: string, loc: SourceLocation): ASTv1.PathHead { // the `@` should be included so we have a complete source range assert(name[0] === '@', `call builders.at() with a string that starts with '@'`); return { type: 'AtHead', name, loc: buildLoc(loc || null), }; } function buildVar(name: string, loc: SourceLocation): ASTv1.PathHead { assert(name !== 'this', `You called builders.var() with 'this'. Call builders.this instead`); assert( name[0] !== '@', `You called builders.var() with '${name}'. Call builders.at('${name}') instead` ); return { type: 'VarHead', name, loc: buildLoc(loc || null), }; } function buildHeadFromString(head: string, loc: SourceLocation): ASTv1.PathHead { if (head[0] === '@') { return buildAtName(head, loc); } else if (head === 'this') { return buildThis(loc); } else { return buildVar(head, loc); } } function buildNamedBlockName(name: string, loc?: SourceLocation): ASTv1.NamedBlockName { return { type: 'NamedBlockName', name, loc: buildLoc(loc || null), }; } function buildCleanPath( head: ASTv1.PathHead, tail: string[], loc: SourceLocation ): ASTv1.PathExpression { let { original: originalHead, parts: headParts } = headToString(head); let parts = [...headParts, ...tail]; let original = [...originalHead, ...parts].join('.'); return new PathExpressionImplV1(original, head, tail, buildLoc(loc || null)); } function buildPath( path: ASTv1.PathExpression | string | { head: string; tail: string[] }, loc?: SourceLocation ): ASTv1.PathExpression; function buildPath(path: ASTv1.Expression, loc?: SourceLocation): ASTv1.Expression; function buildPath(path: BuilderHead | ASTv1.Expression, loc?: SourceLocation): ASTv1.Expression; function buildPath( path: BuilderHead | ASTv1.Expression | { head: string; tail: string[] }, loc?: SourceLocation ): ASTv1.Expression { if (typeof path !== 'string') { if ('type' in path) { return path; } else { let { head, tail } = buildHead(path.head, SourceSpan.broken()); assert( tail.length === 0, `builder.path({ head, tail }) should not be called with a head with dots in it` ); let { original: originalHead } = headToString(head); return new PathExpressionImplV1( [originalHead, ...tail].join('.'), head, tail, buildLoc(loc || null) ); } } let { head, tail } = buildHead(path, SourceSpan.broken()); return new PathExpressionImplV1(path, head, tail, buildLoc(loc || null)); } function buildLiteral<T extends ASTv1.Literal>( type: T['type'], value: T['value'], loc?: SourceLocation ): T { return { type, value, original: value, loc: buildLoc(loc || null), } as T; } // Miscellaneous function buildHash(pairs?: ASTv1.HashPair[], loc?: SourceLocation): ASTv1.Hash { return { type: 'Hash', pairs: pairs || [], loc: buildLoc(loc || null), }; } function buildPair(key: string, value: ASTv1.Expression, loc?: SourceLocation): ASTv1.HashPair { return { type: 'HashPair', key: key, value, loc: buildLoc(loc || null), }; } function buildProgram( body?: ASTv1.Statement[], blockParams?: string[], loc?: SourceLocation ): ASTv1.Template { return { type: 'Template', body: body || [], blockParams: blockParams || [], loc: buildLoc(loc || null), }; } function buildBlockItself( body?: ASTv1.Statement[], blockParams?: string[], chained = false, loc?: SourceLocation ): ASTv1.Block { return { type: 'Block', body: body || [], blockParams: blockParams || [], chained, loc: buildLoc(loc || null), }; } function buildTemplate( body?: ASTv1.Statement[], blockParams?: string[], loc?: SourceLocation ): ASTv1.Template { return { type: 'Template', body: body || [], blockParams: blockParams || [], loc: buildLoc(loc || null), }; } function buildPosition(line: number, column: number): SourcePosition { return { line, column, }; } function buildLoc(loc: Option<SourceLocation>): SourceSpan; function buildLoc( startLine: number, startColumn: number, endLine?: number, endColumn?: number, source?: string ): SourceSpan; function buildLoc(...args: any[]): SourceSpan { if (args.length === 1) { let loc = args[0]; if (loc && typeof loc === 'object') { return SourceSpan.forHbsLoc(SOURCE(), loc); } else { return SourceSpan.forHbsLoc(SOURCE(), SYNTHETIC_LOCATION); } } else { let [startLine, startColumn, endLine, endColumn, _source] = args; let source = _source ? new Source('', _source) : SOURCE(); return SourceSpan.forHbsLoc(source, { start: { line: startLine, column: startColumn, }, end: { line: endLine, column: endColumn, }, }); } } export default { mustache: buildMustache, block: buildBlock, partial: buildPartial, comment: buildComment, mustacheComment: buildMustacheComment, element: buildElement, elementModifier: buildElementModifier, attr: buildAttr, text: buildText, sexpr: buildSexpr, concat: buildConcat, hash: buildHash, pair: buildPair, literal: buildLiteral, program: buildProgram, blockItself: buildBlockItself, template: buildTemplate, loc: buildLoc, pos: buildPosition, path: buildPath, fullPath: buildCleanPath, head: buildHeadFromString, at: buildAtName, var: buildVar, this: buildThis, blockName: buildNamedBlockName, string: literal('StringLiteral') as (value: string) => ASTv1.StringLiteral, boolean: literal('BooleanLiteral') as (value: boolean) => ASTv1.BooleanLiteral, number: literal('NumberLiteral') as (value: number) => ASTv1.NumberLiteral, undefined(): ASTv1.UndefinedLiteral { return buildLiteral('UndefinedLiteral', undefined); }, null(): ASTv1.NullLiteral { return buildLiteral('NullLiteral', null); }, }; type BuildLiteral<T extends ASTv1.Literal> = (value: T['value']) => T; function literal<T extends ASTv1.Literal>(type: T['type']): BuildLiteral<T> { return function (value: T['value'], loc?: SourceLocation): T { return buildLiteral(type, value, loc); }; }
the_stack
// export type SectionType = typeof SectionType[keyof typeof SectionType] export const SectionType = { Study: 'study', Break: 'break' } export type TimeSection = { starts: { h: number m: number } ends: { h: number m: number } sectionType: string sectionId: number partName: string } export function getCurrentSection(): TimeSection { // startsとendsの差は23時間未満とする const now: Date = new Date() for (const section of TimeTable) { const starts = section.starts const ends = section.ends // 適当に初期化 let startsDate = now let endsDate = now endsDate.setDate(now.getDate() - 1) if (starts.h <= ends.h) { startsDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), section.starts.h, section.starts.m) endsDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), section.ends.h, section.ends.m) } else { // 日付またがる時の場合 if ((starts.h == now.getHours() && starts.m <= now.getMinutes()) || (starts.h < now.getHours())) { startsDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), starts.h, starts.m) endsDate = new Date(now.getFullYear(), now.getMonth(), now.getDate()+1, ends.h, ends.m) } else if ((now.getHours() < ends.h) || (now.getHours() == ends.h && now.getMinutes() < ends.m)) { startsDate = new Date(now.getFullYear(), now.getMonth(), now.getDate()-1, starts.h, starts.m) endsDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), ends.h, ends.m) } } if (startsDate <= now && now < endsDate) { return section } } console.error('no current section.') return TimeTable[0] } export function getNextSection(): TimeSection | null{ const currentSection = getCurrentSection() if (currentSection !== null) { for (const section of TimeTable) { if (currentSection.ends.h === section.starts.h && currentSection.ends.m === section.starts.m) { return section } } } console.error('no next section.') return currentSection } export function remainingTime(currentHours: number, currentMinutes: number, destHours: number, destMinutes: number): number { if (currentHours === destHours) { return destMinutes - currentMinutes } else if (currentHours < destHours) { const diffHours: number = destHours - currentHours return 60*(diffHours - 1) + (60 - currentMinutes) + destMinutes } else { // 日付を跨いでいる return 60*(23 - currentHours) + (60 - currentMinutes) + 60*destHours + destMinutes } } export const partType = { Morning: '朝パート', BeforeNoon: '午前パート', Noon: '昼パート', AfterNoon1: '午後パートⅠ', AfterNoon2: '午後パートⅡ', Evening: '夕方パート', Night1: '夜パートⅠ', Night2: '夜パートⅡ', MidNight1: '深夜パートⅠ', MidNight2: '深夜パートⅡ', EarlyMorning: '早朝パート', } const TimeTable: TimeSection[] = [ { starts: {h: 0, m: 5}, ends: {h: 0, m: 25}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Night2 }, { starts: {h: 0, m: 25}, ends: {h: 0, m: 50}, sectionType: SectionType.Study, sectionId: 31, partName: partType.MidNight1, }, { starts: {h: 0, m: 50}, ends: {h: 0, m: 55}, sectionType: SectionType.Break, sectionId: 0, partName: partType.MidNight1, }, { starts: {h: 0, m: 55}, ends: {h: 1, m: 20}, sectionType: SectionType.Study, sectionId: 32, partName: partType.MidNight1, }, { starts: {h: 1, m: 20}, ends: {h: 1, m: 25}, sectionType: SectionType.Break, sectionId: 0, partName: partType.MidNight1, }, { starts: {h: 1, m: 25}, ends: {h: 1, m: 50}, sectionType: SectionType.Study, sectionId: 33, partName: partType.MidNight1, }, { starts: {h: 1, m: 50}, ends: {h: 1, m: 55}, sectionType: SectionType.Break, sectionId: 0, partName: partType.MidNight1, }, { starts: {h: 1, m: 55}, ends: {h: 2, m: 20}, sectionType: SectionType.Study, sectionId: 34, partName: partType.MidNight1, }, { starts: {h: 2, m: 20}, ends: {h: 2, m: 40}, sectionType: SectionType.Break, sectionId: 0, partName: partType.MidNight1, }, { starts: {h: 2, m: 40}, ends: {h: 3, m: 5}, sectionType: SectionType.Study, sectionId: 35, partName: partType.MidNight2, }, { starts: {h: 3, m: 5}, ends: {h: 3, m: 10}, sectionType: SectionType.Break, sectionId: 0, partName: partType.MidNight2, }, { starts: {h: 3, m: 10}, ends: {h: 3, m: 35}, sectionType: SectionType.Study, sectionId: 36, partName: partType.MidNight2, }, { starts: {h: 3, m: 35}, ends: {h: 3, m: 40}, sectionType: SectionType.Break, sectionId: 0, partName: partType.MidNight2, }, { starts: {h: 3, m: 40}, ends: {h: 4, m: 5}, sectionType: SectionType.Study, sectionId: 37, partName: partType.MidNight2, }, { starts: {h: 4, m: 5}, ends: {h: 4, m: 10}, sectionType: SectionType.Break, sectionId: 0, partName: partType.MidNight2, }, { starts: {h: 4, m: 10}, ends: {h: 4, m: 35}, sectionType: SectionType.Study, sectionId: 38, partName: partType.MidNight2, }, { starts: {h: 4, m: 35}, ends: {h: 4, m: 55}, sectionType: SectionType.Break, sectionId: 0, partName: partType.MidNight2, }, { starts: {h: 4, m: 55}, ends: {h: 5, m: 20}, sectionType: SectionType.Study, sectionId: 39, partName: partType.EarlyMorning, }, { starts: {h: 5, m: 20}, ends: {h: 5, m: 25}, sectionType: SectionType.Break, sectionId: 0, partName: partType.EarlyMorning, }, { starts: {h: 5, m: 25}, ends: {h: 5, m: 50}, sectionType: SectionType.Study, sectionId: 40, partName: partType.EarlyMorning, }, { starts: {h: 5, m: 50}, ends: {h: 5, m: 55}, sectionType: SectionType.Break, sectionId: 0, partName: partType.EarlyMorning, }, { starts: {h: 5, m: 55}, ends: {h: 6, m: 20}, sectionType: SectionType.Study, sectionId: 41, partName: partType.EarlyMorning, }, { starts: {h: 6, m: 20}, ends: {h: 6, m: 25}, sectionType: SectionType.Break, sectionId: 0, partName: partType.EarlyMorning, }, { starts: {h: 6, m: 25}, ends: {h: 6, m: 50}, sectionType: SectionType.Study, sectionId: 42, partName: partType.EarlyMorning, }, { starts: {h: 6, m: 50}, ends: {h: 7, m: 0}, sectionType: SectionType.Break, sectionId: 0, partName: partType.EarlyMorning, }, { starts: {h: 7, m: 0}, ends: {h: 7, m: 25}, sectionType: SectionType.Study, sectionId: 1, partName: partType.Morning, }, { starts: {h: 7, m: 25}, ends: {h: 7, m: 30}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Morning, }, { starts: {h: 7, m: 30}, ends: {h: 7, m: 55}, sectionType: SectionType.Study, sectionId: 2, partName: partType.Morning, }, { starts: {h: 7, m: 55}, ends: {h: 8, m: 0}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Morning, }, { starts: {h: 8, m: 0}, ends: {h: 8, m: 25}, sectionType: SectionType.Study, sectionId: 3, partName: partType.Morning, }, { starts: {h: 8, m: 25}, ends: {h: 8, m: 30}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Morning, }, { starts: {h: 8, m: 30}, ends: {h: 8, m: 55}, sectionType: SectionType.Study, sectionId: 4, partName: partType.Morning, }, { starts: {h: 8, m: 55}, ends: {h: 9, m: 15}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Morning, }, { starts: {h: 9, m: 15}, ends: {h: 9, m: 40}, sectionType: SectionType.Study, sectionId: 5, partName: partType.BeforeNoon, }, { starts: {h: 9, m: 40}, ends: {h: 9, m: 45}, sectionType: SectionType.Break, sectionId: 0, partName: partType.BeforeNoon, }, { starts: {h: 9, m: 45}, ends: {h: 10, m: 10}, sectionType: SectionType.Study, sectionId: 6, partName: partType.BeforeNoon, }, { starts: {h: 10, m: 10}, ends: {h: 10, m: 15}, sectionType: SectionType.Break, sectionId: 0, partName: partType.BeforeNoon, }, { starts: {h: 10, m: 15}, ends: {h: 10, m: 40}, sectionType: SectionType.Study, sectionId: 7, partName: partType.BeforeNoon, }, { starts: {h: 10, m: 40}, ends: {h: 10, m: 45}, sectionType: SectionType.Break, sectionId: 0, partName: partType.BeforeNoon, }, { starts: {h: 10, m: 45}, ends: {h: 11, m: 10}, sectionType: SectionType.Study, sectionId: 8, partName: partType.BeforeNoon, }, { starts: {h: 11, m: 10}, ends: {h: 11, m: 30}, sectionType: SectionType.Break, sectionId: 0, partName: partType.BeforeNoon, }, { starts: {h: 11, m: 30}, ends: {h: 11, m: 55}, sectionType: SectionType.Study, sectionId: 9, partName: partType.Noon, }, { starts: {h: 11, m: 55}, ends: {h: 12, m: 0}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Noon, }, { starts: {h: 12, m: 0}, ends: {h: 12, m: 25}, sectionType: SectionType.Study, sectionId: 10, partName: partType.Noon, }, { starts: {h: 12, m: 25}, ends: {h: 13, m: 0}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Noon, }, { starts: {h: 13, m: 0}, ends: {h: 13, m: 25}, sectionType: SectionType.Study, sectionId: 11, partName: partType.AfterNoon1, }, { starts: {h: 13, m: 25}, ends: {h: 13, m: 30}, sectionType: SectionType.Break, sectionId: 0, partName: partType.AfterNoon1, }, { starts: {h: 13, m: 30}, ends: {h: 13, m: 55}, sectionType: SectionType.Study, sectionId: 12, partName: partType.AfterNoon1, }, { starts: {h: 13, m: 55}, ends: {h: 14, m: 0}, sectionType: SectionType.Break, sectionId: 0, partName: partType.AfterNoon1, }, { starts: {h: 14, m: 0}, ends: {h: 14, m: 25}, sectionType: SectionType.Study, sectionId: 13, partName: partType.AfterNoon1, }, { starts: {h: 14, m: 25}, ends: {h: 14, m: 30}, sectionType: SectionType.Break, sectionId: 0, partName: partType.AfterNoon1, }, { starts: {h: 14, m: 30}, ends: {h: 14, m: 55}, sectionType: SectionType.Study, sectionId: 14, partName: partType.AfterNoon1, }, { starts: {h: 14, m: 55}, ends: {h: 15, m: 15}, sectionType: SectionType.Break, sectionId: 0, partName: partType.AfterNoon1, }, { starts: {h: 15, m: 15}, ends: {h: 15, m: 40}, sectionType: SectionType.Study, sectionId: 15, partName: partType.AfterNoon2, }, { starts: {h: 15, m: 40}, ends: {h: 15, m: 45}, sectionType: SectionType.Break, sectionId: 0, partName: partType.AfterNoon2, }, { starts: {h: 15, m: 45}, ends: {h: 16, m: 10}, sectionType: SectionType.Study, sectionId: 16, partName: partType.AfterNoon2, }, { starts: {h: 16, m: 10}, ends: {h: 16, m: 15}, sectionType: SectionType.Break, sectionId: 0, partName: partType.AfterNoon2, }, { starts: {h: 16, m: 15}, ends: {h: 16, m: 40}, sectionType: SectionType.Study, sectionId: 17, partName: partType.AfterNoon2, }, { starts: {h: 16, m: 40}, ends: {h: 16, m: 45}, sectionType: SectionType.Break, sectionId: 0, partName: partType.AfterNoon2, }, { starts: {h: 16, m: 45}, ends: {h: 17, m: 10}, sectionType: SectionType.Study, sectionId: 18, partName: partType.AfterNoon2, }, { starts: {h: 17, m: 10}, ends: {h: 17, m: 40}, sectionType: SectionType.Break, sectionId: 0, partName: partType.AfterNoon2, }, { starts: {h: 17, m: 40}, ends: {h: 18, m: 5}, sectionType: SectionType.Study, sectionId: 19, partName: partType.Evening, }, { starts: {h: 18, m: 5}, ends: {h: 18, m: 10}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Evening, }, { starts: {h: 18, m: 10}, ends: {h: 18, m: 35}, sectionType: SectionType.Study, sectionId: 20, partName: partType.Evening, }, { starts: {h: 18, m: 35}, ends: {h: 18, m: 40}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Evening, }, { starts: {h: 18, m: 40}, ends: {h: 19, m: 5}, sectionType: SectionType.Study, sectionId: 21, partName: partType.Evening, }, { starts: {h: 19, m: 5}, ends: {h: 19, m: 10}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Evening, }, { starts: {h: 19, m: 10}, ends: {h: 19, m: 35}, sectionType: SectionType.Study, sectionId: 22, partName: partType.Evening, }, { starts: {h: 19, m: 35}, ends: {h: 19, m: 55}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Evening, }, { starts: {h: 19, m: 55}, ends: {h: 20, m: 20}, sectionType: SectionType.Study, sectionId: 23, partName: partType.Night1, }, { starts: {h: 20, m: 20}, ends: {h: 20, m: 25}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Night1, }, { starts: {h: 20, m: 25}, ends: {h: 20, m: 50}, sectionType: SectionType.Study, sectionId: 24, partName: partType.Night1, }, { starts: {h: 20, m: 50}, ends: {h: 20, m: 55}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Night1, }, { starts: {h: 20, m: 55}, ends: {h: 21, m: 20}, sectionType: SectionType.Study, sectionId: 25, partName: partType.Night1, }, { starts: {h: 21, m: 20}, ends: {h: 21, m: 25}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Night1, }, { starts: {h: 21, m: 25}, ends: {h: 21, m: 50}, sectionType: SectionType.Study, sectionId: 26, partName: partType.Night1, }, { starts: {h: 21, m: 50}, ends: {h: 22, m: 10}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Night2, }, { starts: {h: 22, m: 10}, ends: {h: 22, m: 35}, sectionType: SectionType.Study, sectionId: 27, partName: partType.Night2, }, { starts: {h: 22, m: 35}, ends: {h: 22, m: 40}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Night2, }, { starts: {h: 22, m: 40}, ends: {h: 23, m: 5}, sectionType: SectionType.Study, sectionId: 28, partName: partType.Night2, }, { starts: {h: 23, m: 5}, ends: {h: 23, m: 10}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Night2, }, { starts: {h: 23, m: 10}, ends: {h: 23, m: 35}, sectionType: SectionType.Study, sectionId: 29, partName: partType.Night2, }, { starts: {h: 23, m: 35}, ends: {h: 23, m: 40}, sectionType: SectionType.Break, sectionId: 0, partName: partType.Night2, }, { starts: {h: 23, m: 40}, ends: {h: 0, m: 5}, sectionType: SectionType.Study, sectionId: 30, partName: partType.Night2, }, ] export default {TimeTable}
the_stack
/** @hidden */ const POW_2_24 = 5.960464477539063e-8 /** @hidden */ const POW_2_32 = 4294967296 /** @hidden */ const POW_2_53 = 9007199254740992; /** @hidden */ const DECODE_CHUNK_SIZE = 8192 /** @hidden */ function objectIs(x: any, y: any) { if (typeof Object.is === 'function') { return Object.is(x, y); } // SameValue algorithm // Steps 1-5, 7-10 if (x === y) { // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } // Step 6.a: NaN == NaN return x !== x && y !== y } /** A Function that extracts tagged values. */ type TaggedValueFunction = (value: any, tag: number) => TaggedValue; /** A function that extracts simple values. */ type SimpleValueFunction = (value: any) => SimpleValue; /** Convenience class for structuring a tagged value. */ export class TaggedValue { public value: any; public tag: number; constructor(value: any, tag: number) { this.value = value; this.tag = tag; } } /** Convenience class for structuring a simple value. */ export class SimpleValue { public value: any; constructor(value: any) { this.value = value } } /* tslint:disable:no-bitwise */ export function decode<T = any>( data: ArrayBuffer | SharedArrayBuffer, tagger?: TaggedValueFunction, simpleValue?: SimpleValueFunction, ): T { const dataView = new DataView(data); const ta = new Uint8Array(data); let offset = 0; let tagValueFunction = (value: any, tag: number) => { return new TaggedValue(value, tag); } let simpleValueFunction = (value: any) => { return new SimpleValue(value); } if (typeof tagger === 'function') { tagValueFunction = tagger; } if (typeof simpleValue === 'function') { simpleValueFunction = simpleValue; } function commitRead(length: number, value: any) { offset += length; return value; } function readArrayBuffer(length: number) { return commitRead(length, new Uint8Array(data, offset, length)); } function readFloat16() { const tempArrayBuffer = new ArrayBuffer(4); const tempDataView = new DataView(tempArrayBuffer); const value = readUint16(); const sign = value & 0x8000 let exponent = value & 0x7c00 const fraction = value & 0x03ff if (exponent === 0x7c00) { exponent = 0xff << 10; } else if (exponent !== 0) { exponent += (127 - 15) << 10; } else if (fraction !== 0) { return (sign ? -1 : 1) * fraction * POW_2_24; } tempDataView.setUint32(0, (sign << 16) | (exponent << 13) | (fraction << 13)); return tempDataView.getFloat32(0); } function readFloat32(): number { return commitRead(4, dataView.getFloat32(offset)); } function readFloat64(): number { return commitRead(8, dataView.getFloat64(offset)); } function readUint8(): number { return commitRead(1, ta[offset]); } function readUint16(): number { return commitRead(2, dataView.getUint16(offset)); } function readUint32(): number { return commitRead(4, dataView.getUint32(offset)); } function readUint64(): number { return readUint32() * POW_2_32 + readUint32(); } function readBreak(): boolean { if (ta[offset] !== 0xff) { return false; } offset += 1; return true; } function readLength(additionalInformation: number): number { if (additionalInformation < 24) { return additionalInformation; } else if (additionalInformation === 24) { return readUint8(); } else if (additionalInformation === 25) { return readUint16(); } else if (additionalInformation === 26) { return readUint32(); } else if (additionalInformation === 27) { return readUint64(); } else if (additionalInformation === 31) { return -1; } throw new Error('Invalid length encoding') } function readIndefiniteStringLength(majorType: number): number { const initialByte = readUint8(); if (initialByte === 0xff) { return -1; } const length = readLength(initialByte & 0x1f); if (length < 0 || initialByte >> 5 !== majorType) { throw new Error('Invalid indefinite length element'); } return length; } function appendUtf16Data(utf16data: number[], length: number) { for (let i = 0; i < length; ++i) { let value = readUint8(); if (value & 0x80) { if (value < 0xe0) { value = ((value & 0x1f) << 6) | (readUint8() & 0x3f); length -= 1; } else if (value < 0xf0) { value = ((value & 0x0f) << 12) | ((readUint8() & 0x3f) << 6) | (readUint8() & 0x3f); length -= 2; } else { value = ((value & 0x0f) << 18) | ((readUint8() & 0x3f) << 12) | ((readUint8() & 0x3f) << 6) | (readUint8() & 0x3f); length -= 3; } } if (value < 0x10000) { utf16data.push(value); } else { value -= 0x10000; utf16data.push(0xd800 | (value >> 10)); utf16data.push(0xdc00 | (value & 0x3ff)); } } } function decodeItem(): any { const initialByte = readUint8(); const majorType = initialByte >> 5; const additionalInformation = initialByte & 0x1f; let i; let length; if (majorType === 7) { switch (additionalInformation) { case 25: return readFloat16(); case 26: return readFloat32(); case 27: return readFloat64(); } } length = readLength(additionalInformation); if (length < 0 && (majorType < 2 || 6 < majorType)) { throw new Error('Invalid length'); } switch (majorType) { case 0: return length; case 1: return -1 - length; case 2: if (length < 0) { const elements = []; let fullArrayLength = 0; length = readIndefiniteStringLength(majorType); while (length >= 0) { fullArrayLength += length; elements.push(readArrayBuffer(length)); } const fullArray = new Uint8Array(fullArrayLength); let fullArrayOffset = 0; for (i = 0; i < elements.length; ++i) { fullArray.set(elements[i], fullArrayOffset); fullArrayOffset += elements[i].length; } return fullArray; } return readArrayBuffer(length); case 3: const utf16data: number[] = []; if (length < 0) { length = readIndefiniteStringLength(majorType); while (length >= 0) { appendUtf16Data(utf16data, length); } } else { appendUtf16Data(utf16data, length); } let str = ''; for (i = 0; i < utf16data.length; i += DECODE_CHUNK_SIZE) { str += String.fromCharCode.apply(null, utf16data.slice(i, i + DECODE_CHUNK_SIZE)); } return str; case 4: let retArray; if (length < 0) { retArray = []; while (!readBreak()) { retArray.push(decodeItem()); } } else { retArray = new Array(length); for (i = 0; i < length; ++i) { retArray[i] = decodeItem(); } } return retArray; case 5: const retObject: any = {}; for (i = 0; i < length || (length < 0 && !readBreak()); ++i) { const key = decodeItem(); retObject[key] = decodeItem(); } return retObject; case 6: return tagValueFunction(decodeItem(), length); case 7: switch (length) { case 20: return false; case 21: return true; case 22: return null; case 23: return undefined; default: return simpleValueFunction(length); } } } const ret = decodeItem(); if (offset !== data.byteLength) { throw new Error('Remaining bytes'); } return ret; } export function encode<T = any>(value: T): ArrayBuffer { let data = new ArrayBuffer(256); let dataView = new DataView(data); let byteView = new Uint8Array(data); let lastLength: number; let offset = 0; function prepareWrite(length: number): DataView { let newByteLength = data.byteLength; const requiredLength = offset + length; while (newByteLength < requiredLength) { newByteLength <<= 1; } if (newByteLength !== data.byteLength) { const oldDataView = dataView; data = new ArrayBuffer(newByteLength); dataView = new DataView(data); byteView = new Uint8Array(data); const uint32count = (offset + 3) >> 2; for (let i = 0; i < uint32count; ++i) { dataView.setUint32(i << 2, oldDataView.getUint32(i << 2)); } } lastLength = length; return dataView; } function commitWrite(...args: any[]) { offset += lastLength; } function writeFloat64(val: number) { commitWrite(prepareWrite(8).setFloat64(offset, val)); } function writeUint8(val: number) { commitWrite(prepareWrite(1).setUint8(offset, val)); } function writeUint8Array(val: number[] | Uint8Array) { prepareWrite(val.length); byteView.set(val, offset); commitWrite(); } function writeUint16(val: number) { commitWrite(prepareWrite(2).setUint16(offset, val)); } function writeUint32(val: number) { commitWrite(prepareWrite(4).setUint32(offset, val)); } function writeUint64(val: number) { const low = val % POW_2_32; const high = (val - low) / POW_2_32; const view = prepareWrite(8); view.setUint32(offset, high); view.setUint32(offset + 4, low); commitWrite(); } function writeVarUint(val: number, mod: number) { if (val <= 0xff) { if (val < 24) { writeUint8(val | mod); } else { writeUint8(0x18 | mod); writeUint8(val); } } else if (val <= 0xffff) { writeUint8(0x19 | mod); writeUint16(val); } else if (val <= 0xffffffff) { writeUint8(0x1a | mod); writeUint32(val); } else { writeUint8(0x1b | mod); writeUint64(val); } } function writeTypeAndLength(type: number, length: number) { if (length < 24) { writeUint8((type << 5) | length); } else if (length < 0x100) { writeUint8((type << 5) | 24); writeUint8(length); } else if (length < 0x10000) { writeUint8((type << 5) | 25); writeUint16(length); } else if (length < 0x100000000) { writeUint8((type << 5) | 26); writeUint32(length); } else { writeUint8((type << 5) | 27); writeUint64(length); } } function encodeItem(val: any) { let i; if (val === false) { return writeUint8(0xf4); } else if (val === true) { return writeUint8(0xf5); } else if (val === null) { return writeUint8(0xf6); } else if (val === undefined) { return writeUint8(0xf7); } else if (objectIs(val, -0)) { return writeUint8Array([0xf9, 0x80, 0x00]); } switch (typeof val) { case 'number': if (Math.floor(val) === val) { if (0 <= val && val <= POW_2_53) { return writeTypeAndLength(0, val); } else if (-POW_2_53 <= val && val < 0) { return writeTypeAndLength(1, -(val + 1)); } } writeUint8(0xfb); return writeFloat64(val); case 'string': const utf8data = []; for (i = 0; i < val.length; i++) { let charCode = val.charCodeAt(i); if (charCode < 0x80) { utf8data.push(charCode); } else if (charCode < 0x800) { utf8data.push(0xc0 | (charCode >> 6)); utf8data.push(0x80 | (charCode & 0x3f)); } else { charCode = (charCode & 0x3ff) << 10; charCode |= val.charCodeAt(++i) & 0x3ff; charCode += 0x10000; utf8data.push(0xf0 | (charCode >> 18)); utf8data.push(0x80 | ((charCode >> 12) & 0x3f)); utf8data.push(0x80 | ((charCode >> 6) & 0x3f)); utf8data.push(0x80 | (charCode & 0x3f)); } } writeTypeAndLength(3, utf8data.length); return writeUint8Array(utf8data); default: let length; let converted; if (Array.isArray(val)) { length = val.length; writeTypeAndLength(4, length); for (i = 0; i < length; i++) { encodeItem(val[i]); } } else if (val instanceof Uint8Array) { writeTypeAndLength(2, val.length); writeUint8Array(val); } else if (ArrayBuffer.isView(val)) { converted = new Uint8Array(val.buffer); writeTypeAndLength(2, converted.length); writeUint8Array(converted); } else if (val instanceof ArrayBuffer || (typeof SharedArrayBuffer === 'function' && val instanceof SharedArrayBuffer)) { converted = new Uint8Array(val); writeTypeAndLength(2, converted.length); writeUint8Array(converted); } else if (val instanceof TaggedValue) { writeVarUint(val.tag, 0b11000000) encodeItem(val.value) } else { const keys = Object.keys(val); length = keys.length; writeTypeAndLength(5, length); for (i = 0; i < length; i++) { const key = keys[i]; encodeItem(key); encodeItem(val[key]); } } } } encodeItem(value); if ('slice' in data) { return data.slice(0, offset); } const ret = new ArrayBuffer(offset); const retView = new DataView(ret); for (let i = 0; i < offset; ++i) { retView.setUint8(i, dataView.getUint8(i)); } return ret; } /* tslint:enable:no-bitwise */
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Allows configuring a single access level condition to be appended to an access level's conditions. * This resource is intended to be used in cases where it is not possible to compile a full list * of conditions to include in a `gcp.accesscontextmanager.AccessLevel` resource, * to enable them to be added separately. * * > **Note:** If this resource is used alongside a `gcp.accesscontextmanager.AccessLevel` resource, * the access level resource must have a `lifecycle` block with `ignoreChanges = [basic[0].conditions]` so * they don't fight over which service accounts should be included. * * To get more information about AccessLevelCondition, see: * * * [API documentation](https://cloud.google.com/access-context-manager/docs/reference/rest/v1/accessPolicies.accessLevels) * * How-to Guides * * [Access Policy Quickstart](https://cloud.google.com/access-context-manager/docs/quickstart) * * > **Warning:** If you are using User ADCs (Application Default Credentials) with this resource, * you must specify a `billingProject` and set `userProjectOverride` to true * in the provider configuration. Otherwise the ACM API will return a 403 error. * Your account must have the `serviceusage.services.use` permission on the * `billingProject` you defined. * * ## Example Usage * * ## Import * * This resource does not support import. */ export class AccessLevelCondition extends pulumi.CustomResource { /** * Get an existing AccessLevelCondition resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: AccessLevelConditionState, opts?: pulumi.CustomResourceOptions): AccessLevelCondition { return new AccessLevelCondition(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:accesscontextmanager/accessLevelCondition:AccessLevelCondition'; /** * Returns true if the given object is an instance of AccessLevelCondition. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is AccessLevelCondition { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === AccessLevelCondition.__pulumiType; } /** * The name of the Access Level to add this condition to. */ public readonly accessLevel!: pulumi.Output<string>; /** * Device specific restrictions, all restrictions must hold for * the Condition to be true. If not specified, all devices are * allowed. * Structure is documented below. */ public readonly devicePolicy!: pulumi.Output<outputs.accesscontextmanager.AccessLevelConditionDevicePolicy | undefined>; /** * A list of CIDR block IP subnetwork specification. May be IPv4 * or IPv6. * Note that for a CIDR IP address block, the specified IP address * portion must be properly truncated (i.e. all the host bits must * be zero) or the input is considered malformed. For example, * "192.0.2.0/24" is accepted but "192.0.2.1/24" is not. Similarly, * for IPv6, "2001:db8::/32" is accepted whereas "2001:db8::1/32" * is not. The originating IP of a request must be in one of the * listed subnets in order for this Condition to be true. * If empty, all IP addresses are allowed. */ public readonly ipSubnetworks!: pulumi.Output<string[] | undefined>; /** * An allowed list of members (users, service accounts). * Using groups is not supported yet. * The signed-in user originating the request must be a part of one * of the provided members. If not specified, a request may come * from any user (logged in/not logged in, not present in any * groups, etc.). * Formats: `user:{emailid}`, `serviceAccount:{emailid}` */ public readonly members!: pulumi.Output<string[] | undefined>; /** * Whether to negate the Condition. If true, the Condition becomes * a NAND over its non-empty fields, each field must be false for * the Condition overall to be satisfied. Defaults to false. */ public readonly negate!: pulumi.Output<boolean | undefined>; /** * The request must originate from one of the provided * countries/regions. * Format: A valid ISO 3166-1 alpha-2 code. */ public readonly regions!: pulumi.Output<string[] | undefined>; /** * A list of other access levels defined in the same Policy, * referenced by resource name. Referencing an AccessLevel which * does not exist is an error. All access levels listed must be * granted for the Condition to be true. * Format: accessPolicies/{policy_id}/accessLevels/{short_name} */ public readonly requiredAccessLevels!: pulumi.Output<string[] | undefined>; /** * Create a AccessLevelCondition resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: AccessLevelConditionArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: AccessLevelConditionArgs | AccessLevelConditionState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as AccessLevelConditionState | undefined; inputs["accessLevel"] = state ? state.accessLevel : undefined; inputs["devicePolicy"] = state ? state.devicePolicy : undefined; inputs["ipSubnetworks"] = state ? state.ipSubnetworks : undefined; inputs["members"] = state ? state.members : undefined; inputs["negate"] = state ? state.negate : undefined; inputs["regions"] = state ? state.regions : undefined; inputs["requiredAccessLevels"] = state ? state.requiredAccessLevels : undefined; } else { const args = argsOrState as AccessLevelConditionArgs | undefined; if ((!args || args.accessLevel === undefined) && !opts.urn) { throw new Error("Missing required property 'accessLevel'"); } inputs["accessLevel"] = args ? args.accessLevel : undefined; inputs["devicePolicy"] = args ? args.devicePolicy : undefined; inputs["ipSubnetworks"] = args ? args.ipSubnetworks : undefined; inputs["members"] = args ? args.members : undefined; inputs["negate"] = args ? args.negate : undefined; inputs["regions"] = args ? args.regions : undefined; inputs["requiredAccessLevels"] = args ? args.requiredAccessLevels : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(AccessLevelCondition.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering AccessLevelCondition resources. */ export interface AccessLevelConditionState { /** * The name of the Access Level to add this condition to. */ accessLevel?: pulumi.Input<string>; /** * Device specific restrictions, all restrictions must hold for * the Condition to be true. If not specified, all devices are * allowed. * Structure is documented below. */ devicePolicy?: pulumi.Input<inputs.accesscontextmanager.AccessLevelConditionDevicePolicy>; /** * A list of CIDR block IP subnetwork specification. May be IPv4 * or IPv6. * Note that for a CIDR IP address block, the specified IP address * portion must be properly truncated (i.e. all the host bits must * be zero) or the input is considered malformed. For example, * "192.0.2.0/24" is accepted but "192.0.2.1/24" is not. Similarly, * for IPv6, "2001:db8::/32" is accepted whereas "2001:db8::1/32" * is not. The originating IP of a request must be in one of the * listed subnets in order for this Condition to be true. * If empty, all IP addresses are allowed. */ ipSubnetworks?: pulumi.Input<pulumi.Input<string>[]>; /** * An allowed list of members (users, service accounts). * Using groups is not supported yet. * The signed-in user originating the request must be a part of one * of the provided members. If not specified, a request may come * from any user (logged in/not logged in, not present in any * groups, etc.). * Formats: `user:{emailid}`, `serviceAccount:{emailid}` */ members?: pulumi.Input<pulumi.Input<string>[]>; /** * Whether to negate the Condition. If true, the Condition becomes * a NAND over its non-empty fields, each field must be false for * the Condition overall to be satisfied. Defaults to false. */ negate?: pulumi.Input<boolean>; /** * The request must originate from one of the provided * countries/regions. * Format: A valid ISO 3166-1 alpha-2 code. */ regions?: pulumi.Input<pulumi.Input<string>[]>; /** * A list of other access levels defined in the same Policy, * referenced by resource name. Referencing an AccessLevel which * does not exist is an error. All access levels listed must be * granted for the Condition to be true. * Format: accessPolicies/{policy_id}/accessLevels/{short_name} */ requiredAccessLevels?: pulumi.Input<pulumi.Input<string>[]>; } /** * The set of arguments for constructing a AccessLevelCondition resource. */ export interface AccessLevelConditionArgs { /** * The name of the Access Level to add this condition to. */ accessLevel: pulumi.Input<string>; /** * Device specific restrictions, all restrictions must hold for * the Condition to be true. If not specified, all devices are * allowed. * Structure is documented below. */ devicePolicy?: pulumi.Input<inputs.accesscontextmanager.AccessLevelConditionDevicePolicy>; /** * A list of CIDR block IP subnetwork specification. May be IPv4 * or IPv6. * Note that for a CIDR IP address block, the specified IP address * portion must be properly truncated (i.e. all the host bits must * be zero) or the input is considered malformed. For example, * "192.0.2.0/24" is accepted but "192.0.2.1/24" is not. Similarly, * for IPv6, "2001:db8::/32" is accepted whereas "2001:db8::1/32" * is not. The originating IP of a request must be in one of the * listed subnets in order for this Condition to be true. * If empty, all IP addresses are allowed. */ ipSubnetworks?: pulumi.Input<pulumi.Input<string>[]>; /** * An allowed list of members (users, service accounts). * Using groups is not supported yet. * The signed-in user originating the request must be a part of one * of the provided members. If not specified, a request may come * from any user (logged in/not logged in, not present in any * groups, etc.). * Formats: `user:{emailid}`, `serviceAccount:{emailid}` */ members?: pulumi.Input<pulumi.Input<string>[]>; /** * Whether to negate the Condition. If true, the Condition becomes * a NAND over its non-empty fields, each field must be false for * the Condition overall to be satisfied. Defaults to false. */ negate?: pulumi.Input<boolean>; /** * The request must originate from one of the provided * countries/regions. * Format: A valid ISO 3166-1 alpha-2 code. */ regions?: pulumi.Input<pulumi.Input<string>[]>; /** * A list of other access levels defined in the same Policy, * referenced by resource name. Referencing an AccessLevel which * does not exist is an error. All access levels listed must be * granted for the Condition to be true. * Format: accessPolicies/{policy_id}/accessLevels/{short_name} */ requiredAccessLevels?: pulumi.Input<pulumi.Input<string>[]>; }
the_stack
import React, { useEffect } from "react"; import Chart from "chart.js"; import { SiteVariablesPrepared } from "@fluentui/react-northstar"; import { IChartData } from "../ChartTypes"; import { tooltipTrigger, tooltipAxisYLine, chartConfig, axesConfig, setTooltipColorScheme, hexToRgb, } from "../ChartUtils"; import { TeamsTheme } from "../../../themes"; import { ChartContainer } from "./ChartContainer"; import { lineChartPatterns } from "../ChartPatterns"; import { getText } from "../../../translations"; export const LineChart = ({ title, data, siteVariables, gradients, }: { title: string; data: IChartData; siteVariables: SiteVariablesPrepared; gradients?: boolean; }) => { const { colorScheme, theme, t } = siteVariables; const canvasRef = React.useRef<HTMLCanvasElement | null>(null); const chartRef = React.useRef<Chart | undefined>(); const chartId = React.useMemo( () => Math.random().toString(36).substr(2, 9), [] ); const chartDataPointColors = React.useMemo( () => [ colorScheme.brand.background, colorScheme.default.borderHover, colorScheme.brand.borderHover, colorScheme.default.foreground2, colorScheme.brand.background4, colorScheme.default.foreground, ], [theme] ); const createDataPoints = (): Chart.ChartDataSets[] => Array.from(data.datasets, (set, i) => { let dataPointConfig = { label: getText(t.locale, set.label), data: set.data, borderColor: chartDataPointColors[i], hoverBorderColor: chartDataPointColors[i], hoverBorderWidth: 2, backgroundColor: "transparent", hoverBackgroundColor: "transparent", borderWidth: 2, pointBorderColor: chartDataPointColors[i], pointBackgroundColor: chartDataPointColors[i], pointHoverBackgroundColor: chartDataPointColors[i], pointHoverBorderColor: chartDataPointColors[i], pointHoverBorderWidth: 0, borderCapStyle: "round", borderJoinStyle: "round", pointBorderWidth: 0, pointRadius: 2, pointHoverRadius: 2, pointStyle: "circle", borderDash: [], }; if (theme === TeamsTheme.HighContrast) { dataPointConfig = { ...dataPointConfig, borderColor: colorScheme.brand.background, hoverBorderColor: colorScheme.default.borderHover, pointBorderColor: colorScheme.brand.background, pointBackgroundColor: colorScheme.brand.background, pointHoverBackgroundColor: colorScheme.brand.background, pointHoverBorderColor: colorScheme.brand.background, hoverBorderWidth: 4, pointRadius: 4, pointHoverRadius: 4, pointStyle: lineChartPatterns[i].pointStyle, borderDash: lineChartPatterns[i].lineBorderDash, } as any; } return dataPointConfig as Chart.ChartDataSets; }); const createAreaChartDataPoints = ( ctx: CanvasRenderingContext2D ): Chart.ChartDataSets[] => Array.from(data.datasets, (set, i) => { const gradientStroke = ctx.createLinearGradient( 0, 0, 0, ctx.canvas.clientHeight * 0.8 ); const hoverGradientStroke = ctx.createLinearGradient( 0, 0, 0, ctx.canvas.clientHeight * 0.8 ); if (theme === TeamsTheme.HighContrast) { const colorRGB = hexToRgb(colorScheme.brand.background); const hoverColorRGB = hexToRgb(colorScheme.default.borderHover); gradientStroke.addColorStop(0, `rgba(${colorRGB}, .2)`); gradientStroke.addColorStop(1, `rgba(${colorRGB}, .0)`); hoverGradientStroke.addColorStop(0, `rgba(${hoverColorRGB}, .4)`); hoverGradientStroke.addColorStop(1, `rgba(${hoverColorRGB}, .0)`); } else { const colorRGB = hexToRgb(chartDataPointColors[i]); gradientStroke.addColorStop(0, `rgba(${colorRGB}, .4)`); gradientStroke.addColorStop(1, `rgba(${colorRGB}, .0)`); hoverGradientStroke.addColorStop(0, `rgba(${colorRGB}, .6)`); hoverGradientStroke.addColorStop(1, `rgba(${colorRGB}, .0)`); } let dataPointConfig = { label: getText(t.locale, set.label), data: set.data, borderColor: chartDataPointColors[i], hoverBorderColor: chartDataPointColors[i], hoverBorderWidth: 2, backgroundColor: gradientStroke as any, hoverBackgroundColor: hoverGradientStroke as any, borderWidth: 2, pointBorderColor: chartDataPointColors[i], pointBackgroundColor: chartDataPointColors[i], pointHoverBackgroundColor: chartDataPointColors[i], pointHoverBorderColor: chartDataPointColors[i], pointHoverBorderWidth: 0, borderCapStyle: "round", borderJoinStyle: "round", pointBorderWidth: 0, pointRadius: 2, pointHoverRadius: 2, pointStyle: "circle", borderDash: [], }; if (theme === TeamsTheme.HighContrast) { dataPointConfig = { ...dataPointConfig, borderColor: colorScheme.brand.background, hoverBorderColor: colorScheme.default.borderHover, pointBorderColor: colorScheme.brand.background, pointBackgroundColor: colorScheme.brand.background, pointHoverBackgroundColor: colorScheme.brand.background, pointHoverBorderColor: colorScheme.brand.background, hoverBorderWidth: 4, pointRadius: 4, pointHoverRadius: 4, pointStyle: lineChartPatterns[i].pointStyle, borderDash: lineChartPatterns[i].lineBorderDash, } as any; } return dataPointConfig as Chart.ChartDataSets; }); useEffect(() => { let selectedIndex = -1; let selectedDataSet = 0; if (!canvasRef.current) return; const ctx = canvasRef.current.getContext("2d"); if (!ctx) return; chartRef.current = new Chart(ctx, { ...(chartConfig({ type: "line" }) as any), data: { labels: Array.isArray(data.labels) ? data.labels.map((label) => getText(t.locale, label)) : getText(t.locale, data.labels), datasets: [], }, plugins: [ { afterDatasetsDraw: ({ ctx, tooltip, chart }: any) => { tooltipAxisYLine({ chart, ctx, tooltip, }); }, }, ], }); const chart: any = chartRef.current; /** * Keyboard manipulations */ function meta() { return chart.getDatasetMeta(selectedDataSet); } function removeFocusStyleOnClick() { // Remove focus state style if selected by mouse if (canvasRef.current) { canvasRef.current.style.boxShadow = "none"; } } function removeDataPointsHoverStates() { if (selectedIndex > -1) { meta().controller.removeHoverStyle( meta().data[selectedIndex], 0, selectedIndex ); } } function hoverDataPoint(pointID: number) { meta().controller.setHoverStyle( meta().data[pointID], selectedDataSet, pointID ); } function showFocusedDataPoint() { hoverDataPoint(selectedIndex); tooltipTrigger({ chart: chartRef.current as any, data, set: selectedDataSet, index: selectedIndex, siteVariables, }); document .getElementById( `${chartId}-tooltip-${selectedDataSet}-${selectedIndex}` ) ?.focus(); } function resetChartStates() { removeDataPointsHoverStates(); const activeElements = chart.tooltip._active; const requestedElem = chart.getDatasetMeta(selectedDataSet).data[ selectedIndex ]; activeElements.find((v: any, i: number) => { if (requestedElem._index === v._index) { activeElements.splice(i, 1); return true; } }); for (let i = 0; i < activeElements.length; i++) { if (requestedElem._index === activeElements[i]._index) { activeElements.splice(i, 1); break; } } if (theme === TeamsTheme.HighContrast) { chart.data.datasets.map((dataset: any) => { dataset.borderColor = colorScheme.default.border; dataset.borderWidth = 2; }); chart.update(); } chart.tooltip._active = activeElements; chart.tooltip.update(true); chart.draw(); } function changeFocus(e: KeyboardEvent) { removeDataPointsHoverStates(); switch (e.key) { case "ArrowRight": e.preventDefault(); selectedIndex = (selectedIndex + 1) % meta().data.length; break; case "ArrowLeft": e.preventDefault(); selectedIndex = (selectedIndex || meta().data.length) - 1; break; case "ArrowUp": case "ArrowDown": e.preventDefault(); if (data.datasets.length > 1) { // Get all values for the current data point const values = data.datasets.map( (dataset) => dataset.data[selectedIndex] ); // Sort an array to define next available number const sorted = [...Array.from(new Set(values))].sort( (a, b) => Number(a) - Number(b) ); let nextValue = sorted[ sorted.findIndex((v) => v === values[selectedDataSet]) + (e.key === "ArrowUp" ? 1 : -1) ]; // Find dataset ID by the next higher number after current let nextDataSet = values.findIndex((v) => v === nextValue); // If there is no next number that could selected, get number from oposite side if (nextDataSet < 0) { nextDataSet = values.findIndex( (v) => v === sorted[e.key === "ArrowUp" ? 0 : data.datasets.length - 1] ); } selectedDataSet = nextDataSet; selectedIndex = selectedIndex % meta().data.length; } break; } showFocusedDataPoint(); } canvasRef.current.addEventListener("click", removeFocusStyleOnClick); canvasRef.current.addEventListener("keydown", changeFocus); canvasRef.current.addEventListener("focusout", resetChartStates); return () => { if (!chartRef.current) return; if (canvasRef.current) { canvasRef.current.removeEventListener("click", removeFocusStyleOnClick); canvasRef.current.removeEventListener("keydown", changeFocus); canvasRef.current.removeEventListener("focusout", resetChartStates); } chartRef.current.destroy(); }; }, []); /** * Theme updates */ useEffect(() => { if (!chartRef.current) return; if (!canvasRef.current) return; const ctx = canvasRef.current.getContext("2d"); if (!ctx) return; // Apply new colors scheme for data points chartRef.current.data.datasets = gradients ? createAreaChartDataPoints(ctx) : createDataPoints(); // Update tooltip colors scheme setTooltipColorScheme({ chart: chartRef.current, siteVariables, chartDataPointColors, }); // Update axeses axesConfig({ chart: chartRef.current, ctx, colorScheme }); // Show style changes chartRef.current.update(); }, [theme]); function onLegendClick(datasetIndex: number) { if (!chartRef.current) return; chartRef.current.data.datasets![datasetIndex].hidden = !chartRef.current .data.datasets![datasetIndex].hidden; chartRef.current.update(); } return ( <ChartContainer siteVariables={siteVariables} data={data} chartDataPointColors={chartDataPointColors} onLegendClick={onLegendClick} > <canvas id={chartId} ref={canvasRef} tabIndex={0} style={{ userSelect: "none", }} aria-label={title} > {data.datasets.map((set, setKey) => (set.data as number[]).forEach((item: number, itemKey: number) => ( // Generated tooltips for screen readers <div key={itemKey} id={`${chartId}-tooltip-${setKey}-${itemKey}`}> <p>{item}</p> <span> {getText(t.locale, set.label)}: {set.data[itemKey]} </span> </div> )) )} </canvas> </ChartContainer> ); };
the_stack
import {UserPrefRepo} from '../UserPrefRepo'; import {GitHubSearchClient} from '../../Library/GitHub/GitHubSearchClient'; import {DateUtil} from '../../Library/Util/DateUtil'; import {StreamId, StreamRepo} from '../StreamRepo'; import {StreamEntity} from '../../Library/Type/StreamEntity'; import {DB} from '../../Library/Infra/DB'; import {color} from '../../Library/Style/color'; import {GitHubUserClient} from '../../Library/GitHub/GitHubUserClient'; import {GitHubUtil} from '../../Library/Util/GitHubUtil'; import {RemoteUserTeamEntity} from '../../Library/Type/RemoteGitHubV3/RemoteUserTeamEntity'; import {ArrayUtil} from '../../Library/Util/ArrayUtil'; import {RemoteIssueEntity} from '../../Library/Type/RemoteGitHubV3/RemoteIssueEntity'; import {GitHubV4IssueClient} from '../../Library/GitHub/V4/GitHubV4IssueClient'; class _StreamSetup { private creatingInitialStreams: boolean = false; private involvesIssues: RemoteIssueEntity[]; isCreatingInitialStreams(): boolean { return this.creatingInitialStreams; } async exec() { this.creatingInitialStreams = false; const already = await this.isAlready(); if (already) return; this.involvesIssues = await this.fetchInvolvesIssues(); // note: 並列には実行できない(streamのポジションがその時のレコードに依存するから) await this.createLibraryStreams(); await this.createSystemStreams(); await this.createMeStream(); await this.createTeamStream(); await this.createRepoStreams(); this.creatingInitialStreams = true; } private async isAlready(): Promise<boolean> { const {error, streams} = await StreamRepo.getAllStreams(['UserStream', 'FilterStream', 'ProjectStream']); if (error) return true; if (streams.length !== 0) return true; return false; } private async fetchInvolvesIssues(): Promise<RemoteIssueEntity[]> { const github = UserPrefRepo.getPref().github; const client = new GitHubSearchClient(github.accessToken, github.host, github.pathPrefix, github.https); const updatedAt = DateUtil.localToUTCString(new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)); // 30days ago const query = `involves:${UserPrefRepo.getUser().login} updated:>=${updatedAt}`; const {error, issues} = await client.search(query, 1, 100); if (error) { console.error(error); return []; } return issues; } private async createLibraryStreams() { const createdAt = DateUtil.localToUTCString(new Date()); const type: StreamEntity['type'] = 'LibraryStream'; const {error} = await DB.exec(` insert into streams (id, type, name, query_stream_id, queries, default_filter, user_filter, position, notification, icon, color, enabled, created_at, updated_at, searched_at) values (${StreamId.inbox}, "${type}", "Inbox", null, "", "is:unarchived", "", -1004, 0, "inbox-full", "${color.stream.blue}", 1, "${createdAt}", "${createdAt}", ""), (${StreamId.unread}, "${type}", "Unread", null, "", "is:unarchived is:unread", "", -1003, 0, "clipboard-outline", "${color.stream.blue}", 0, "${createdAt}", "${createdAt}", ""), (${StreamId.open}, "${type}", "Open", null, "", "is:unarchived is:open", "", -1002, 0, "book-open-variant", "${color.stream.blue}", 0, "${createdAt}", "${createdAt}", ""), (${StreamId.mark}, "${type}", "Bookmark", null, "", "is:unarchived is:bookmark", "", -1001, 0, "bookmark", "${color.stream.blue}", 1, "${createdAt}", "${createdAt}", ""), (${StreamId.archived}, "${type}", "Archived", null, "", "is:archived", "", -1000, 0, "archive", "${color.stream.blue}", 1, "${createdAt}", "${createdAt}", "") `); if (error) { console.error(error); return; } } private async createSystemStreams() { const createdAt = DateUtil.localToUTCString(new Date()); const type: StreamEntity['type'] = 'SystemStream'; const {error} = await DB.exec(` insert into streams (id, type, name, query_stream_id, queries, default_filter, user_filter, position, notification, icon, color, enabled, created_at, updated_at, searched_at) values (${StreamId.team}, "${type}", "Team", ${StreamId.team}, "", "is:unarchived", "", -102, 1, "account-multiple", "${color.brand}", 0, "${createdAt}", "${createdAt}", ""), (${StreamId.watching}, "${type}", "Watching", ${StreamId.watching}, "", "is:unarchived", "", -101, 1, "eye", "${color.brand}", 0, "${createdAt}", "${createdAt}", ""), (${StreamId.subscription}, "${type}", "Subscription", ${StreamId.subscription}, "", "is:unarchived", "", -100, 1, "volume-high", "${color.brand}", 0, "${createdAt}", "${createdAt}", "") `); if (error) { console.error(error); return; } } private async createMeStream() { // create stream const iconColor = color.brand; const queries = [`involves:${UserPrefRepo.getUser().login}`, `user:${UserPrefRepo.getUser().login}`]; const {error, stream} = await StreamRepo.createStream('UserStream', null, 'Me', queries, '', 1, iconColor); if (error) { console.error(error); return; } // create filter const login = UserPrefRepo.getUser().login; await StreamRepo.createStream('FilterStream', stream.id, 'My Issues', [], `is:issue author:${login}`, 1, iconColor); await StreamRepo.createStream('FilterStream', stream.id, 'My PRs', [], `is:pr author:${login}`, 1, iconColor); await StreamRepo.createStream('FilterStream', stream.id, 'Assign', [], `assignee:${login}`, 1, iconColor); } private async createTeamStream() { const teams = await this.getUsingTeams(); if (!teams.length) return; // create stream const iconColor = color.stream.navy; const query = teams.map(team => `team:${team.organization.login}/${team.slug}`).join(' '); const {error, stream} = await StreamRepo.createStream('UserStream', null, 'Team', [query], '', 1, iconColor); if (error) { console.error(error); return; } // create filter for (const team of teams) { await StreamRepo.createStream('FilterStream', stream.id, `@${team.organization.login}/${team.slug}`, [], `team:${team.organization.login}/${team.slug}`, 1, iconColor); } } // 使用しているteamを取得する // 1. 所属するチームを全て取得 // 2. 自分が関係したissueのorgのチームにだけ限定する(チームが多い場合、不要なチームをふるいにかけるため) // 3. チームとinvolves:meでissueを検索する // - チームが多い場合は最新のチームでも検索する // 4. teamメンションを取得できるようにv4 issueをマージする // 5. teamメンションされたissueが多い順にtop3のteamを返す private async getUsingTeams(): Promise<RemoteUserTeamEntity[]> { // fetch teams const github = UserPrefRepo.getPref().github; const userClient = new GitHubUserClient(github.accessToken, github.host, github.pathPrefix, github.https); const {error: e1, teams: allTeams} = await userClient.getUserTeams(1, 1); if (e1) { console.error(e1); return []; } if (!allTeams.length) return []; // 自分が関係したorgのみのteamに絞る // 理由: teamがたくさんある場合、最適なチームを選ぶ可能性をあげるため const orgs = this.involvesIssues.map(issue => { const {repoOrg} = GitHubUtil.getInfo(issue.url); return repoOrg; }); const teams = allTeams.filter(team => orgs.includes(team.organization.login)); if (!teams.length) return []; // search const involves = `involves:${UserPrefRepo.getUser().login}`; const updatedAt = `updated:>=${DateUtil.localToUTCString(new Date(Date.now() - 30 * 24 * 60 * 60 * 1000))}`; // 30days ago const maxLength = 256 - involves.length - 1 - updatedAt.length - 1; const teamWords = teams.map(t => `team:${t.organization.login}/${t.slug}`); const teamQueries = ArrayUtil.joinWithMax(teamWords, maxLength); const query = `${teamQueries[0]} ${involves} ${updatedAt}`; const searchClient = new GitHubSearchClient(github.accessToken, github.host, github.pathPrefix, github.https); const {error: e2, issues} = await searchClient.search(query, 1, 100); if (e2) { console.error(e2); return []; } // teams数が多い場合、最新の方でも検索する // 理由: 最古だけだと、古いissueしか取れない場合があるから if (teamQueries.length >= 2) { const rTeamWords = [...teamWords].reverse(); const teamQueries = ArrayUtil.joinWithMax(rTeamWords, maxLength); const query = `${teamQueries[0]} ${involves} ${updatedAt}`; const {error, issues: issues2} = await searchClient.search(query, 1, 100); if (error) { console.error(error); return []; } // 最新と最古で検索した場合、teamが重複する可能性があるので、issueも重複する可能性がある。 // なので、重複しないものだけ追加する issues2.forEach(issue2 => { if (!issues.find(issue => issue.id === issue2.id)) issues.push(issue2); }); } if (!issues.length) return []; // v4も取得して、teamメンションを取れるようにする { const v4Client = new GitHubV4IssueClient(github.accessToken, github.host, github.https, UserPrefRepo.getGHEVersion()); const nodeIds = issues.map(issue => issue.node_id); const {error, issues: v4Issues} = await v4Client.getIssuesByNodeIds(nodeIds); if (error) { console.error(error); return []; } GitHubV4IssueClient.injectV4ToV3(v4Issues, issues); } // count and sort const teamCounts: {team: RemoteUserTeamEntity, count: number}[] = []; for (const team of teams) { // todo: team.slugじゃなくてteam.nameが適切? const teamName = `${team.organization.login}/${team.slug}`; const count = issues.filter(issue => { return issue.mentions.find(mention => mention.login === teamName) }).length; teamCounts.push({team, count}); } teamCounts.sort((a, b) => b.count - a.count); return teamCounts.filter(teamCount => teamCount.count).slice(0, 3).map(v => v.team); } private async createRepoStreams() { // create stream const iconColor = color.stream.green; const repos = await this.getUsingRepos(); const query = repos.map(repo => `repo:${repo}`).join(' '); const {error, stream} = await StreamRepo.createStream('UserStream', null, 'Repo', [query], '', 1, iconColor); if (error) { console.error(error); return; } // create filter for (const repo of repos) { const shortName = repo.split('/')[1]; await StreamRepo.createStream('FilterStream', stream.id, `${shortName}`, [], `repo:${repo}`, 1, iconColor); } } private async getUsingRepos(): Promise<string[]> { const issues = [...this.involvesIssues]; if (!issues.length) return []; const repoCounts = {}; for (const issue of issues) { const paths = issue.url.split('/').reverse(); const repo = `${paths[3]}/${paths[2]}`; if (!repoCounts[repo]) repoCounts[repo] = 0; repoCounts[repo]++; } const items = Object.keys(repoCounts).map(repo => ({repo: repo, count: repoCounts[repo]})); items.sort((a, b) => b.count - a.count); return items.slice(0, 3).map(item => item.repo); } } export const StreamSetup = new _StreamSetup();
the_stack
import { assert, ContractDefinition, ContractKind, FunctionDefinition, resolve, resolveAny, SourceUnit, Statement, StatementWithChildren, StructuredDocumentation, TryCatchClause, VariableDeclaration } from "solc-typed-ast"; import { MacroDefinition, parseMacroMethodSignature } from "../macros"; import { AnnotationType, SAnnotation, SId, SMacro, SNode, SProperty, SUserFunctionDefinition } from "../spec-lang/ast"; import { parseAnnotation, SyntaxError as ExprPEGSSyntaxError } from "../spec-lang/expr_parser"; import { PPAbleError } from "../util/errors"; import { makeRange, Range, rangeToLocRange } from "../util/location"; import { getOr, getScopeUnit, zip } from "../util/misc"; import { SourceFile, SourceMap } from "../util/sources"; const srcloc = require("src-location"); export type AnnotationFilterOptions = { type?: string; message?: string; }; export type AnnotationExtractionContext = { filterOptions: AnnotationFilterOptions; compilerVersion: string; macros: Map<string, MacroDefinition>; }; export type AnnotationTarget = | ContractDefinition | FunctionDefinition | VariableDeclaration | Statement | StatementWithChildren<any>; let numAnnotations = 0; /** * Base class containing metadata for parsed anntotations useful for * pretty-printing error messages and error line information. */ export class AnnotationMetaData<T extends SAnnotation = SAnnotation> { /// StructuredDocumentation AST node containing the annotation readonly raw: StructuredDocumentation; /// Target ast node being annotated. Either FunctionDefintion or ContractDefinition readonly target: AnnotationTarget; /// Name of target node. We need this to remember the original name, as interposing /// destructively changes names readonly targetName: string; /// Parsed annotation readonly parsedAnnot: T; /// User-label ("" if not provided) get message(): string { return this.parsedAnnot.label ? this.parsedAnnot.label : ""; } /// Type of the annotation get type(): AnnotationType { return this.parsedAnnot.type; } /// Original annotation text readonly original: string; /// UID of this annotation readonly id: number; /// In flat mode we destructively modify SourceUnits and move definitions to a new unit. /// Remember the original source file name for the annotation for use in json_output readonly originalSourceFile: SourceFile; constructor( raw: StructuredDocumentation, target: AnnotationTarget, parsedAnnot: T, source: SourceFile ) { this.raw = raw; this.target = target; // This is a hack. Remember the target name as interposing overwrites it this.targetName = target instanceof Statement || target instanceof StatementWithChildren ? "" : target.name; this.original = parsedAnnot.getSourceFragment(source.contents); this.id = numAnnotations++; this.parsedAnnot = parsedAnnot; /// Location of the annotation relative to the start of the file this.originalSourceFile = source; } get originalFileName(): string { return this.originalSourceFile.fileName; } get annotationFileRange(): Range { return this.parsedAnnot.requiredRange; } } export type AnnotationMap = Map<AnnotationTarget, AnnotationMetaData[]>; /** * Metadata specific to a user function definition. */ export class UserFunctionDefinitionMetaData extends AnnotationMetaData<SUserFunctionDefinition> {} /** * Metadata specific to a property annotation (invariant, if_succeeds) */ export class PropertyMetaData extends AnnotationMetaData<SProperty> {} export class MacroMetaData extends AnnotationMetaData<SMacro> { readonly macroDefinition: MacroDefinition; get definitionFile(): SourceFile { return this.macroDefinition.source; } constructor( raw: StructuredDocumentation, target: AnnotationTarget, parsedAnnot: SMacro, source: SourceFile, macroDefinition: MacroDefinition ) { super(raw, target, parsedAnnot, source); this.macroDefinition = macroDefinition; } /** * Computes a mapping where "keys" are formal variable names from macro definition * and "values" are actual names from macro annotation on contract. */ getAliasingMap(): Map<string, string> { const formal = Array.from(this.macroDefinition.variables.keys()); const actual = this.parsedAnnot.parameters.map((node) => node.name); const pairs = zip( formal, actual, "Macro annotation arguments count {0} mismatches macro definition variables count {1}", actual.length, formal.length ); return new Map(pairs); } } export class AnnotationError extends PPAbleError { readonly annotation: string; readonly target: AnnotationTarget; constructor(msg: string, annotation: string, range: Range, target: AnnotationTarget) { super(msg, range); this.annotation = annotation; this.target = target; } } export class SyntaxError extends AnnotationError {} export class UnsupportedByTargetError extends AnnotationError {} type RawMetaData = { target: AnnotationTarget; node: StructuredDocumentation; text: string; docFileOffset: number; }; function makeAnnotationFromMatch( match: RegExpExecArray, meta: RawMetaData, source: SourceFile, ctx: AnnotationExtractionContext ): AnnotationMetaData { let matchIdx = match.index; while (meta.text[matchIdx].match(/[\n\r]/)) matchIdx++; const slice = meta.text.slice(matchIdx); let annotation: SAnnotation; try { annotation = parseAnnotation( slice, meta.target, ctx.compilerVersion, source, meta.docFileOffset + matchIdx ); } catch (e) { if (e instanceof ExprPEGSSyntaxError) { // Compute the syntax error offset relative to the start of the file const errStartOff = e.location.start.offset + meta.docFileOffset + matchIdx; const errLength = e.location.end.offset - e.location.start.offset; const errRange = rangeToLocRange(errStartOff, errLength, source); const original = meta.text.slice(matchIdx, matchIdx + errStartOff + errLength + 10); throw new SyntaxError(e.message, original, errRange, meta.target); } throw e; } if (annotation instanceof SProperty) { return new PropertyMetaData(meta.node, meta.target, annotation, source); } if (annotation instanceof SUserFunctionDefinition) { return new UserFunctionDefinitionMetaData(meta.node, meta.target, annotation, source); } if (annotation instanceof SMacro) { const macroDef = ctx.macros.get(annotation.name.pp()); if (macroDef) { return new MacroMetaData(meta.node, meta.target, annotation, source, macroDef); } else { throw new Error(`Unknown macro ${annotation.name.pp()}`); } } throw new Error(`Unknown annotation ${annotation.pp()}`); } /** * Checks the validity of an annotation * @param annotation The annotation to be validated * @param target Target block(contract/function) of the annotation */ function validateAnnotation(target: AnnotationTarget, annotation: AnnotationMetaData) { if (target instanceof ContractDefinition) { const contractApplicableTypes = [ AnnotationType.Invariant, AnnotationType.Define, AnnotationType.IfSucceeds, AnnotationType.Try, AnnotationType.Require, AnnotationType.Macro ]; if (!contractApplicableTypes.includes(annotation.type)) { throw new UnsupportedByTargetError( `The "${annotation.type}" annotation is not applicable to contracts`, annotation.original, annotation.annotationFileRange, target ); } // @todo (dimo) add support for user functions on interfaces/libraries and add tests with that if (target.kind === ContractKind.Interface || target.kind === ContractKind.Library) { throw new UnsupportedByTargetError( `Unsupported contract annotations on ${target.kind} ${target.name}`, annotation.original, annotation.annotationFileRange, target ); } } else if (target instanceof FunctionDefinition) { if ( annotation.type !== AnnotationType.IfSucceeds && annotation.type !== AnnotationType.Try && annotation.type !== AnnotationType.Require ) { throw new UnsupportedByTargetError( `The "${annotation.type}" annotation is not applicable to functions`, annotation.original, annotation.annotationFileRange, target ); } if (target.vScope instanceof SourceUnit) { throw new UnsupportedByTargetError( `Instrumenting free functions is not supported`, annotation.original, annotation.annotationFileRange, target ); } } else if (target instanceof Statement || target instanceof StatementWithChildren) { if ( annotation.type !== AnnotationType.Assert && annotation.type !== AnnotationType.Try && annotation.type !== AnnotationType.Require ) { throw new UnsupportedByTargetError( `The "${annotation.type}" annotation is not applicable inside functions`, annotation.original, annotation.annotationFileRange, target ); } if (target instanceof TryCatchClause) { throw new UnsupportedByTargetError( `The "${annotation.type}" annotation is not applicable to try-catch clauses`, annotation.original, annotation.annotationFileRange, target ); } } else { if ( annotation.type !== AnnotationType.IfUpdated && annotation.type !== AnnotationType.IfAssigned ) { throw new UnsupportedByTargetError( `The "${annotation.type}" annotation is not applicable to state variables`, annotation.original, annotation.annotationFileRange, target ); } if (!(target.vScope instanceof ContractDefinition)) { throw new UnsupportedByTargetError( `The "${annotation.type}" annotation is only applicable to state variables`, annotation.original, annotation.annotationFileRange, target ); } } } function findAnnotations( raw: StructuredDocumentation, target: AnnotationTarget, source: SourceFile, ctx: AnnotationExtractionContext ): AnnotationMetaData[] { const rxType = ctx.filterOptions.type === undefined ? undefined : new RegExp(ctx.filterOptions.type); const rxMsg = ctx.filterOptions.message === undefined ? undefined : new RegExp(ctx.filterOptions.message); const sourceInfo = raw.sourceInfo; const meta: RawMetaData = { target: target, node: raw, text: raw.extractSourceFragment(source.contents), docFileOffset: sourceInfo.offset }; const result: AnnotationMetaData[] = []; const rx = /\s*(\*|\/\/\/)\s*(@custom:scribble)?\s*#(if_succeeds|if_updated|if_assigned|invariant|assert|try|require|macro|define)/g; let match = rx.exec(meta.text); while (match !== null) { const annotation = makeAnnotationFromMatch(match, meta, source, ctx); if ( (rxType === undefined || rxType.test(annotation.type)) && (rxMsg === undefined || rxMsg.test(annotation.message)) ) { validateAnnotation(target, annotation); result.push(annotation); } rx.lastIndex = match.index + annotation.original.length; match = rx.exec(meta.text); } return result; } export function extractAnnotations( target: AnnotationTarget, sources: SourceMap, ctx: AnnotationExtractionContext ): AnnotationMetaData[] { const result: AnnotationMetaData[] = []; if (target.documentation === undefined) { return result; } const raw = target.documentation; if (!(raw instanceof StructuredDocumentation)) { throw new Error(`Expected structured documentation not string`); } const unit = getScopeUnit(target); const source = sources.get(unit.absolutePath) as SourceFile; const annotations = findAnnotations(raw, target, source, ctx); result.push(...annotations); return result; } /** * Gather annotations from `fun` and all functions up the inheritance tree * that `fun` overrides. */ export function gatherFunctionAnnotations( fun: FunctionDefinition, annotationMap: AnnotationMap ): AnnotationMetaData[] { // Free functions can not be overriden and shouldn't have annotations. if (!(fun.vScope instanceof ContractDefinition)) { return []; } let overridee: FunctionDefinition | undefined = fun; let scope = overridee.vScope as ContractDefinition; // We may have functions missing in annotationMap as map interposing adds new functions const result: AnnotationMetaData[] = getOr(annotationMap, fun, []); while ((overridee = resolve(scope, overridee, true)) !== undefined) { result.unshift(...(annotationMap.get(overridee) as AnnotationMetaData[])); scope = overridee.vScope as ContractDefinition; } return result; } /** * Gather annotations from `contract` and all it's parent contracts */ export function gatherContractAnnotations( contract: ContractDefinition, annotationMap: AnnotationMap ): AnnotationMetaData[] { const result: AnnotationMetaData[] = []; for (const base of contract.vLinearizedBaseContracts) { result.unshift(...(annotationMap.get(base) as AnnotationMetaData[])); } return result; } export class MacroError extends AnnotationError {} /** * Detects macro annotations, produces annotations that are defined by macro * and injects them target nodes. Macro annotations are removed afterwards. */ function processMacroAnnotations( annotationMap: AnnotationMap, ctx: AnnotationExtractionContext ): void { const injections: AnnotationMap = new Map(); for (const [scope, metas] of annotationMap) { for (let m = 0; m < metas.length; m++) { const meta = metas[m]; if (!(meta instanceof MacroMetaData)) { continue; } const globalAliases = meta.getAliasingMap(); for (const [signature, properties] of meta.macroDefinition.properties) { let name: string; let args: string[]; if (signature.includes("(")) { /** * Signature with method */ [name, args] = parseMacroMethodSignature(signature); } else { /** * Signature with variable */ name = getOr(globalAliases, signature, signature); args = []; } const localAliases = new Map(globalAliases); const targets = [...resolveAny(name, scope, ctx.compilerVersion, true)]; if (targets.length !== 1) { throw new MacroError( `No target ${name} found in contract ${ (scope as ContractDefinition).name } for ${meta.original}`, meta.original, meta.parsedAnnot.src as Range, meta.target ); } const target = targets[0]; if (target instanceof FunctionDefinition && args.length > 0) { const params = target.vParameters.vParameters; const pairs = zip( args, params, `{0}: arguments count {1} in macro definition mismatches method arguments count {2}`, signature, args.length, params.length ); for (const [formalParam, actualParam] of pairs) { if (formalParam !== "") { /** * Note that it is allowed for global aliases to be SHADOWED by local aliases. * Other solution would require to throw an error in case of name clashing, i.e.: * * ``` * assert( * !localAliases.has(formalParam), * "{0}: shadowing of globally defined alias {1}", * signature, * formalParam * ); * ``` */ localAliases.set(formalParam, actualParam.name); } } } for (const { expression, message, offset } of properties) { let annotation: SAnnotation; try { annotation = parseAnnotation( expression, target, ctx.compilerVersion, meta.definitionFile, offset ); } catch (e) { if (e instanceof ExprPEGSSyntaxError) { const { line, column } = srcloc.indexToLocation( meta.definitionFile.contents, offset ); throw new SyntaxError( e.message, expression, /// TODO: Remove or fix makeRange(e.location, { file: meta.definitionFile, baseOff: offset, baseLine: line - 1, baseCol: column }), target ); } throw e; } assert( annotation instanceof SProperty, "Only properties are allowed to be defined in macros. Unsupported annotation: {0}", expression ); /** * Callback to * * 1) Rename all ids in the macro definition with their * corresponding values in the instantiation context. * Renaming can be due to variable arguments for the macro, * or differing function parameter names * * 2) Update the location of each node to reflect both the * original macro location as well as the macro * instantiation location */ const walker = (node: SNode) => { if (node instanceof SId) { const actualName = localAliases.get(node.name); if (actualName !== undefined) { node.name = actualName; } } node.src = [node.src as Range, meta.parsedAnnot.src as Range]; }; /** * Replace macro aliases with supplied variable names in macro annotation */ annotation.walk(walker); /** * Use property message in macro definition as a label for injected annotation */ annotation.label = message; const dummyDoc = new StructuredDocumentation( 0, "0:0:0", "StructuredDocumentation", "#" + annotation.pp() ); const metaToInject = new PropertyMetaData( dummyDoc, target, annotation, meta.originalSourceFile ); validateAnnotation(target, metaToInject); const metasToInject = injections.get(target); if (metasToInject === undefined) { injections.set(target, [metaToInject]); } else { metasToInject.push(metaToInject); } } } /** * Remove macro annotation as it will not pass type-checking. * It is now represented by other annotations in `injections`, * so there is no further use for macro annotation itself. */ metas.splice(m, 1); } } /** * Merge injected annotations with original annotations. */ for (const [target, metasToInject] of injections) { const metas = annotationMap.get(target); if (metas === undefined) { annotationMap.set(target, metasToInject); } else { metas.push(...metasToInject); } } } /** * Find all annotations in the list of `SourceUnit`s `units` and combine them in a * map from ASTNode to its annotations. Return the resulting map. * * @param units - List of `SourceUnit`s. * @param sources - Mapping from file names to their contents. Used during annotation extraction. * @param ctx - Annotation context to consider while processing annotations. */ export function buildAnnotationMap( units: SourceUnit[], sources: SourceMap, ctx: AnnotationExtractionContext ): AnnotationMap { const res: AnnotationMap = new Map(); for (const unit of units) { // Check no annotations on free functions for (const freeFun of unit.vFunctions) { const annots = extractAnnotations(freeFun, sources, ctx); if (annots.length !== 0) { throw new UnsupportedByTargetError( `The "${annots[0].type}" annotation is not applicable to free functions`, annots[0].original, annots[0].annotationFileRange, freeFun ); } } // Check no annotations on file-level constants. for (const fileLevelConst of unit.vVariables) { const annots = extractAnnotations(fileLevelConst, sources, ctx); if (annots.length !== 0) { throw new UnsupportedByTargetError( `The "${annots[0].type}" annotation is not applicable to file-level constants`, annots[0].original, annots[0].annotationFileRange, fileLevelConst ); } } for (const contract of unit.vContracts) { res.set(contract, extractAnnotations(contract, sources, ctx)); for (const stateVar of contract.vStateVariables) { res.set(stateVar, extractAnnotations(stateVar, sources, ctx)); } for (const method of contract.vFunctions) { res.set(method, extractAnnotations(method, sources, ctx)); } } // Finally check for any assertions for (const stmt of unit.getChildrenBySelector( (nd) => nd instanceof Statement || nd instanceof StatementWithChildren )) { res.set( stmt as Statement | StatementWithChildren<any>, extractAnnotations(stmt, sources, ctx) ); } } processMacroAnnotations(res, ctx); return res; }
the_stack
import * as d3 from "d3"; import * as Typesettable from "typesettable"; import * as Animators from "../animators"; import { Dataset } from "../core/dataset"; import * as Formatters from "../core/formatters"; import { DatumFormatter } from "../core/formatters"; import { AttributeToProjector, IAccessor, Point, SimpleSelection } from "../core/interfaces"; import * as Scales from "../scales"; import { Scale } from "../scales/scale"; import * as Utils from "../utils"; import { ArcSVGDrawer } from "../drawers/arcDrawer"; import { ArcOutlineSVGDrawer } from "../drawers/arcOutlineDrawer"; import { ProxyDrawer } from "../drawers/drawer"; import { warn } from "../utils/windowUtils"; import { IAccessorScaleBinding, IPlotEntity } from "./"; import { Plot } from "./plot"; export interface IPiePlotEntity extends IPlotEntity { strokeSelection: SimpleSelection<any>; } export class Pie extends Plot { private static _INNER_RADIUS_KEY = "inner-radius"; private static _OUTER_RADIUS_KEY = "outer-radius"; private static _SECTOR_VALUE_KEY = "sector-value"; private _startAngle: number = 0; private _endAngle: number = 2 * Math.PI; private _startAngles: number[]; private _endAngles: number[]; private _labelFormatter: DatumFormatter = Formatters.identity(); private _labelsEnabled = false; private _strokeDrawers: Utils.Map<Dataset, ArcOutlineSVGDrawer>; /** * @constructor */ constructor() { super(); this.innerRadius(0); this.outerRadius(() => { const pieCenter = this._pieCenter(); return Math.min(Math.max(this.width() - pieCenter.x, pieCenter.x), Math.max(this.height() - pieCenter.y, pieCenter.y)); }); this.addClass("pie-plot"); this.attr("fill", (d, i) => String(i), new Scales.Color()); this._strokeDrawers = new Utils.Map<Dataset, ArcOutlineSVGDrawer>(); } protected _setup() { super._setup(); this._strokeDrawers.forEach((d) => d.attachTo(this._renderArea)); } public computeLayout(origin?: Point, availableWidth?: number, availableHeight?: number) { super.computeLayout(origin, availableWidth, availableHeight); const pieCenter = this._pieCenter(); this._renderArea.attr("transform", "translate(" + pieCenter.x + "," + pieCenter.y + ")"); const radiusLimit = Math.min(Math.max(this.width() - pieCenter.x, pieCenter.x), Math.max(this.height() - pieCenter.y, pieCenter.y)); if (this.innerRadius().scale != null) { this.innerRadius().scale.range([0, radiusLimit]); } if (this.outerRadius().scale != null) { this.outerRadius().scale.range([0, radiusLimit]); } return this; } public addDataset(dataset: Dataset) { super.addDataset(dataset); return this; } protected _addDataset(dataset: Dataset) { if (this.datasets().length === 1) { Utils.Window.warn("Only one dataset is supported in Pie plots"); return this; } this._updatePieAngles(); super._addDataset(dataset); const strokeDrawer = new ArcOutlineSVGDrawer(); if (this._isSetup) { strokeDrawer.attachTo(this._renderArea); } this._strokeDrawers.set(dataset, strokeDrawer); return this; } public removeDataset(dataset: Dataset) { super.removeDataset(dataset); return this; } protected _removeDatasetNodes(dataset: Dataset) { super._removeDatasetNodes(dataset); this._strokeDrawers.get(dataset).remove(); } protected _removeDataset(dataset: Dataset) { super._removeDataset(dataset); this._strokeDrawers.delete(dataset); this._startAngles = []; this._endAngles = []; return this; } public selections(datasets = this.datasets()): SimpleSelection<any> { const allSelections = super.selections(datasets).nodes(); datasets.forEach((dataset) => { const drawer = this._strokeDrawers.get(dataset); if (drawer == null) { return; } allSelections.push(...drawer.getVisualPrimitives()); }); return d3.selectAll(allSelections); } protected _onDatasetUpdate() { super._onDatasetUpdate(); this._updatePieAngles(); this.render(); } protected _createDrawer() { return new ProxyDrawer( () => new ArcSVGDrawer(), () => { warn("canvas renderer is not supported on Pie Plot!"); return null; }); } public entities(datasets = this.datasets()): IPiePlotEntity[] { const entities = super.entities(datasets); return entities.map((entity) => { entity.position.x += this.width() / 2; entity.position.y += this.height() / 2; const stroke = d3.select(this._strokeDrawers.get(entity.dataset).getVisualPrimitiveAtIndex(entity.index)); const piePlotEntity = entity as IPiePlotEntity; piePlotEntity.strokeSelection = stroke; return piePlotEntity; }); } /** * Gets the AccessorScaleBinding for the sector value. */ public sectorValue<S>(): IAccessorScaleBinding<S, number>; /** * Sets the sector value to a constant number or the result of an Accessor<number>. * * @param {number|Accessor<number>} sectorValue * @returns {Pie} The calling Pie Plot. */ public sectorValue(sectorValue: number | IAccessor<number>): this; /** * Sets the sector value to a scaled constant value or scaled result of an Accessor. * The provided Scale will account for the values when autoDomain()-ing. * * @param {S|Accessor<S>} sectorValue * @param {Scale<S, number>} scale * @returns {Pie} The calling Pie Plot. */ public sectorValue<S>(sectorValue: S | IAccessor<S>, scale: Scale<S, number>): this; public sectorValue<S>(sectorValue?: number | IAccessor<number> | S | IAccessor<S>, scale?: Scale<S, number>): any { if (sectorValue == null) { return this._propertyBindings.get(Pie._SECTOR_VALUE_KEY); } this._bindProperty(Pie._SECTOR_VALUE_KEY, sectorValue, scale); this._updatePieAngles(); this.render(); return this; } /** * Gets the AccessorScaleBinding for the inner radius. */ public innerRadius<R>(): IAccessorScaleBinding<R, number>; /** * Sets the inner radius to a constant number or the result of an Accessor<number>. * * @param {number|Accessor<number>} innerRadius * @returns {Pie} The calling Pie Plot. */ public innerRadius(innerRadius: number | IAccessor<number>): any; /** * Sets the inner radius to a scaled constant value or scaled result of an Accessor. * The provided Scale will account for the values when autoDomain()-ing. * * @param {R|Accessor<R>} innerRadius * @param {Scale<R, number>} scale * @returns {Pie} The calling Pie Plot. */ public innerRadius<R>(innerRadius: R | IAccessor<R>, scale: Scale<R, number>): any; public innerRadius<R>(innerRadius?: number | IAccessor<number> | R | IAccessor<R>, scale?: Scale<R, number>): any { if (innerRadius == null) { return this._propertyBindings.get(Pie._INNER_RADIUS_KEY); } this._bindProperty(Pie._INNER_RADIUS_KEY, innerRadius, scale); this.render(); return this; } /** * Gets the AccessorScaleBinding for the outer radius. */ public outerRadius<R>(): IAccessorScaleBinding<R, number>; /** * Sets the outer radius to a constant number or the result of an Accessor<number>. * * @param {number|Accessor<number>} outerRadius * @returns {Pie} The calling Pie Plot. */ public outerRadius(outerRadius: number | IAccessor<number>): this; /** * Sets the outer radius to a scaled constant value or scaled result of an Accessor. * The provided Scale will account for the values when autoDomain()-ing. * * @param {R|Accessor<R>} outerRadius * @param {Scale<R, number>} scale * @returns {Pie} The calling Pie Plot. */ public outerRadius<R>(outerRadius: R | IAccessor<R>, scale: Scale<R, number>): this; public outerRadius<R>(outerRadius?: number | IAccessor<number> | R | IAccessor<R>, scale?: Scale<R, number>): any { if (outerRadius == null) { return this._propertyBindings.get(Pie._OUTER_RADIUS_KEY); } this._bindProperty(Pie._OUTER_RADIUS_KEY, outerRadius, scale); this.render(); return this; } /** * Gets the start angle of the Pie Plot * * @returns {number} Returns the start angle */ public startAngle(): number; /** * Sets the start angle of the Pie Plot. * * @param {number} startAngle * @returns {Pie} The calling Pie Plot. */ public startAngle(angle: number): this; public startAngle(angle?: number): any { if (angle == null) { return this._startAngle; } else { this._startAngle = angle; this._updatePieAngles(); this.render(); return this; } } /** * Gets the end angle of the Pie Plot. * * @returns {number} Returns the end angle */ public endAngle(): number; /** * Sets the end angle of the Pie Plot. * * @param {number} endAngle * @returns {Pie} The calling Pie Plot. */ public endAngle(angle: number): this; public endAngle(angle?: number): any { if (angle == null) { return this._endAngle; } else { this._endAngle = angle; this._updatePieAngles(); this.render(); return this; } } /** * Get whether slice labels are enabled. * * @returns {boolean} Whether slices should display labels or not. */ public labelsEnabled(): boolean; /** * Sets whether labels are enabled. * * @param {boolean} labelsEnabled * @returns {Pie} The calling Pie Plot. */ public labelsEnabled(enabled: boolean): this; public labelsEnabled(enabled?: boolean): any { if (enabled == null) { return this._labelsEnabled; } else { this._labelsEnabled = enabled; this.render(); return this; } } /** * Gets the Formatter for the labels. */ public labelFormatter(): DatumFormatter; /** * Sets the Formatter for the labels. The labelFormatter will be fed each pie * slice's value as computed by the `.sectorValue()` accessor, as well as the * datum, datum index, and dataset associated with that bar. * * @param {Formatter} formatter * @returns {Pie} The calling Pie Plot. */ public labelFormatter(formatter: DatumFormatter): this; public labelFormatter(formatter?: DatumFormatter): any { if (formatter == null) { return this._labelFormatter; } else { this._labelFormatter = formatter; this.render(); return this; } } /* * Gets the Entities at a particular Point. * * @param {Point} p * @param {PlotEntity[]} */ public entitiesAt(queryPoint: Point) { const center = { x: this.width() / 2, y: this.height() / 2 }; const adjustedQueryPoint = { x: queryPoint.x - center.x, y: queryPoint.y - center.y }; const index = this._sliceIndexForPoint(adjustedQueryPoint); return index == null ? [] : [this.entities()[index]]; } protected _propertyProjectors(): AttributeToProjector { const attrToProjector = super._propertyProjectors(); const innerRadiusAccessor = Plot._scaledAccessor(this.innerRadius()); const outerRadiusAccessor = Plot._scaledAccessor(this.outerRadius()); attrToProjector["d"] = (datum: any, index: number, ds: Dataset) => { return d3.arc().innerRadius(innerRadiusAccessor(datum, index, ds)) .outerRadius(outerRadiusAccessor(datum, index, ds)) .startAngle(this._startAngles[index]) .endAngle(this._endAngles[index])(datum, index); }; return attrToProjector; } private _updatePieAngles() { if (this.sectorValue() == null) { return; } if (this.datasets().length === 0) { return; } const sectorValueAccessor = Plot._scaledAccessor(this.sectorValue()); const dataset = this.datasets()[0]; const data = this._getDataToDraw().get(dataset); const pie = d3.pie().sort(null).startAngle(this._startAngle).endAngle(this._endAngle) .value((d, i) => sectorValueAccessor(d, i, dataset))(data); this._startAngles = pie.map((slice) => slice.startAngle); this._endAngles = pie.map((slice) => slice.endAngle); } private _pieCenter(): Point { const a = this._startAngle < this._endAngle ? this._startAngle : this._endAngle; const b = this._startAngle < this._endAngle ? this._endAngle : this._startAngle; const sinA = Math.sin(a); const cosA = Math.cos(a); const sinB = Math.sin(b); const cosB = Math.cos(b); let hTop: number; let hBottom: number; let wRight: number; let wLeft: number; /** * The center of the pie is computed using the sine and cosine of the start angle and the end angle * The sine indicates whether the start and end fall on the right half or the left half of the pie * The cosine indicates whether the start and end fall on the top or the bottom half of the pie * Different combinations provide the different heights and widths the pie needs from the center to the sides */ if (sinA >= 0 && sinB >= 0) { if (cosA >= 0 && cosB >= 0) { hTop = cosA; hBottom = 0; wLeft = 0; wRight = sinB; } else if (cosA < 0 && cosB < 0) { hTop = 0; hBottom = -cosB; wLeft = 0; wRight = sinA; } else if (cosA >= 0 && cosB < 0) { hTop = cosA; hBottom = -cosB; wLeft = 0; wRight = sinA; } else if (cosA < 0 && cosB >= 0) { hTop = 1; hBottom = 1; wLeft = 1; wRight = Math.max(sinA, sinB); } } else if (sinA >= 0 && sinB < 0) { if (cosA >= 0 && cosB >= 0) { hTop = Math.max(cosA, cosB); hBottom = 1; wLeft = 1; wRight = 1; } else if (cosA < 0 && cosB < 0) { hTop = 0; hBottom = 1; wLeft = -sinB; wRight = sinA; } else if (cosA >= 0 && cosB < 0) { hTop = cosA; hBottom = 1; wLeft = -sinB; wRight = 1; } else if (cosA < 0 && cosB >= 0) { hTop = cosB; hBottom = 1; wLeft = 1; wRight = sinA; } } else if (sinA < 0 && sinB >= 0) { if (cosA >= 0 && cosB >= 0) { hTop = 1; hBottom = 0; wLeft = -sinA; wRight = sinB; } else if (cosA < 0 && cosB < 0) { hTop = 1; hBottom = Math.max(-cosA, -cosB); wLeft = 1; wRight = 1; } else if (cosA >= 0 && cosB < 0) { hTop = 1; hBottom = -cosB; wLeft = -sinA; wRight = 1; } else if (cosA < 0 && cosB >= 0) { hTop = 1; hBottom = -cosA; wLeft = 1; wRight = sinB; } } else if (sinA < 0 && sinB < 0) { if (cosA >= 0 && cosB >= 0) { hTop = cosB; hBottom = 0; wLeft = -sinA; wRight = 0; } else if (cosA < 0 && cosB < 0) { hTop = 0; hBottom = -cosA; wLeft = -sinB; wRight = 0; } else if (cosA >= 0 && cosB < 0) { hTop = 1; hBottom = 1; wLeft = Math.max(cosA, -cosB); wRight = 1; } else if (cosA < 0 && cosB >= 0) { hTop = cosB; hBottom = -cosA; wLeft = 1; wRight = 0; } } return { x: wLeft + wRight == 0 ? 0 : (wLeft / (wLeft + wRight)) * this.width(), y: hTop + hBottom == 0 ? 0 : (hTop / (hTop + hBottom)) * this.height(), }; } protected _getDataToDraw(): Utils.Map<Dataset, any[]> { const dataToDraw = super._getDataToDraw(); if (this.datasets().length === 0) { return dataToDraw; } const sectorValueAccessor = Plot._scaledAccessor(this.sectorValue()); const ds = this.datasets()[0]; const data = dataToDraw.get(ds); const filteredData = data.filter((d, i) => Pie._isValidData(sectorValueAccessor(d, i, ds))); dataToDraw.set(ds, filteredData); return dataToDraw; } protected static _isValidData(value: any) { return Utils.Math.isValidNumber(value) && value >= 0; } protected _pixelPoint(datum: any, index: number, dataset: Dataset) { const scaledValueAccessor = Plot._scaledAccessor(this.sectorValue()); if (!Pie._isValidData(scaledValueAccessor(datum, index, dataset))) { return { x: NaN, y: NaN }; } const innerRadius = Plot._scaledAccessor(this.innerRadius())(datum, index, dataset); const outerRadius = Plot._scaledAccessor(this.outerRadius())(datum, index, dataset); const avgRadius = (innerRadius + outerRadius) / 2; const pie = d3.pie() .sort(null) .value((d: any, i: number) => { const value = scaledValueAccessor(d, i, dataset); return Pie._isValidData(value) ? value : 0; }).startAngle(this._startAngle).endAngle(this._endAngle)(dataset.data()); const startAngle = pie[index].startAngle; const endAngle = pie[index].endAngle; const avgAngle = (startAngle + endAngle) / 2; return { x: avgRadius * Math.sin(avgAngle), y: -avgRadius * Math.cos(avgAngle) }; } protected _additionalPaint(time: number) { this._renderArea.select(".label-area").remove(); if (this._labelsEnabled) { Utils.Window.setTimeout(() => this._drawLabels(), time); } const drawSteps = this._generateStrokeDrawSteps(); const dataToDraw = this._getDataToDraw(); this.datasets().forEach((dataset) => { const appliedDrawSteps = Plot.applyDrawSteps(drawSteps, dataset); this._strokeDrawers.get(dataset).draw(dataToDraw.get(dataset), appliedDrawSteps); }); } private _generateStrokeDrawSteps() { const attrToProjector = this._getAttrToProjector(); return [{ attrToProjector: attrToProjector, animator: new Animators.Null() }]; } private _sliceIndexForPoint(p: Point) { const pointRadius = Math.sqrt(Math.pow(p.x, 2) + Math.pow(p.y, 2)); let pointAngle = Math.acos(-p.y / pointRadius); if (p.x < 0) { pointAngle = Math.PI * 2 - pointAngle; } let index: number; for (let i = 0; i < this._startAngles.length; i++) { if (this._startAngles[i] < pointAngle && this._endAngles[i] > pointAngle) { index = i; break; } } if (index !== undefined) { const dataset = this.datasets()[0]; const datum = dataset.data()[index]; const innerRadius = this.innerRadius().accessor(datum, index, dataset); const outerRadius = this.outerRadius().accessor(datum, index, dataset); if (pointRadius > innerRadius && pointRadius < outerRadius) { return index; } } return null; } private _drawLabels() { const attrToProjector = this._getAttrToProjector(); const labelArea = this._renderArea.append("g").classed("label-area", true); const context = new Typesettable.SvgContext(labelArea.node() as SVGElement); const measurer = new Typesettable.CacheMeasurer(context); const writer = new Typesettable.Writer(measurer, context); const dataset = this.datasets()[0]; const data = this._getDataToDraw().get(dataset); const dataLen = data.length; for (let datumIndex = 0; datumIndex < dataLen; datumIndex++) { const datum = data[datumIndex]; let value = this.sectorValue().accessor(datum, datumIndex, dataset); if (!Utils.Math.isValidNumber(value)) { continue; } value = this._labelFormatter(value, datum, datumIndex, dataset); const measurement = measurer.measure(value); const theta = (this._endAngles[datumIndex] + this._startAngles[datumIndex]) / 2; let outerRadius = this.outerRadius().accessor(datum, datumIndex, dataset); if (this.outerRadius().scale) { outerRadius = this.outerRadius().scale.scale(outerRadius); } let innerRadius = this.innerRadius().accessor(datum, datumIndex, dataset); if (this.innerRadius().scale) { innerRadius = this.innerRadius().scale.scale(innerRadius); } const labelRadius = (outerRadius + innerRadius) / 2; const x = Math.sin(theta) * labelRadius - measurement.width / 2; const y = -Math.cos(theta) * labelRadius - measurement.height / 2; const corners = [ { x: x, y: y }, { x: x, y: y + measurement.height }, { x: x + measurement.width, y: y }, { x: x + measurement.width, y: y + measurement.height }, ]; let showLabel = corners.every((corner) => { return Math.abs(corner.x) <= this.width() / 2 && Math.abs(corner.y) <= this.height() / 2; }); if (showLabel) { const sliceIndices = corners.map((corner) => this._sliceIndexForPoint(corner)); showLabel = sliceIndices.every((index) => index === datumIndex); } const color = attrToProjector["fill"](datum, datumIndex, dataset); const dark = Utils.Color.contrast("white", color) * 1.6 < Utils.Color.contrast("black", color); const g = labelArea.append("g").attr("transform", "translate(" + x + "," + y + ")"); const className = dark ? "dark-label" : "light-label"; g.classed(className, true); g.style("visibility", showLabel ? "inherit" : "hidden"); writer.write(value, measurement.width, measurement.height, { xAlign: "center", yAlign: "center", }, g.node()); } } }
the_stack
* Hyperledger Cactus Plugin - Odap Hermes * Implementation for Odap and Hermes * * The version of the OpenAPI document: 0.0.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Configuration } from './configuration'; import globalAxios, { AxiosPromise, AxiosInstance } from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base'; /** * * @export * @interface AssetProfile */ export interface AssetProfile { /** * * @type {string} * @memberof AssetProfile */ issuer?: string; /** * * @type {string} * @memberof AssetProfile */ assetCode?: string; /** * * @type {string} * @memberof AssetProfile */ assetCodeType?: string; /** * * @type {string} * @memberof AssetProfile */ issuanceDate?: string; /** * * @type {string} * @memberof AssetProfile */ expirationDate: string; /** * * @type {string} * @memberof AssetProfile */ verificationEndPoint?: string; /** * * @type {string} * @memberof AssetProfile */ digitalSignature?: string; /** * * @type {string} * @memberof AssetProfile */ prospectusLink?: string; /** * * @type {Array<any>} * @memberof AssetProfile */ keyInformationLink?: Array<any>; /** * * @type {Array<any>} * @memberof AssetProfile */ keyWord?: Array<any>; /** * * @type {Array<any>} * @memberof AssetProfile */ transferRestriction?: Array<any>; /** * * @type {Array<any>} * @memberof AssetProfile */ ledgerRequirements?: Array<any>; } /** * * @export * @interface CommitFinalV1Request */ export interface CommitFinalV1Request { /** * * @type {string} * @memberof CommitFinalV1Request */ sessionID: string; /** * * @type {string} * @memberof CommitFinalV1Request */ messageType: string; /** * * @type {string} * @memberof CommitFinalV1Request */ clientIdentityPubkey: string; /** * * @type {string} * @memberof CommitFinalV1Request */ serverIdentityPubkey: string; /** * * @type {string} * @memberof CommitFinalV1Request */ commitFinalClaim: string; /** * * @type {object} * @memberof CommitFinalV1Request */ commitFinalClaimFormat?: object; /** * * @type {string} * @memberof CommitFinalV1Request */ hashCommitPrepareAck: string; /** * * @type {number} * @memberof CommitFinalV1Request */ clientTransferNumber?: number | null; /** * * @type {string} * @memberof CommitFinalV1Request */ clientSignature: string; } /** * * @export * @interface CommitFinalV1Response */ export interface CommitFinalV1Response { /** * * @type {string} * @memberof CommitFinalV1Response */ messageType: string; /** * * @type {string} * @memberof CommitFinalV1Response */ clientIdentityPubkey?: string; /** * * @type {string} * @memberof CommitFinalV1Response */ serverIdentityPubkey: string; /** * * @type {string} * @memberof CommitFinalV1Response */ commitAcknowledgementClaim: string; /** * * @type {object} * @memberof CommitFinalV1Response */ commitAcknowledgementClaimFormat?: object; /** * * @type {string} * @memberof CommitFinalV1Response */ hashCommitFinal: string; /** * * @type {number} * @memberof CommitFinalV1Response */ serverTransferNumber?: number; /** * * @type {string} * @memberof CommitFinalV1Response */ serverSignature: string; } /** * * @export * @interface CommitPreparationV1Request */ export interface CommitPreparationV1Request { /** * * @type {string} * @memberof CommitPreparationV1Request */ sessionID: string; /** * * @type {string} * @memberof CommitPreparationV1Request */ messageType: string; /** * * @type {string} * @memberof CommitPreparationV1Request */ clientIdentityPubkey: string; /** * * @type {string} * @memberof CommitPreparationV1Request */ serverIdentityPubkey: string; /** * * @type {string} * @memberof CommitPreparationV1Request */ hashLockEvidenceAck: string; /** * * @type {number} * @memberof CommitPreparationV1Request */ clientTransferNumber?: number; /** * * @type {string} * @memberof CommitPreparationV1Request */ clientSignature: string; } /** * * @export * @interface CommitPreparationV1Response */ export interface CommitPreparationV1Response { /** * * @type {string} * @memberof CommitPreparationV1Response */ messageType: string; /** * * @type {string} * @memberof CommitPreparationV1Response */ clientIdentityPubkey: string; /** * * @type {string} * @memberof CommitPreparationV1Response */ serverIdentityPubkey: string; /** * * @type {string} * @memberof CommitPreparationV1Response */ hashCommitPrep: string; /** * * @type {string} * @memberof CommitPreparationV1Response */ serverTransferNumber?: string; /** * * @type {string} * @memberof CommitPreparationV1Response */ serverSignature: string; } /** * * @export * @enum {string} */ export enum CredentialProfile { Saml = 'SAML', Oauth = 'OAUTH', X509 = 'X509' } /** * * @export * @interface History */ export interface History { /** * * @type {Array<object>} * @memberof History */ Transactions?: Array<object>; /** * * @type {Array<object>} * @memberof History */ Actions?: Array<object>; /** * * @type {string} * @memberof History */ Origin?: string; /** * * @type {string} * @memberof History */ Destination?: string; /** * * @type {string} * @memberof History */ Balance?: string; /** * * @type {object} * @memberof History */ CurrentStatus?: object; /** * * @type {object} * @memberof History */ ApplicationSpecificParameters?: object; } /** * * @export * @interface LockEvidenceV1Request */ export interface LockEvidenceV1Request { /** * * @type {string} * @memberof LockEvidenceV1Request */ sessionID: string; /** * * @type {string} * @memberof LockEvidenceV1Request */ clientIdentityPubkey: string; /** * * @type {string} * @memberof LockEvidenceV1Request */ serverIdentityPubkey: string; /** * * @type {string} * @memberof LockEvidenceV1Request */ lockEvidenceClaim: string; /** * * @type {object} * @memberof LockEvidenceV1Request */ lockEvidenceFormat?: object; /** * * @type {string} * @memberof LockEvidenceV1Request */ lockEvidenceExpiration: string; /** * * @type {string} * @memberof LockEvidenceV1Request */ hashCommenceAckRequest: string; /** * * @type {number} * @memberof LockEvidenceV1Request */ clientTransferNumber?: number | null; /** * * @type {string} * @memberof LockEvidenceV1Request */ clientSignature: string; /** * * @type {string} * @memberof LockEvidenceV1Request */ messageType: string; /** * * @type {string} * @memberof LockEvidenceV1Request */ messageHash?: string; } /** * * @export * @interface LockEvidenceV1Response */ export interface LockEvidenceV1Response { /** * * @type {string} * @memberof LockEvidenceV1Response */ clientIdentityPubkey: string; /** * * @type {string} * @memberof LockEvidenceV1Response */ serverIdentityPubkey: string; /** * * @type {string} * @memberof LockEvidenceV1Response */ hashLockEvidenceRequest: string; /** * * @type {number} * @memberof LockEvidenceV1Response */ serverTransferNumber?: number | null; /** * * @type {string} * @memberof LockEvidenceV1Response */ serverSignature: string; /** * * @type {string} * @memberof LockEvidenceV1Response */ messageType: string; } /** * * @export * @interface OdapMessage */ export interface OdapMessage { /** * * @type {number} * @memberof OdapMessage */ SequenceNumber?: number; /** * * @type {string} * @memberof OdapMessage */ Phase?: OdapMessagePhaseEnum; /** * * @type {string} * @memberof OdapMessage */ ResourceURL?: string; /** * * @type {string} * @memberof OdapMessage */ DeveloperURN?: string; /** * * @type {OdapMessageActionResponse} * @memberof OdapMessage */ ActionResponse?: OdapMessageActionResponse; /** * * @type {string} * @memberof OdapMessage */ CredentialProfile?: OdapMessageCredentialProfileEnum; /** * * @type {Array<any>} * @memberof OdapMessage */ CredentialBlock?: Array<any>; /** * * @type {PayloadProfile} * @memberof OdapMessage */ CredentialsProfile?: PayloadProfile; /** * * @type {object} * @memberof OdapMessage */ ApplicationProfile?: object; /** * * @type {object} * @memberof OdapMessage */ Payload?: object; /** * * @type {string} * @memberof OdapMessage */ PayloadHash?: string; /** * * @type {string} * @memberof OdapMessage */ MessageSignature?: string; } /** * @export * @enum {string} */ export enum OdapMessagePhaseEnum { TransferInitialization = 'TransferInitialization', LockEvidenceVerification = 'LockEvidenceVerification', CommitmentEstablishment = 'CommitmentEstablishment' } /** * @export * @enum {string} */ export enum OdapMessageCredentialProfileEnum { Saml = 'SAML', OAuth = 'OAuth', X509 = 'X509' } /** * * @export * @interface OdapMessageActionResponse */ export interface OdapMessageActionResponse { /** * * @type {string} * @memberof OdapMessageActionResponse */ ResponseCode?: OdapMessageActionResponseResponseCodeEnum; /** * * @type {Array<any>} * @memberof OdapMessageActionResponse */ Arguments?: Array<any>; } /** * @export * @enum {string} */ export enum OdapMessageActionResponseResponseCodeEnum { OK = '200', RESOURCE_NOT_FOUND = '404' } /** * * @export * @interface PayloadProfile */ export interface PayloadProfile { /** * * @type {AssetProfile} * @memberof PayloadProfile */ assetProfile: AssetProfile; /** * * @type {string} * @memberof PayloadProfile */ capabilities?: string; } /** * * @export * @interface SendClientV1Request */ export interface SendClientV1Request { /** * * @type {string} * @memberof SendClientV1Request */ version: string; /** * * @type {string} * @memberof SendClientV1Request */ loggingProfile: string; /** * * @type {string} * @memberof SendClientV1Request */ accessControlProfile: string; /** * * @type {string} * @memberof SendClientV1Request */ assetControlProfile: string; /** * * @type {string} * @memberof SendClientV1Request */ applicationProfile: string; /** * * @type {AssetProfile} * @memberof SendClientV1Request */ assetProfile: AssetProfile; /** * * @type {PayloadProfile} * @memberof SendClientV1Request */ payLoadProfile: PayloadProfile; /** * * @type {string} * @memberof SendClientV1Request */ sourceGateWayDltSystem: string; /** * * @type {string} * @memberof SendClientV1Request */ recipientGateWayDltSystem: string; /** * * @type {string} * @memberof SendClientV1Request */ recipientGateWayPubkey: string; /** * * @type {string} * @memberof SendClientV1Request */ originatorPubkey: string; /** * * @type {string} * @memberof SendClientV1Request */ beneficiaryPubkey: string; /** * * @type {string} * @memberof SendClientV1Request */ clientIdentityPubkey: string; /** * * @type {string} * @memberof SendClientV1Request */ serverIdentityPubkey: string; /** * * @type {string} * @memberof SendClientV1Request */ clientDltSystem: string; /** * * @type {string} * @memberof SendClientV1Request */ serverDltSystem: string; /** * * @type {SendClientV1RequestServerGatewayConfiguration} * @memberof SendClientV1Request */ serverGatewayConfiguration: SendClientV1RequestServerGatewayConfiguration; } /** * * @export * @interface SendClientV1RequestServerGatewayConfiguration */ export interface SendClientV1RequestServerGatewayConfiguration { /** * * @type {string} * @memberof SendClientV1RequestServerGatewayConfiguration */ apiHost: string; } /** * * @export * @interface SessionData */ export interface SessionData { /** * * @type {number} * @memberof SessionData */ step?: number; /** * * @type {string} * @memberof SessionData */ initializationMsgHash?: string; /** * * @type {string} * @memberof SessionData */ loggingProfile?: string; /** * * @type {string} * @memberof SessionData */ accessControlProfile?: string; /** * * @type {string} * @memberof SessionData */ applicationProfile?: string; /** * * @type {AssetProfile} * @memberof SessionData */ assetProfile?: AssetProfile; /** * * @type {string} * @memberof SessionData */ initializationRequestMsgSignature?: string; /** * * @type {string} * @memberof SessionData */ sourceGateWayPubkey?: string; /** * * @type {string} * @memberof SessionData */ sourceGateWayDltSystem?: string; /** * * @type {string} * @memberof SessionData */ recipientGateWayPubkey?: string; /** * * @type {string} * @memberof SessionData */ recipientGateWayDltSystem?: string; /** * * @type {string} * @memberof SessionData */ initialMsgRcvTimeStamp?: string; /** * * @type {string} * @memberof SessionData */ initialMsgProcessedTimeStamp?: string; /** * * @type {string} * @memberof SessionData */ originatorPubkey?: string; /** * * @type {string} * @memberof SessionData */ beneficiaryPubkey?: string; /** * * @type {string} * @memberof SessionData */ clientIdentityPubkey?: string; /** * * @type {string} * @memberof SessionData */ serverIdentityPubkey?: string; /** * * @type {string} * @memberof SessionData */ clientDltSystem?: string; /** * * @type {string} * @memberof SessionData */ serverDltSystem?: string; /** * * @type {string} * @memberof SessionData */ commenceReqHash?: string; /** * * @type {string} * @memberof SessionData */ commenceAckHash?: string; /** * * @type {string} * @memberof SessionData */ clientSignatureForCommenceReq?: string; /** * * @type {string} * @memberof SessionData */ serverSignatureForCommenceAck?: string; /** * * @type {string} * @memberof SessionData */ lockEvidenceClaim?: string; /** * * @type {string} * @memberof SessionData */ clientSignatureForLockEvidence?: string; /** * * @type {string} * @memberof SessionData */ serverSignatureForLockEvidence?: string; /** * * @type {string} * @memberof SessionData */ lockEvidenceAckHash?: string; /** * * @type {string} * @memberof SessionData */ clientSignatureForCommitPreparation?: string; /** * * @type {string} * @memberof SessionData */ commitPrepareReqHash?: string; /** * * @type {string} * @memberof SessionData */ commitPrepareAckHash?: string; /** * * @type {string} * @memberof SessionData */ serverSignatureForCommitPreparation?: string; /** * * @type {string} * @memberof SessionData */ commitFinalClaim?: string; /** * * @type {string} * @memberof SessionData */ clientSignatureForCommitFinal?: string; /** * * @type {string} * @memberof SessionData */ commitAckClaim?: string; /** * * @type {string} * @memberof SessionData */ serverSignatureForCommitFinal?: string; /** * * @type {string} * @memberof SessionData */ commitFinalReqHash?: string; /** * * @type {string} * @memberof SessionData */ commitFinalAckHash?: string; /** * * @type {boolean} * @memberof SessionData */ isFabricAssetDeleted?: boolean; /** * * @type {boolean} * @memberof SessionData */ isFabricAssetLocked?: boolean; /** * * @type {boolean} * @memberof SessionData */ isFabricAssetCreated?: boolean; /** * * @type {boolean} * @memberof SessionData */ isBesuAssetCreated?: boolean; /** * * @type {boolean} * @memberof SessionData */ isBesuAssetDeleted?: boolean; /** * * @type {boolean} * @memberof SessionData */ isBesuAssetLocked?: boolean; /** * * @type {string} * @memberof SessionData */ fabricAssetID?: string; /** * * @type {number} * @memberof SessionData */ fabricAssetSize?: number; /** * * @type {string} * @memberof SessionData */ besuAssetID?: string; } /** * * @export * @interface TransferCommenceV1Request */ export interface TransferCommenceV1Request { /** * * @type {string} * @memberof TransferCommenceV1Request */ sessionID: string; /** * * @type {string} * @memberof TransferCommenceV1Request */ messageType: string; /** * * @type {string} * @memberof TransferCommenceV1Request */ originatorPubkey: string; /** * * @type {string} * @memberof TransferCommenceV1Request */ beneficiaryPubkey: string; /** * * @type {string} * @memberof TransferCommenceV1Request */ senderDltSystem: string; /** * * @type {string} * @memberof TransferCommenceV1Request */ recipientDltSystem: string; /** * * @type {string} * @memberof TransferCommenceV1Request */ clientIdentityPubkey: string; /** * * @type {string} * @memberof TransferCommenceV1Request */ serverIdentityPubkey: string; /** * * @type {string} * @memberof TransferCommenceV1Request */ hashAssetProfile: string; /** * * @type {number} * @memberof TransferCommenceV1Request */ assetUnit?: number; /** * * @type {string} * @memberof TransferCommenceV1Request */ hashPrevMessage: string; /** * * @type {number} * @memberof TransferCommenceV1Request */ clientTransferNumber?: number | null; /** * * @type {string} * @memberof TransferCommenceV1Request */ clientSignature: string; } /** * * @export * @interface TransferCommenceV1Response */ export interface TransferCommenceV1Response { /** * * @type {string} * @memberof TransferCommenceV1Response */ clientIdentityPubkey: string; /** * * @type {string} * @memberof TransferCommenceV1Response */ serverIdentityPubkey: string; /** * * @type {string} * @memberof TransferCommenceV1Response */ hashCommenceRequest: string; /** * * @type {number} * @memberof TransferCommenceV1Response */ serverTransferNumber?: number | null; /** * * @type {string} * @memberof TransferCommenceV1Response */ serverSignature: string; /** * * @type {string} * @memberof TransferCommenceV1Response */ messageType: string; /** * * @type {string} * @memberof TransferCommenceV1Response */ messageHash?: string; } /** * * @export * @interface TransferCompleteV1Request */ export interface TransferCompleteV1Request { /** * * @type {string} * @memberof TransferCompleteV1Request */ sessionID: string; /** * * @type {string} * @memberof TransferCompleteV1Request */ messageType: string; /** * * @type {string} * @memberof TransferCompleteV1Request */ clientIdentityPubkey: string; /** * * @type {string} * @memberof TransferCompleteV1Request */ serverIdentityPubkey: string; /** * * @type {string} * @memberof TransferCompleteV1Request */ hashCommitFinalAck: string; /** * * @type {number} * @memberof TransferCompleteV1Request */ clientTransferNumber?: number | null; /** * * @type {string} * @memberof TransferCompleteV1Request */ clientSignature: string; /** * * @type {string} * @memberof TransferCompleteV1Request */ hashTransferCommence: string; } /** * * @export * @interface TransferCompleteV1Response */ export interface TransferCompleteV1Response { /** * * @type {string} * @memberof TransferCompleteV1Response */ ok: string; } /** * * @export * @interface TransferInitializationV1Request */ export interface TransferInitializationV1Request { /** * * @type {string} * @memberof TransferInitializationV1Request */ version?: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ developerURN?: string; /** * * @type {CredentialProfile} * @memberof TransferInitializationV1Request */ credentialProfile?: CredentialProfile; /** * * @type {PayloadProfile} * @memberof TransferInitializationV1Request */ payloadProfile: PayloadProfile; /** * * @type {string} * @memberof TransferInitializationV1Request */ applicationProfile: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ loggingProfile: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ accessControlProfile: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ initializationRequestMessageSignature: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ sourceGatewayPubkey: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ sourceGateWayDltSystem: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ recipientGateWayPubkey: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ recipientGateWayDltSystem: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ escrowType?: TransferInitializationV1RequestEscrowTypeEnum; /** * * @type {string} * @memberof TransferInitializationV1Request */ expiryTime?: string; /** * * @type {boolean} * @memberof TransferInitializationV1Request */ multipleClaimsAllowed?: boolean; /** * * @type {boolean} * @memberof TransferInitializationV1Request */ multipleCancelsAllowed?: boolean; /** * * @type {object} * @memberof TransferInitializationV1Request */ permissions?: object; /** * * @type {string} * @memberof TransferInitializationV1Request */ origin?: string; /** * * @type {string} * @memberof TransferInitializationV1Request */ destination?: string; /** * * @type {object} * @memberof TransferInitializationV1Request */ subsequentCalls?: object; /** * * @type {Array<History>} * @memberof TransferInitializationV1Request */ histories?: Array<History>; } /** * @export * @enum {string} */ export enum TransferInitializationV1RequestEscrowTypeEnum { Faucet = 'FAUCET', Timelock = 'TIMELOCK', Hashlock = 'HASHLOCK', Hashtimelock = 'HASHTIMELOCK', Multiclaimpc = 'MULTICLAIMPC', Destroy = 'DESTROY', Burn = 'BURN' } /** * * @export * @interface TransferInitializationV1Response */ export interface TransferInitializationV1Response { /** * * @type {string} * @memberof TransferInitializationV1Response */ sessionID: string; /** * * @type {number} * @memberof TransferInitializationV1Response */ sequenceNumber?: number; /** * * @type {string} * @memberof TransferInitializationV1Response */ odapPhase?: TransferInitializationV1ResponseOdapPhaseEnum; /** * * @type {string} * @memberof TransferInitializationV1Response */ initialRequestMessageHash: string; /** * * @type {string} * @memberof TransferInitializationV1Response */ destination?: string; /** * * @type {string} * @memberof TransferInitializationV1Response */ timeStamp: string; /** * * @type {string} * @memberof TransferInitializationV1Response */ processedTimeStamp: string; /** * * @type {string} * @memberof TransferInitializationV1Response */ serverIdentityPubkey: string; } /** * @export * @enum {string} */ export enum TransferInitializationV1ResponseOdapPhaseEnum { TransferInitialization = 'TransferInitialization', LockEvidenceVerification = 'LockEvidenceVerification', CommitmentEstablishment = 'CommitmentEstablishment' } /** * DefaultApi - axios parameter creator * @export */ export const DefaultApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * * @param {TransferInitializationV1Request} [transferInitializationV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase1TransferInitiationV1: async (transferInitializationV1Request?: TransferInitializationV1Request, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hemres/phase1/transferinitiation`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(transferInitializationV1Request, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {LockEvidenceV1Request} [lockEvidenceV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase2LockEvidenceV1: async (lockEvidenceV1Request?: LockEvidenceV1Request, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hemres/phase2/lockevidence`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(lockEvidenceV1Request, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {TransferCommenceV1Request} [transferCommenceV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase2TransferCommenceV1: async (transferCommenceV1Request?: TransferCommenceV1Request, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hemres/phase2/transfercommence`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(transferCommenceV1Request, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {CommitFinalV1Request} [commitFinalV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase3CommitFinalV1: async (commitFinalV1Request?: CommitFinalV1Request, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hemres/phase3/commitfinal`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(commitFinalV1Request, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {CommitPreparationV1Request} [commitPreparationV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase3CommitPreparationV1: async (commitPreparationV1Request?: CommitPreparationV1Request, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hemres/phase3/commitpreparation`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(commitPreparationV1Request, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {TransferCompleteV1Request} [transferCompleteV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase3TransferCompleteV1: async (transferCompleteV1Request?: TransferCompleteV1Request, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hemres/phase3/transfercomplete`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(transferCompleteV1Request, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @param {SendClientV1Request} [sendClientV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ sendClientRequestV1: async (sendClientV1Request?: SendClientV1Request, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/@hyperledger/cactus-plugin-odap-hemres/sendclientrequest`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(sendClientV1Request, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, } }; /** * DefaultApi - functional programming interface * @export */ export const DefaultApiFp = function(configuration?: Configuration) { const localVarAxiosParamCreator = DefaultApiAxiosParamCreator(configuration) return { /** * * @param {TransferInitializationV1Request} [transferInitializationV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async phase1TransferInitiationV1(transferInitializationV1Request?: TransferInitializationV1Request, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<TransferInitializationV1Response>> { const localVarAxiosArgs = await localVarAxiosParamCreator.phase1TransferInitiationV1(transferInitializationV1Request, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {LockEvidenceV1Request} [lockEvidenceV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async phase2LockEvidenceV1(lockEvidenceV1Request?: LockEvidenceV1Request, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<LockEvidenceV1Response>> { const localVarAxiosArgs = await localVarAxiosParamCreator.phase2LockEvidenceV1(lockEvidenceV1Request, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {TransferCommenceV1Request} [transferCommenceV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async phase2TransferCommenceV1(transferCommenceV1Request?: TransferCommenceV1Request, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<TransferCommenceV1Response>> { const localVarAxiosArgs = await localVarAxiosParamCreator.phase2TransferCommenceV1(transferCommenceV1Request, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {CommitFinalV1Request} [commitFinalV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async phase3CommitFinalV1(commitFinalV1Request?: CommitFinalV1Request, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<CommitFinalV1Response>> { const localVarAxiosArgs = await localVarAxiosParamCreator.phase3CommitFinalV1(commitFinalV1Request, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {CommitPreparationV1Request} [commitPreparationV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async phase3CommitPreparationV1(commitPreparationV1Request?: CommitPreparationV1Request, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<CommitPreparationV1Response>> { const localVarAxiosArgs = await localVarAxiosParamCreator.phase3CommitPreparationV1(commitPreparationV1Request, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {TransferCompleteV1Request} [transferCompleteV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async phase3TransferCompleteV1(transferCompleteV1Request?: TransferCompleteV1Request, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<any>> { const localVarAxiosArgs = await localVarAxiosParamCreator.phase3TransferCompleteV1(transferCompleteV1Request, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @param {SendClientV1Request} [sendClientV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async sendClientRequestV1(sendClientV1Request?: SendClientV1Request, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<any>> { const localVarAxiosArgs = await localVarAxiosParamCreator.sendClientRequestV1(sendClientV1Request, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, } }; /** * DefaultApi - factory interface * @export */ export const DefaultApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { const localVarFp = DefaultApiFp(configuration) return { /** * * @param {TransferInitializationV1Request} [transferInitializationV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase1TransferInitiationV1(transferInitializationV1Request?: TransferInitializationV1Request, options?: any): AxiosPromise<TransferInitializationV1Response> { return localVarFp.phase1TransferInitiationV1(transferInitializationV1Request, options).then((request) => request(axios, basePath)); }, /** * * @param {LockEvidenceV1Request} [lockEvidenceV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase2LockEvidenceV1(lockEvidenceV1Request?: LockEvidenceV1Request, options?: any): AxiosPromise<LockEvidenceV1Response> { return localVarFp.phase2LockEvidenceV1(lockEvidenceV1Request, options).then((request) => request(axios, basePath)); }, /** * * @param {TransferCommenceV1Request} [transferCommenceV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase2TransferCommenceV1(transferCommenceV1Request?: TransferCommenceV1Request, options?: any): AxiosPromise<TransferCommenceV1Response> { return localVarFp.phase2TransferCommenceV1(transferCommenceV1Request, options).then((request) => request(axios, basePath)); }, /** * * @param {CommitFinalV1Request} [commitFinalV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase3CommitFinalV1(commitFinalV1Request?: CommitFinalV1Request, options?: any): AxiosPromise<CommitFinalV1Response> { return localVarFp.phase3CommitFinalV1(commitFinalV1Request, options).then((request) => request(axios, basePath)); }, /** * * @param {CommitPreparationV1Request} [commitPreparationV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase3CommitPreparationV1(commitPreparationV1Request?: CommitPreparationV1Request, options?: any): AxiosPromise<CommitPreparationV1Response> { return localVarFp.phase3CommitPreparationV1(commitPreparationV1Request, options).then((request) => request(axios, basePath)); }, /** * * @param {TransferCompleteV1Request} [transferCompleteV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ phase3TransferCompleteV1(transferCompleteV1Request?: TransferCompleteV1Request, options?: any): AxiosPromise<any> { return localVarFp.phase3TransferCompleteV1(transferCompleteV1Request, options).then((request) => request(axios, basePath)); }, /** * * @param {SendClientV1Request} [sendClientV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ sendClientRequestV1(sendClientV1Request?: SendClientV1Request, options?: any): AxiosPromise<any> { return localVarFp.sendClientRequestV1(sendClientV1Request, options).then((request) => request(axios, basePath)); }, }; }; /** * DefaultApi - object-oriented interface * @export * @class DefaultApi * @extends {BaseAPI} */ export class DefaultApi extends BaseAPI { /** * * @param {TransferInitializationV1Request} [transferInitializationV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public phase1TransferInitiationV1(transferInitializationV1Request?: TransferInitializationV1Request, options?: any) { return DefaultApiFp(this.configuration).phase1TransferInitiationV1(transferInitializationV1Request, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {LockEvidenceV1Request} [lockEvidenceV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public phase2LockEvidenceV1(lockEvidenceV1Request?: LockEvidenceV1Request, options?: any) { return DefaultApiFp(this.configuration).phase2LockEvidenceV1(lockEvidenceV1Request, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {TransferCommenceV1Request} [transferCommenceV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public phase2TransferCommenceV1(transferCommenceV1Request?: TransferCommenceV1Request, options?: any) { return DefaultApiFp(this.configuration).phase2TransferCommenceV1(transferCommenceV1Request, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {CommitFinalV1Request} [commitFinalV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public phase3CommitFinalV1(commitFinalV1Request?: CommitFinalV1Request, options?: any) { return DefaultApiFp(this.configuration).phase3CommitFinalV1(commitFinalV1Request, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {CommitPreparationV1Request} [commitPreparationV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public phase3CommitPreparationV1(commitPreparationV1Request?: CommitPreparationV1Request, options?: any) { return DefaultApiFp(this.configuration).phase3CommitPreparationV1(commitPreparationV1Request, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {TransferCompleteV1Request} [transferCompleteV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public phase3TransferCompleteV1(transferCompleteV1Request?: TransferCompleteV1Request, options?: any) { return DefaultApiFp(this.configuration).phase3TransferCompleteV1(transferCompleteV1Request, options).then((request) => request(this.axios, this.basePath)); } /** * * @param {SendClientV1Request} [sendClientV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public sendClientRequestV1(sendClientV1Request?: SendClientV1Request, options?: any) { return DefaultApiFp(this.configuration).sendClientRequestV1(sendClientV1Request, options).then((request) => request(this.axios, this.basePath)); } }
the_stack
import React, { useRef, useCallback, useEffect, useState, useMemo } from 'react' import { EMState, createEM } from "./em" import { makeDrawSquareInfo, makeDrawEllipseInfo, DrawShape } from "./em/drawing" import { signalSourceToDescriptor, descriptorToSignalSource, makeMaterialMap } from './em/serialization' import { SideBarType, BrushType, CollapsibleContainer, SettingsComponent, ExamplesComponent, MaterialBrushMenu, SignalBrushMenu, MultiMenu, MultiMenuChild, InfoBox, LoadingIndicator, ShareBox, ResetButtons, BrushSelectionButtons, MenuSelectionButtons, BrushCursor, MiscButtons, InteractiveCanvas, FullscreenView } from './components' import { clamp, qualityPresets } from './util' import { getSharedSimulatorMap, shareSimulatorMap } from './share' const defaultPreset = qualityPresets["Medium"] const defaultSignalBrushValue = 10 const defaultSignalBrushSize = 1 const defaultSignalFrequency = 3 const defaultPermittivityBrushValue = 5 const defaultPermeabilityBrushValue = 1 const defaultConductivityBrushValue = 0 const defaultMaterialBrushSize = 5 const defaultBrushDrawShape = DrawShape.Square const initialDt = defaultPreset.dt const initialCellSize = defaultPreset.cellSize const initialSimulationSpeed = 1 const initialGridSizeLongest = defaultPreset.gridSizeLongest const initialResolutionScale = defaultPreset.resolutionScale const initialWindowSize: [number, number] = [window.innerWidth, window.innerHeight] const initialCanvasSize: [number, number] = calculateCanvasSize(initialWindowSize, initialResolutionScale) const initialGridSize: [number, number] = calculateGridSize(initialGridSizeLongest, initialCanvasSize) const initialReflectiveBoundary = false function calculateCanvasSize(windowSize: [number, number], resolutionScale: number): [number, number] { return [Math.round(windowSize[0] * resolutionScale), Math.round(windowSize[1] * resolutionScale)] } function calculateGridSize(gridSizeLongest: number, canvasSize: [number, number]): [number, number] { const canvasAspect = canvasSize[0] / canvasSize[1] return canvasSize[0] >= canvasSize[1] ? [gridSizeLongest, Math.ceil(gridSizeLongest / canvasAspect)] : [Math.ceil(gridSizeLongest * canvasAspect), gridSizeLongest] } export default function () { const urlShareId = window.location.hash ? window.location.hash.substr(1) : null const [shareId, setShareId] = useState<string | null>(urlShareId) const drawCanvasRef = useRef<HTMLCanvasElement>(null) const [canvasSize, setCanvasSize] = useState<[number, number]>(initialCanvasSize) const [windowSize, setWindowSize] = useState<[number, number]>(initialWindowSize) const [gridSizeLongest, setGridSizeLongest] = useState(initialGridSizeLongest) const [dt, setDt] = useState(initialDt) const [cellSize, setCellSize] = useState(initialCellSize) const [resolutionScale, setResolutionScale] = useState(initialResolutionScale) const [simulationSpeed, setSimulationSpeed] = useState(initialSimulationSpeed) const [reflectiveBoundary, setReflectiveBoundary] = useState(initialReflectiveBoundary) const gridSize = useMemo<[number, number]>(() => calculateGridSize(gridSizeLongest, canvasSize), [canvasSize, gridSizeLongest]) const [em, setEm] = useState<EMState | null>(null) // Would use useMemo for gpu here, but useMemo does not seem to work with ref dependencies. useEffect(() => { if (drawCanvasRef.current) { setEm(createEM(drawCanvasRef.current, initialGridSize, initialCellSize, initialReflectiveBoundary, initialDt)) } }, [drawCanvasRef]) // Window resize canvas useEffect(() => { const adjustCanvasSize = () => { const wndSize: [number, number] = [window.innerWidth, window.innerHeight] setCanvasSize(calculateCanvasSize(wndSize, resolutionScale)) setWindowSize(wndSize) } adjustCanvasSize() window.addEventListener("resize", adjustCanvasSize) return () => window.removeEventListener("resize", adjustCanvasSize) }, [resolutionScale]) // Load share id useEffect(() => { if (em && urlShareId) { setShowLoading(true) console.log(`Loading ${urlShareId}`) getSharedSimulatorMap(urlShareId).then(simulatorMap => { // Load material em.loadMaterialFromComponents( simulatorMap.materialMap.permittivity, simulatorMap.materialMap.permeability, simulatorMap.materialMap.conductivity ) // Load settings setDt(simulatorMap.simulationSettings.dt) setGridSizeLongest(Math.max(simulatorMap.simulationSettings.gridSize[0], simulatorMap.simulationSettings.gridSize[1])) setCellSize(simulatorMap.simulationSettings.cellSize) // Load sources em.setSources(simulatorMap.sourceDescriptors.map(desc => descriptorToSignalSource(desc))) console.log(`Loaded ${urlShareId}`) }).catch(err => console.error(`Error getting share ${urlShareId}: ${JSON.stringify(err)}`)).finally(() => setShowLoading(false)) } }, [em, urlShareId]) // Update render sim output size useEffect(() => { if (em) { em.adjustCanvasSize(canvasSize) em.resetFields() em.resetMaterials() } }, [em, canvasSize]) // Update simulator grid size useEffect(() => { if (em) { em.setGridSize(gridSize) em.resetFields() em.resetMaterials() } }, [em, gridSize]) // Update simulator cell size useEffect(() => { if (em) { em.setCellSize(cellSize) } }, [em, cellSize]) // Update reflective boundary useEffect(() => { if (em) { em.setReflectiveBoundary(reflectiveBoundary) } }, [em, reflectiveBoundary]) const [signalBrushSize, setSignalBrushSize] = useState(defaultSignalBrushSize) const [signalBrushValue, setSignalBrushValue] = useState(defaultSignalBrushValue) const [activeBrushShape, setActiveBrushDrawShape] = useState<DrawShape>(defaultBrushDrawShape) const [materialBrushSize, setMaterialBrushSize] = useState(defaultMaterialBrushSize) const [permittivityBrushValue, setPermittivityBrushValue] = useState(defaultPermittivityBrushValue) const [permeabilityBrushValue, setPermeabilityBrushValue] = useState(defaultPermeabilityBrushValue) const [conductivityBrushValue, setConductivityBrushValue] = useState(defaultConductivityBrushValue) const [signalFrequency, setSignalFrequency] = useState(defaultSignalFrequency) const [activeBrush, setActiveBrush] = useState(BrushType.Signal) const [mousePosition, setMousePosition] = useState<[number, number] | null>(null) const signalStrength = useRef(0) const mouseDownPos = useRef<[number, number] | null>(null) const [shareInProgress, setShareInProgress] = useState(false) const [sideMenuCollapsed, setSideMenuCollapsed] = useState(false) const [infoVisible, setInfoVisible] = useState(false) const [showLoading, setShowLoading] = useState(false) // Snap input across a line const [snapInput, setSnapInput] = useState(false) // Convert from window location to the coordinates used // by the simulator's draw function. const windowToSimulationPoint = useMemo(() => { return (windowPoint: [number, number]) => { const simulationPoint: [number, number] = [ clamp(0, 1, windowPoint[0] / windowSize[0]), clamp(0, 1, 1 - windowPoint[1] / windowSize[1]) ] return simulationPoint } }, [windowSize]) // Simulate one step const simStep = useCallback(() => { if (em) { if (mouseDownPos.current !== null) { const center: [number, number] = windowToSimulationPoint(mouseDownPos.current) const brushHalfSize: [number, number] = [ signalBrushSize / gridSize[0] / 2, signalBrushSize / gridSize[1] / 2 ] const value = -signalBrushValue * 2000 * Math.cos(2 * Math.PI * signalFrequency * em.getTime()) const drawInfo = activeBrushShape === DrawShape.Square ? makeDrawSquareInfo(center, brushHalfSize, value) : makeDrawEllipseInfo(center, brushHalfSize, value) em.injectSignal(drawInfo, dt) } em.stepSim(dt) } }, [em, dt, signalFrequency, signalBrushValue, signalBrushSize, windowToSimulationPoint, activeBrushShape, gridSize]) // Change simulation speed useEffect(() => { if (simulationSpeed > 0) { const timer = setInterval(simStep, 1000 / simulationSpeed * dt) return () => clearInterval(timer) } return undefined }, [simStep, dt, simulationSpeed]) // Draw one frame const drawStep = useCallback(() => { if (em) { if (drawCanvasRef.current) { const cnvSize = calculateCanvasSize([window.innerWidth, window.innerHeight], resolutionScale) drawCanvasRef.current.width = cnvSize[0] drawCanvasRef.current.height = cnvSize[1] } em?.renderToCanvas(true, true) } }, [em, resolutionScale, drawCanvasRef]) // Draw loop useEffect(() => { let stop = false const drawIfNotStopped = () => { if (!stop) { drawStep() requestAnimationFrame(drawIfNotStopped) } } requestAnimationFrame(drawIfNotStopped) return () => { stop = true } }, [drawStep]) // Reset materials in the simulator const resetMaterials = useCallback(() => { if (em) { em.setSources([]) em.resetMaterials() } }, [em]) // Reset fields in the simulator const resetFields = useCallback(() => { if (em) { em.resetFields() signalStrength.current = 0 } }, [em]) const [isInputDown, setIsInputDown] = useState(false) const activeBrushSize = useMemo(() => (activeBrush === BrushType.Signal ? signalBrushSize : materialBrushSize) * (canvasSize[0] / gridSize[0]), [activeBrush, signalBrushSize, materialBrushSize, canvasSize, gridSize]) const [sideBar, setSideBar] = useState(SideBarType.SignalBrush) const [shareVisible, setShareVisible] = useState(false) const hideWhenInputDownStyle = useMemo<React.CSSProperties>(() => isInputDown ? { pointerEvents: "none", opacity: 0.2 } : {}, [isInputDown]) const generateShareUrl = useCallback(() => { if (em) { setShareInProgress(true) const material = em.getMaterial() if (material) { shareSimulatorMap({ materialMap: makeMaterialMap(material), simulationSettings: { cellSize: cellSize, dt: dt, gridSize: gridSize, simulationSpeed: 1 }, sourceDescriptors: em.getSources().map(source => signalSourceToDescriptor(source)) }) .then(shareId => setShareId(shareId)) .catch(err => console.log("Error uploading share: " + JSON.stringify(err))) .finally(() => setShareInProgress(false)) } } }, [dt, cellSize, gridSize, em]) const shareUrl = useMemo(() => { return shareId ? `${window.location.origin}${window.location.pathname}#${shareId}` : null }, [shareId]) // Open side menu when switching the side bar useEffect(() => { setSideMenuCollapsed(false) }, [sideBar]) return <> <FullscreenView> <InteractiveCanvas activeBrush={activeBrush} activeBrushShape={activeBrushShape} canvasSize={canvasSize} conductivityBrushValue={conductivityBrushValue} drawCanvasRef={drawCanvasRef} em={em} gridSize={gridSize} materialBrushSize={materialBrushSize} mouseDownPos={mouseDownPos} permeabilityBrushValue={permeabilityBrushValue} permittivityBrushValue={permittivityBrushValue} setIsInputDown={setIsInputDown} setMousePosition={setMousePosition} snapInput={snapInput} windowSize={windowSize} windowToSimulationPoint={windowToSimulationPoint} /> <BrushCursor mousePosition={mousePosition} activeBrushSize={activeBrushSize} brushShape={activeBrushShape} /> <MiscButtons extraStyle={hideWhenInputDownStyle} generateShareUrl={generateShareUrl} infoVisible={infoVisible} setInfoVisible={setInfoVisible} shareVisible={shareVisible} setShareVisible={setShareVisible} /> <BrushSelectionButtons activeSideBar={sideBar} setActiveSideBar={setSideBar} setActiveBrush={setActiveBrush} extraStyle={hideWhenInputDownStyle} /> <MenuSelectionButtons activeSideBar={sideBar} setActiveSideBar={setSideBar} extraStyle={hideWhenInputDownStyle} /> <ResetButtons resetFields={resetFields} resetMaterials={resetMaterials} extraStyle={hideWhenInputDownStyle} /> <CollapsibleContainer collapsed={sideMenuCollapsed} setCollapsed={setSideMenuCollapsed} title={sideBar.toString()} style={{ position: "absolute", top: "50%", height: "400px", marginTop: "-200px", right: 0, opacity: 0.9, ...hideWhenInputDownStyle }}> <MultiMenu activeState={sideBar}> <MultiMenuChild activateForState={SideBarType.SignalBrush}> <SignalBrushMenu signalBrushSize={signalBrushSize} setSignalBrushSize={setSignalBrushSize} signalBrushValue={signalBrushValue} setSignalBrushValue={setSignalBrushValue} signalFrequency={signalFrequency} setSignalFrequency={setSignalFrequency} activeBrushShape={activeBrushShape} setActiveBrushDrawShape={setActiveBrushDrawShape} snapInput={snapInput} setSnapInput={setSnapInput} /> </MultiMenuChild> <MultiMenuChild activateForState={SideBarType.MaterialBrush}> <MaterialBrushMenu materialBrushSize={materialBrushSize} setMaterialBrushSize={setMaterialBrushSize} permittivityBrushValue={permittivityBrushValue} setPermittivityBrushValue={setPermittivityBrushValue} permeabilityBrushValue={permeabilityBrushValue} setPermeabilityBrushValue={setPermeabilityBrushValue} conductivityBrushValue={conductivityBrushValue} setConductivityBrushValue={setConductivityBrushValue} activeBrushShape={activeBrushShape} setActiveBrushDrawShape={setActiveBrushDrawShape} snapInput={snapInput} setSnapInput={setSnapInput} /> </MultiMenuChild> <MultiMenuChild activateForState={SideBarType.Settings}> <SettingsComponent gridSizeLongest={gridSizeLongest} setGridSizeLongest={setGridSizeLongest} simulationSpeed={simulationSpeed} setSimulationSpeed={setSimulationSpeed} resolutionScale={resolutionScale} setResolutionScale={setResolutionScale} cellSize={cellSize} setCellSize={setCellSize} reflectiveBoundary={reflectiveBoundary} setReflectiveBoundary={setReflectiveBoundary} dt={dt} setDt={setDt} qualityPresets={qualityPresets} /> </MultiMenuChild> <MultiMenuChild activateForState={SideBarType.Examples}> <ExamplesComponent em={em} setCellSize={setCellSize} setDt={setDt} setGridSizeLongest={setGridSizeLongest} setSimulationSpeed={setSimulationSpeed} gridSize={gridSize} dt={dt} cellSize={cellSize} simulationSpeed={simulationSpeed} /> </MultiMenuChild> </MultiMenu> </CollapsibleContainer> </FullscreenView> <ShareBox visible={shareVisible} setVisible={setShareVisible} shareUrl={shareUrl} shareInProgress={shareInProgress} /> <LoadingIndicator visible={(shareVisible && (shareInProgress || !shareUrl)) || showLoading} /> <InfoBox visible={infoVisible} setVisible={setInfoVisible} /> </> }
the_stack
import { act, render } from "@testing-library/svelte"; import { suppressConsoleLogs } from "$lib/test-utils/suppress-console-logs"; import TestRenderer from "$lib/test-utils/TestRenderer.svelte"; import { Tab, TabGroup, TabList, TabPanel, TabPanels } from "."; import { assertActiveElement, assertTabs, getByText, getTabs } from "$lib/test-utils/accessibility-assertions"; import { click, Keys, press, shift } from "$lib/test-utils/interactions"; import Button from "$lib/internal/elements/Button.svelte"; import svelte from "svelte-inline-compile"; import { writable } from "svelte/store"; let mockId = 0; jest.mock('../../hooks/use-id', () => { return { useId: jest.fn(() => ++mockId), } }) beforeEach(() => mockId = 0) beforeAll(() => { // jest.spyOn(window, 'requestAnimationFrame').mockImplementation(setImmediate as any) // jest.spyOn(window, 'cancelAnimationFrame').mockImplementation(clearImmediate as any) }) afterAll(() => jest.restoreAllMocks()) describe('safeguards', () => { it.each([ ['TabList', TabList], ['Tab', Tab], ['TabPanels', TabPanels], ['TabPanel', TabPanel], ])( 'should error when we are using a <%s /> without a parent <TabGroup /> component', suppressConsoleLogs((name, Component) => { expect(() => render(Component)).toThrowError( `<${name} /> is missing a parent <TabGroup /> component.` ) }) ) it('should be possible to render TabGroup without crashing', async () => { render( TestRenderer, { allProps: [ [TabGroup, {}, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], ] }) assertTabs({ active: 0 }) }) }) describe('Rendering', () => { it('should be possible to render the TabPanels first, then the TabList', async () => { render( TestRenderer, { allProps: [ [TabGroup, {}, [ [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], ]], ] }) assertTabs({ active: 0 }) }) describe('`slot props`', () => { it('should expose the `selectedIndex` on the `TabGroup` component', async () => { render(svelte` <TabGroup let:selectedIndex> <pre id="exposed">{JSON.stringify({ selectedIndex })}</pre> <TabList> <Tab>Tab 1</Tab> <Tab>Tab 2</Tab> <Tab>Tab 3</Tab> </TabList> <TabPanels> <TabPanel>Content 1</TabPanel> <TabPanel>Content 2</TabPanel> <TabPanel>Content 3</TabPanel> </TabPanels> </TabGroup> `) expect(document.getElementById('exposed')).toHaveTextContent( JSON.stringify({ selectedIndex: 0 }) ) await click(getByText('Tab 2')) expect(document.getElementById('exposed')).toHaveTextContent( JSON.stringify({ selectedIndex: 1 }) ) }) it('should expose the `selectedIndex` on the `TabList` component', async () => { render(svelte` <TabGroup> <TabList let:selectedIndex> <pre id="exposed">{ JSON.stringify({ selectedIndex }) }</pre> <Tab>Tab 1</Tab> <Tab>Tab 2</Tab> <Tab>Tab 3</Tab> </TabList> <TabPanels> <TabPanel>Content 1</TabPanel> <TabPanel>Content 2</TabPanel> <TabPanel>Content 3</TabPanel> </TabPanels> </TabGroup> `) expect(document.getElementById('exposed')).toHaveTextContent( JSON.stringify({ selectedIndex: 0 }) ) await click(getByText('Tab 2')) expect(document.getElementById('exposed')).toHaveTextContent( JSON.stringify({ selectedIndex: 1 }) ) }) it('should expose the `selectedIndex` on the `TabPanels` component', async () => { render(svelte` <TabGroup> <TabList> <Tab>Tab 1</Tab> <Tab>Tab 2</Tab> <Tab>Tab 3</Tab> </TabList> <TabPanels let:selectedIndex> <pre id="exposed">{ JSON.stringify({ selectedIndex }) }</pre> <TabPanel>Content 1</TabPanel> <TabPanel>Content 2</TabPanel> <TabPanel>Content 3</TabPanel> </TabPanels> </TabGroup> `) expect(document.getElementById('exposed')).toHaveTextContent( JSON.stringify({ selectedIndex: 0 }) ) await click(getByText('Tab 2')) expect(document.getElementById('exposed')).toHaveTextContent( JSON.stringify({ selectedIndex: 1 }) ) }) it('should expose the `selected` state on the `Tab` components', async () => { render(svelte` <TabGroup> <TabList> <Tab let:selected> <pre data-tab={0}>{JSON.stringify({selected})}</pre> <span>Tab 1</span> </Tab> <Tab let:selected> <pre data-tab={1}>{JSON.stringify({selected})}</pre> <span>Tab 2</span> </Tab> <Tab let:selected> <pre data-tab={2}>{JSON.stringify({selected})}</pre> <span>Tab 3</span> </Tab> </TabList> <TabPanels> <TabPanel>Content 1</TabPanel> <TabPanel>Content 2</TabPanel> <TabPanel>Content 3</TabPanel> </TabPanels> </TabGroup> `) expect(document.querySelector('[data-tab="0"]')).toHaveTextContent( JSON.stringify({ selected: true }) ) expect(document.querySelector('[data-tab="1"]')).toHaveTextContent( JSON.stringify({ selected: false }) ) expect(document.querySelector('[data-tab="2"]')).toHaveTextContent( JSON.stringify({ selected: false }) ) await click(getTabs()[1]) expect(document.querySelector('[data-tab="0"]')).toHaveTextContent( JSON.stringify({ selected: false }) ) expect(document.querySelector('[data-tab="1"]')).toHaveTextContent( JSON.stringify({ selected: true }) ) expect(document.querySelector('[data-tab="2"]')).toHaveTextContent( JSON.stringify({ selected: false }) ) }) it('should expose the `selected` state on the `TabPanel` components', async () => { render(svelte` <TabGroup> <TabList> <Tab>Tab 1</Tab> <Tab>Tab 2</Tab> <Tab>Tab 3</Tab> </TabList> <TabPanels> <TabPanel unmount={false} let:selected> <pre data-panel={0}>{JSON.stringify({ selected })}</pre> <span> Content 1 </span> </TabPanel> <TabPanel unmount={false} let:selected> <pre data-panel={1}>{JSON.stringify({ selected })}</pre> <span> Content 2 </span> </TabPanel> <TabPanel unmount={false} let:selected> <pre data-panel={2}>{JSON.stringify({ selected })}</pre> <span> Content 3 </span> </TabPanel> </TabPanels> </TabGroup> `) expect(document.querySelector('[data-panel="0"]')).toHaveTextContent( JSON.stringify({ selected: true }) ) expect(document.querySelector('[data-panel="1"]')).toHaveTextContent( JSON.stringify({ selected: false }) ) expect(document.querySelector('[data-panel="2"]')).toHaveTextContent( JSON.stringify({ selected: false }) ) await click(getByText('Tab 2')) expect(document.querySelector('[data-panel="0"]')).toHaveTextContent( JSON.stringify({ selected: false }) ) expect(document.querySelector('[data-panel="1"]')).toHaveTextContent( JSON.stringify({ selected: true }) ) expect(document.querySelector('[data-panel="2"]')).toHaveTextContent( JSON.stringify({ selected: false }) ) }) }) describe('`defaultIndex`', () => { it('should jump to the nearest tab when the defaultIndex is out of bounds (-2)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: -2 }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0 }) assertActiveElement(getByText('Tab 1')) }) it('should jump to the nearest tab when the defaultIndex is out of bounds (+5)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 5 }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 2 }) assertActiveElement(getByText('Tab 3')) }) it('should jump to the next available tab when the defaultIndex is a disabled tab', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 0 }, [ [TabList, {}, [ [Tab, { disabled: true }, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 1 }) assertActiveElement(getByText('Tab 2')) }) it('should jump to the next available tab when the defaultIndex is a disabled tab and wrap around', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 2 }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, { disabled: true }, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0 }) assertActiveElement(getByText('Tab 1')) }) }) describe(`'Tab'`, () => { describe('`type` attribute', () => { it('should set the `type` to "button" by default', async () => { render( TestRenderer, { allProps: [ [TabGroup, {}, [ [TabList, {}, [ [Tab, {}, "Trigger"], ]], ]], ] }) expect(getTabs()[0]).toHaveAttribute('type', 'button') }) it('should not set the `type` to "button" if it already contains a `type`', async () => { render( TestRenderer, { allProps: [ [TabGroup, {}, [ [TabList, {}, [ [Tab, { type: "submit" }, "Trigger"], ]], ]], ] }) expect(getTabs()[0]).toHaveAttribute('type', 'submit') }) it('should not set the type if the "as" prop is not a "button"', async () => { render( TestRenderer, { allProps: [ [TabGroup, {}, [ [TabList, {}, [ [Tab, { as: "div" }, "Trigger"], ]], ]], ] }) expect(getTabs()[0]).not.toHaveAttribute('type') }) }) it('should guarantee the tab order after a few unmounts', async () => { let showFirst = writable(false); render(svelte` <TabGroup> <TabList> {#if $showFirst} <Tab>Tab 1</Tab> {/if} <Tab>Tab 2</Tab> <Tab>Tab 3</Tab> </TabList> </TabGroup> `) let tabs = getTabs() expect(tabs).toHaveLength(2) // Make the first tab active await press(Keys.Tab) // Verify that the first tab is active assertTabs({ active: 0 }) // Now add a new tab dynamically await act(() => showFirst.set(true)); // New tab should be treated correctly tabs = getTabs() expect(tabs).toHaveLength(3) // Active tab should now be second assertTabs({ active: 1 }) // We should be able to go to the first tab await press(Keys.Home) assertTabs({ active: 0 }) // And the last one await press(Keys.End) assertTabs({ active: 2 }) }) }) }) describe('Keyboard interactions', () => { describe('`Tab` key', () => { it('should be possible to tab to the default initial first tab', async () => { render( TestRenderer, { allProps: [ [TabGroup, {}, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0 }) assertActiveElement(getByText('Tab 1')) await press(Keys.Tab) assertActiveElement(getByText('Content 1')) await press(Keys.Tab) assertActiveElement(getByText('after')) await press(shift(Keys.Tab)) assertActiveElement(getByText('Content 1')) await press(shift(Keys.Tab)) assertActiveElement(getByText('Tab 1')) }) it('should be possible to tab to the default index tab', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 1 }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 1 }) assertActiveElement(getByText('Tab 2')) await press(Keys.Tab) assertActiveElement(getByText('Content 2')) await press(Keys.Tab) assertActiveElement(getByText('after')) await press(shift(Keys.Tab)) assertActiveElement(getByText('Content 2')) await press(shift(Keys.Tab)) assertActiveElement(getByText('Tab 2')) }) }) describe('`ArrowRight` key', () => { it('should be possible to go to the next item (activation = `auto`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, {}, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0 }) await press(Keys.ArrowRight) assertTabs({ active: 1 }) await press(Keys.ArrowRight) assertTabs({ active: 2 }) }) it('should be possible to go to the next item (activation = `manual`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0 }) await press(Keys.ArrowRight) assertTabs({ active: 0 }) await press(Keys.Enter) assertTabs({ active: 1 }) await press(Keys.ArrowRight) assertTabs({ active: 1 }) await press(Keys.Enter) assertTabs({ active: 2 }) }) it('should wrap around at the end (activation = `auto`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, {}, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0 }) await press(Keys.ArrowRight) assertTabs({ active: 1 }) await press(Keys.ArrowRight) assertTabs({ active: 2 }) await press(Keys.ArrowRight) assertTabs({ active: 0 }) await press(Keys.ArrowRight) assertTabs({ active: 1 }) }) it('should wrap around at the end (activation = `manual`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0 }) await press(Keys.ArrowRight) assertTabs({ active: 0 }) await press(Keys.Enter) assertTabs({ active: 1 }) await press(Keys.ArrowRight) assertTabs({ active: 1 }) await press(Keys.Enter) assertTabs({ active: 2 }) await press(Keys.ArrowRight) assertTabs({ active: 2 }) await press(Keys.Enter) assertTabs({ active: 0 }) await press(Keys.ArrowRight) assertTabs({ active: 0 }) await press(Keys.Enter) assertTabs({ active: 1 }) }) it('should not be possible to go right when in vertical mode (activation = `auto`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { vertical: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.ArrowRight) // no-op assertTabs({ active: 0, orientation: 'vertical' }) }) it('should not be possible to go right when in vertical mode (activation = `manual`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { vertical: true, manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.ArrowRight) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.Enter) // no-op assertTabs({ active: 0, orientation: 'vertical' }) }) }) describe('`ArrowLeft` key', () => { it('should be possible to go to the previous item (activation = `auto`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 2 }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 2 }) await press(Keys.ArrowLeft) assertTabs({ active: 1 }) await press(Keys.ArrowLeft) assertTabs({ active: 0 }) }) it('should be possible to go to the previous item (activation = `manual`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 2, manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 2 }) await press(Keys.ArrowLeft) assertTabs({ active: 2 }) await press(Keys.Enter) assertTabs({ active: 1 }) await press(Keys.ArrowLeft) assertTabs({ active: 1 }) await press(Keys.Enter) assertTabs({ active: 0 }) }) it('should wrap around at the beginning (activation = `auto`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 2 }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 2 }) await press(Keys.ArrowLeft) assertTabs({ active: 1 }) await press(Keys.ArrowLeft) assertTabs({ active: 0 }) await press(Keys.ArrowLeft) assertTabs({ active: 2 }) await press(Keys.ArrowLeft) assertTabs({ active: 1 }) }) it('should wrap around at the beginning (activation = `manual`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 2, manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 2 }) await press(Keys.ArrowLeft) assertTabs({ active: 2 }) await press(Keys.Enter) assertTabs({ active: 1 }) await press(Keys.ArrowLeft) assertTabs({ active: 1 }) await press(Keys.Enter) assertTabs({ active: 0 }) await press(Keys.ArrowLeft) assertTabs({ active: 0 }) await press(Keys.Enter) assertTabs({ active: 2 }) await press(Keys.ArrowLeft) assertTabs({ active: 2 }) await press(Keys.Enter) assertTabs({ active: 1 }) }) it('should not be possible to go left when in vertical mode (activation = `auto`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { vertical: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.ArrowLeft) // no-op assertTabs({ active: 0, orientation: 'vertical' }) }) it('should not be possible to go left when in vertical mode (activation = `manual`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { vertical: true, manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.ArrowLeft) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.Enter) // no-op assertTabs({ active: 0, orientation: 'vertical' }) }) }) describe('`ArrowDown` key', () => { it('should be possible to go to the next item (activation = `auto`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { vertical: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.ArrowDown) assertTabs({ active: 1, orientation: 'vertical' }) await press(Keys.ArrowDown) assertTabs({ active: 2, orientation: 'vertical' }) }) it('should be possible to go to the next item (activation = `manual`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { vertical: true, manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.ArrowDown) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.Enter) assertTabs({ active: 1, orientation: 'vertical' }) await press(Keys.ArrowDown) assertTabs({ active: 1, orientation: 'vertical' }) await press(Keys.Enter) assertTabs({ active: 2, orientation: 'vertical' }) }) it('should wrap around at the end (activation = `auto`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { vertical: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.ArrowDown) assertTabs({ active: 1, orientation: 'vertical' }) await press(Keys.ArrowDown) assertTabs({ active: 2, orientation: 'vertical' }) await press(Keys.ArrowDown) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.ArrowDown) assertTabs({ active: 1, orientation: 'vertical' }) }) it('should wrap around at the end (activation = `manual`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { vertical: true, manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.ArrowDown) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.Enter) assertTabs({ active: 1, orientation: 'vertical' }) await press(Keys.ArrowDown) assertTabs({ active: 1, orientation: 'vertical' }) await press(Keys.Enter) assertTabs({ active: 2, orientation: 'vertical' }) await press(Keys.ArrowDown) assertTabs({ active: 2, orientation: 'vertical' }) await press(Keys.Enter) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.ArrowDown) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.Enter) assertTabs({ active: 1, orientation: 'vertical' }) }) it('should not be possible to go down when in horizontal mode (activation = `auto`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, {}, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0 }) await press(Keys.ArrowDown) // no-op assertTabs({ active: 0 }) }) it('should not be possible to go down when in horizontal mode (activation = `manual`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0 }) await press(Keys.ArrowDown) assertTabs({ active: 0 }) await press(Keys.Enter) // no-op assertTabs({ active: 0 }) }) }) describe('`ArrowUp` key', () => { it('should be possible to go to the previous item (activation = `auto`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 2, vertical: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 2, orientation: 'vertical' }) await press(Keys.ArrowUp) assertTabs({ active: 1, orientation: 'vertical' }) await press(Keys.ArrowUp) assertTabs({ active: 0, orientation: 'vertical' }) }) it('should be possible to go to the previous item (activation = `manual`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 2, vertical: true, manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 2, orientation: 'vertical' }) await press(Keys.ArrowUp) assertTabs({ active: 2, orientation: 'vertical' }) await press(Keys.Enter) assertTabs({ active: 1, orientation: 'vertical' }) await press(Keys.ArrowUp) assertTabs({ active: 1, orientation: 'vertical' }) await press(Keys.Enter) assertTabs({ active: 0, orientation: 'vertical' }) }) it('should wrap around at the beginning (activation = `auto`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 2, vertical: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 2, orientation: 'vertical' }) await press(Keys.ArrowUp) assertTabs({ active: 1, orientation: 'vertical' }) await press(Keys.ArrowUp) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.ArrowUp) assertTabs({ active: 2, orientation: 'vertical' }) await press(Keys.ArrowUp) assertTabs({ active: 1, orientation: 'vertical' }) }) it('should wrap around at the beginning (activation = `manual`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 2, vertical: true, manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 2, orientation: 'vertical' }) await press(Keys.ArrowUp) assertTabs({ active: 2, orientation: 'vertical' }) await press(Keys.Enter) assertTabs({ active: 1, orientation: 'vertical' }) await press(Keys.ArrowUp) assertTabs({ active: 1, orientation: 'vertical' }) await press(Keys.Enter) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.ArrowUp) assertTabs({ active: 0, orientation: 'vertical' }) await press(Keys.Enter) assertTabs({ active: 2, orientation: 'vertical' }) await press(Keys.ArrowUp) assertTabs({ active: 2, orientation: 'vertical' }) await press(Keys.Enter) assertTabs({ active: 1, orientation: 'vertical' }) }) it('should not be possible to go left when in vertical mode (activation = `auto`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, {}, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0 }) await press(Keys.ArrowUp) // no-op assertTabs({ active: 0 }) }) it('should not be possible to go left when in vertical mode (activation = `manual`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 0 }) await press(Keys.ArrowUp) assertTabs({ active: 0 }) await press(Keys.Enter) // no-op assertTabs({ active: 0 }) }) }) describe('`Home` key', () => { it('should be possible to go to the first focusable item (activation = `auto`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 1 }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 1 }) await press(Keys.Home) assertTabs({ active: 0 }) }) it('should be possible to go to the first focusable item (activation = `manual`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 1, manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 1 }) await press(Keys.Home) assertTabs({ active: 1 }) await press(Keys.Enter) assertTabs({ active: 0 }) }) }) describe('`PageUp` key', () => { it('should be possible to go to the first focusable item (activation = `auto`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 1 }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 1 }) await press(Keys.PageUp) assertTabs({ active: 0 }) }) it('should be possible to go to the first focusable item (activation = `manual`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 1, manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 1 }) await press(Keys.PageUp) assertTabs({ active: 1 }) await press(Keys.Enter) assertTabs({ active: 0 }) }) }) describe('`End` key', () => { it('should be possible to go to the first focusable item (activation = `auto`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 1 }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 1 }) await press(Keys.End) assertTabs({ active: 2 }) }) it('should be possible to go to the first focusable item (activation = `manual`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 1, manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 1 }) await press(Keys.End) assertTabs({ active: 1 }) await press(Keys.Enter) assertTabs({ active: 2 }) }) }) describe('`PageDown` key', () => { it('should be possible to go to the first focusable item (activation = `auto`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 1 }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 1 }) await press(Keys.PageDown) assertTabs({ active: 2 }) }) it('should be possible to go to the first focusable item (activation = `manual`)', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 1, manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 1 }) await press(Keys.PageDown) assertTabs({ active: 1 }) await press(Keys.Enter) assertTabs({ active: 2 }) }) }) describe('`Enter` key', () => { it('should be possible to activate the focused tab', async () => { render( TestRenderer, { allProps: [ [TabGroup, { manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) getByText('Tab 3')?.focus() assertActiveElement(getByText('Tab 3')) assertTabs({ active: 0 }) await press(Keys.Enter) assertTabs({ active: 2 }) }) }) describe('`Space` key', () => { it('should be possible to activate the focused tab', async () => { render( TestRenderer, { allProps: [ [TabGroup, { manual: true }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) getByText('Tab 3')?.focus() assertActiveElement(getByText('Tab 3')) assertTabs({ active: 0 }) await press(Keys.Space) assertTabs({ active: 2 }) }) }) }) describe('Mouse interactions', () => { it('should be possible to click on a tab to focus it', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 1 }, [ [TabList, {}, [ [Tab, {}, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 1 }) await click(getByText('Tab 1')) assertTabs({ active: 0 }) await click(getByText('Tab 3')) assertTabs({ active: 2 }) await click(getByText('Tab 2')) assertTabs({ active: 1 }) }) it('should be a no-op when clicking on a disabled tab', async () => { render( TestRenderer, { allProps: [ [TabGroup, { defaultIndex: 1 }, [ [TabList, {}, [ [Tab, { disabled: true }, "Tab 1"], [Tab, {}, "Tab 2"], [Tab, {}, "Tab 3"], ]], [TabPanels, {}, [ [TabPanel, {}, "Content 1"], [TabPanel, {}, "Content 2"], [TabPanel, {}, "Content 3"], ]], ]], [Button, {}, "after"], ] }) assertActiveElement(document.body) await press(Keys.Tab) assertTabs({ active: 1 }) await click(getByText('Tab 1')) // No-op, Tab 2 is still active assertTabs({ active: 1 }) }) }) it('should trigger the `on:change` when the tab changes', async () => { let changes = jest.fn() render(svelte` <TabGroup on:change={(e) => changes(e.detail)}> <TabList> <Tab>Tab 1</Tab> <Tab>Tab 2</Tab> <Tab>Tab 3</Tab> </TabList> <TabPanels> <TabPanel>Content 1</TabPanel> <TabPanel>Content 2</TabPanel> <TabPanel>Content 3</TabPanel> </TabPanels> </TabGroup> <Button>After</Button> `); await click(getByText('Tab 2')) await click(getByText('Tab 3')) await click(getByText('Tab 2')) await click(getByText('Tab 1')) expect(changes).toHaveBeenCalledTimes(4) expect(changes).toHaveBeenNthCalledWith(1, 1) expect(changes).toHaveBeenNthCalledWith(2, 2) expect(changes).toHaveBeenNthCalledWith(3, 1) expect(changes).toHaveBeenNthCalledWith(4, 0) })
the_stack
import {AfterViewInit, Component, ViewEncapsulation, NgZone} from "@angular/core"; import {HttpClient} from "@angular/common/http"; import {take} from 'rxjs/operators'; import {ChartIconFactory, ChartType, JigsawTheme, SimpleTreeData} from "jigsaw/public_api"; @Component({ templateUrl: './demo.component.html', styleUrls: ['./demo.component.css'], encapsulation: ViewEncapsulation.None }) export class FishBoneFullComponent implements AfterViewInit { constructor(public http: HttpClient, public _zone: NgZone) { this.data = new SimpleTreeData(); this.data.label = '<span class="orange">目标标题</span>'; this.data.fromObject([ { label: '<span class="orange"><span class="iconfont iconfont-e221"></span>父节点1</span>', nodes: [ { label: '<span class="iconfont iconfont-e67a"></span>父节点11', nodes: [ { label: '子节点111', nodes: [ { label: '子节点1111', nodes: [ { label: "子节点11111", nodes: [ { label: '<span class="line">5,3,9,6,5,9,7,3,5,2</span>' } ] }, { label: 'end' } ] } ] }, { label: '子节点112', nodes: [ { label: '<span class="bar-colours-1">5,3,9,6,5,9,7,3,5,2</span>' } ] } ] }, { label: '父节点12' } ] }, { label: '<span class="orange"><span class="iconfont iconfont-e1ee"></span>父节点2</span>', nodes: [ { label: '<span class="iconfont iconfont-e67a"></span>父节点21', nodes: [ { label: '子节点211', nodes: [ { label: '<span class="iconfont iconfont-e547"></span>end' }, { label: '<span class="line">5,3,9,6,5,9,7,3,5,2</span>' }, { label: ` <div class="jigsaw-table-host" style="width: 300px;${JigsawTheme.majorStyle == 'dark' ? 'background: #0f111a' : ''}"> <table> <thead><tr><td>ID</td><td>name</td><td>gender</td><td>city</td></tr></thead> <tbody> <tr><td>1</td><td><a onclick="hello('tom')">tom</a></td><td>male</td><td>nj</td></tr> <tr><td>2</td><td><a onclick="hello('jerry')">jerry</a></td><td>male</td><td>shz</td></tr> <tr><td>3</td><td><a onclick="hello('marry')">marry</a></td><td>female</td><td>sh</td></tr> </tbody> </table> </div> `, // 这里需要特别注意,由于我们给了一段html片段并且包含了回调函数`hello()`, // 因此这里必须设置 `innerHtmlContext` 属性作为`hello()`函数的上下文 // 如果html片段中不包含回调函数,则无需设置 `innerHtmlContext` 属性 innerHtmlContext: this } ] }, { label: '子节点212' } ] }, { label: '父节点22', nodes: [ { label: '子节点221' } ] } ] }, { label: '<span class="orange"><span class="iconfont iconfont-e67a"></span>父节点3</span>', nodes: [ { label: '父节点31', nodes: [ { label: '<span class="iconfont iconfont-e547"></span>end' } ] } ] }, { label: '<span class="orange">父节点4</span>', nodes: [ { label: '<span class="bar-colours-1">5,3,9,6,5,9,7,3,5,2</span>' }, { label: 'end' } ] }, { label: '<span class="orange">父节点5</span>', nodes: [ { label: '<span class="pie-colours-2">5,3,9,6,5</span>' } ] } ]); this.data2 = new SimpleTreeData(); this.data2.label = '<span class="orange">申论万能思维体系</span>'; this.data2.fromObject([ { label: '<span class="orange">实务维度</span>', nodes: [ { label: '主体', nodes: [ { label: '构成', nodes: [ { label: '政府', }, { label: '企业', }, { label: '民众', } ] }, { label: '方面', nodes: [ { label: '利益', nodes: [ { label: '经济利益-钱' }, { label: '政治利益-权利和权力' }, { label: '文化利益-精神需求' }, { label: '民生利益-生活需求' }, { label: '生态利益' } ] }, { label: '思想', nodes: [ { label: '理念' }, { label: '意识' }, { label: '常识、知识' } ] }, { label: '素质', nodes: [ { label: '业务素质' }, { label: '思想道德素质' }, { label: '心理素质' }, { label: '身体素质' } ] } ] } ] }, ] }, { label: '<span class="orange">时间维度</span>', nodes: [ { label: '微观:事前、事中、事后' }, { label: '宏观', nodes: [ { label: '过去、历史、传统' }, { label: '现在、现状、现代' }, { label: '未来、将来' }, ] } ] }, { label: '<span class="orange">空间维度</span>', nodes: [ { label: '物理空间', nodes: [ { label: '本地、本国、民族' }, { label: '外地、外国、世界' } ] }, { label: '思维空间', nodes: [ { label: '内因' }, { label: '外因' } ] }, ] }, { label: '<span class="orange">价值维度</span>', nodes: [ { label: '利、积极、成绩、意义、经验' }, { label: '弊、消极、问题、危害、教训' } ] } ]); // 在ChartIcon注册Custom Pie ChartIconFactory.registerCustomPie(); this.data3 = new SimpleTreeData(); this.data3.http = http; this.data3.fromAjax('mock-data/fish-bone-1'); this.data3.onAjaxComplete(() => { this.data3.label = `<span class="orange">VoLTE呼损分析</span>`; this.data3.nodes.forEach((node, index) => { node.label = `<span class="orange">${node.name}</span>`; let pieData = this.getPieData(node).join(","); let nodesItem = new SimpleTreeData(); nodesItem.label = `<span class="pie-call-loss-${index}">${pieData}</span>`; nodesItem.desc = `<p class="call-loss-data"> count: ${node.count} <br> ratio: ${node.ratio} <br> delay: ${node.delay}</p>`; node.nodes = [nodesItem]; }); // 等待TreeData里的html字符串在鱼骨图中渲染,此处的异步必须使用zone.onStable this._zone.onStable.asObservable().pipe(take(1)).subscribe(() => { this._zone.run(() => { this.data3.nodes.forEach((node, index) => { const legendData = this.getLegendData(node); const pieData = this.getPieData(node); this.drawPie(index, legendData, this.getPieTitle(pieData, legendData), node); }); }) }); }) } data: SimpleTreeData; data2: SimpleTreeData; data3: SimpleTreeData; sceneData = [ {id: 1, label: "场景一",}, {id: 2, label: "场景二",} ]; selectedScene = this.sceneData[0]; hello(toWhom) { alert('hello ' + toWhom); } changeData(scene) { if (scene.id == 1) { this.data3.fromAjax('mock-data/fish-bone-1'); } else if (scene.id = 2) { this.data3.fromAjax('mock-data/fish-bone-2'); } } getPieData(node) { let pieData = []; if (node && node.pie) { if (node.pie.data instanceof Array) { pieData = node.pie.data.reduce((arr, item) => { arr.push(item[item.length - 1]); return arr; }, []); } if (node.pie.other) { pieData.push(node.pie.other.value); } } return pieData; } getPieTitle(pieData, legendData) { pieData = pieData.map(item => parseInt(item)); const pieDataTotal = pieData.reduce((total, item) => { return total + item; }, 0); return legendData.reduce((pieLabel, item, index) => { pieLabel.push(`${item}: ${pieData[index]}(${(pieData[index] / pieDataTotal * 100).toFixed(2)}%)`); return pieLabel; }, []); } getLegendData(node) { let legendData = []; if (node && node.pie) { if (node.pie.data instanceof Array) { legendData = node.pie.data.reduce((arr, item) => { arr.push(item[0] + item[1]); return arr; }, []); } if (node.pie.other) { legendData.push(node.pie.other.name); } } return legendData; } drawPie(index, legendData, pieTitle, node) { ChartIconFactory.create(".pie-call-loss-" + index, ChartType.customPie, { fill: function (_, i, all) { let g = Math.round((i / all.length) * 255); return "rgb(100, " + g + ", 222)" }, radius: 60, legend: { orient: 'right', // 如果是'top',图例的高度是自动算出来的,所以height属性不需要配置 width: 125, data: legendData, marginLeft: 5 }, series: node, link: this.handleLink, title: pieTitle, context: this, after: () => { console.log('a pie has been draw') }, }); } ngAfterViewInit() { ChartIconFactory.create(".bar-colours-1", ChartType.bar, { fill: ["red", "green", "blue"], height: 50, width: 100 }); ChartIconFactory.create(".pie-colours-2", ChartType.pie, { fill: function (_, i, all) { let g = (i / all.length) * 255; return "rgb(255, " + g + ", 0)" }, radius: 48, }); ChartIconFactory.create(".line", ChartType.line, { height: 80, width: 100 }); } handleLink(data, index) { console.log(this); console.log(index, data); } // ==================================================================== // ignore the following lines, they are not important to this demo // ==================================================================== summary: string = 'FishBone的使用说明'; description: string = require('!!raw-loader!./readme.md').default; }
the_stack