<commit_before>const getSessionKey = entityId => `session_${entityId}`;
const getCampaignDataKey = entityId => `campaignData_${entityId}`;
const getEntityIdFromSession = session => session.replace('session_', '');
let serviceUrl = 'https://machete-app.com';

function checkEntityId(entityId, sendResponse) {
    const valid = entityId && entityId != 'undefined' && entityId != 'null';
    if (valid)
        return valid;
    if (sendResponse)
        sendResponse({error: 'invalid entityId: ' + entityId});
    return false;
}

chrome.runtime.onInstalled.addListener(details => {
    if (details.reason == 'install') {
        chrome.tabs.create({ url: chrome.runtime.getURL('common/welcome.html') });
    }
    else if (details.reason == 'update') {
        // chrome.tabs.create({ url: chrome.runtime.getURL('common/changelog.html') });
    }
});

chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
    if (req.action == 'setSession')
        setSession(req, sendResponse);
    else if (req.action == 'getUser')
        getUser(sendResponse);
    else if (req.action == 'getAllowedCampaigns')
        getAllowedCampaigns(req.entityId, sendResponse);
    else if (req.action == 'requestData')
        requestCampaignData(req.entityId, sendResponse);
    else if (req.action == 'getDataHistory')
        getDataHistory(req.entityId, req.campaignId, sendResponse);
    else if (req.action == 'requestKeywordData')
        requestKeywordData(req.entityId, req.adGroupId, sendResponse);
    else if (req.action == 'getKeywordData')
        getKeywordData(req.entityId, req.adGroupId, sendResponse);
    else if (req.action == 'setCampaignMetadata')
        setCampaignMetadata(req.entityId, req.campaignId, req.asin, sendResponse);
    else if (req.action == 'setAdGroupMetadata')
        setAdGroupMetadata(req.entityId, req.adGroupId, req.campaignId, sendResponse);
    else
        sendResponse({error: 'unknown action'});
    return true;
});

chrome.alarms.onAlarm.addListener((session) => {
    let entityId = getEntityIdFromSession(session.name);
    if (!checkEntityId(entityId)) {
        chrome.alarms.clear(session.name, cleared => console.log("cleared useless alarm", cleared));
        return;
    }

    requestCampaignData(entityId, (response) => {
        response.error ? merror("requestCampaignData", response.error)
                       : console.log('request data success');
    });
});

function setSession(req, sendResponse) {
    let sessionKey = getSessionKey(req.entityId);

    // Always request data on login, then set the alarm
    let lastCampaignData = localStorage.getItem(getCampaignDataKey(req.entityId));
    if (!lastCampaignData || Date.now() - lastCampaignData >= span.hour) {
        requestCampaignData(req.entityId, (response) => {
            response.error ? merror("requestCampaignData", response.error)
                           : console.log('requestCampaignData success');
        });
    }
    chrome.alarms.get(sessionKey, (alarm) => {
        if (!alarm) {
            chrome.alarms.create(sessionKey, {
                when: Date.now() + 500,
                periodInMinutes: 60,
            });
            console.log('set alarm for', sessionKey);
        }
    });
    sendResponse({data: 'ok'});
}

function getUser(sendResponse) {
    return $.ajax({
        url: `${serviceUrl}/api/user`,
        method: 'GET',
        dataType: 'json',
        success: (data) => sendResponse({data}),
        error: (xhr, status, error) => sendResponse({status: xhr.status, error}),
    });
}

function getAllowedCampaigns(entityId, sendResponse) {
    if (!checkEntityId(entityId, sendResponse))
        return Promise.resolve([]);
    return $.ajax({
        url: `${serviceUrl}/api/data/${entityId}/allowed`,
        method: 'GET',
        dataType: 'json',
        success: (data) => sendResponse({data}),
        error: (xhr, status, error) => sendResponse({status: xhr.status, error}),
    });
}

function requestCampaignData(entityId, sendResponse) {
    if (!checkEntityId(entityId, sendResponse))
        return;
    let timestamp = Date.now();
    console.log('requesting campaign data for', entityId);
    $.ajax('https://ams.amazon.com/api/rta/campaigns', {
        method: 'GET',
        data: {
            entityId,
            /* TODO: use these once Amazon actually supports them
            status: null,
            startDate: null,
            endDate: null,
            */
        },
        dataType: 'json',
        success: (data) => {
            if (data && data.aaData && data.aaData.length) {
                let campaignIds = data.aaData.map(x => x.campaignId);
                requestCampaignStatus(entityId, campaignIds, timestamp);
            }
            storeDataCloud(entityId, timestamp, data)
                .then(() => sendResponse({data}))
                .fail((error) => sendResponse({error}));
        },
        error: (xhr, status, error) => {
            if (xhr.status == 401) { // Unauthorized
                notifyNeedCredentials(entityId);
                return;
            }
            sendResponse({status: xhr.status, error});
        },
    });

    localStorage.setItem(getCampaignDataKey(entityId), timestamp);
}

function requestCampaignStatus(entityId, campaignIds, timestamp) {
    $.ajax('https://ams.amazon.com/api/rta/campaign-status', {
        method: 'GET',
        data: {
            entityId,
            campaignIds: campaignIds.join(','),
        },
        dataType: 'json',
        success: (data) => {
            storeStatusCloud(entityId, timestamp, data)
                .then(() => console.log('stored campaign status data successfully'))
                .fail((error) => merror('requestCampaignStatus error', error));
        },
        error: (xhr, textStatus, error) => {
            console.log('error storing campaign status', error);
        },
    });
}

function requestKeywordData(entityId, adGroupId, sendResponse) {
    if (!checkEntityId(entityId, sendResponse))
        return;
    let timestamp = Date.now();
    console.log('requesting keyword data for', entityId, adGroupId);
    $.ajax('https://ams.amazon.com/api/sponsored-products/getAdGroupKeywordList', {
        method: 'POST',
        data: {
            entityId, adGroupId,
            /* TODO: use these once Amazon actually supports them
            status: null,
            startDate: null,
            endDate: null,
            */
        },
        dataType: 'json',
        success: (data) => {
            if (data.message) {
                sendResponse({status: 200, error: data.message});
            }
            else {
                storeKeywordDataCloud(entityId, adGroupId, timestamp, data)
                    .then(() => sendResponse({data}))
                    .fail((error) => sendResponse({error}));
            }
        },
        error: (xhr, status, error) => sendResponse({status: xhr.status, error}),
    });
}

function storeDataCloud(entityId, timestamp, data) {
    return $.ajax({
        url: `${serviceUrl}/api/data/${entityId}?timestamp=${timestamp}`,
        method: 'PUT',
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: (data, status) => console.log('cloud storage', status),
        error: (xhr, status, error) => merror('storeDataCloud', status, error),
    });
}

function storeStatusCloud(entityId, timestamp, data) {
    return $.ajax({
        url: `${serviceUrl}/api/campaignStatus/${entityId}?timestamp=${timestamp}`,
        method: 'PUT',
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: (data, status) => console.log('status storage', status),
        error: (xhr, status, error) => merror('storeStatusCloud', status, error),
    });
}

function storeKeywordDataCloud(entityId, adGroupId, timestamp, data) {
    return $.ajax({
        url: `${serviceUrl}/api/keywordData/${entityId}/${adGroupId}?timestamp=${timestamp}`,
        method: 'PUT',
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: (data, status) => console.log('keyword storage', status),
        error: (xhr, status, error) => merror('storeKeywordDataCloud', status, error),
    });
}

function getDataHistory(entityId, campaignId, sendResponse) { // TODO: date ranges, etc.
    if (!checkEntityId(entityId, sendResponse))
        return;
    $.ajax({
        url: `${serviceUrl}/api/data/${entityId}/${campaignId}`,
        method: 'GET',
        dataType: 'json',
        success: (data) => {
            sendResponse({data});
        },
        error: (xhr, status, error) => {
            sendResponse({status: xhr.status, error});
        },
    });
}

function getKeywordData(entityId, adGroupId, sendResponse) {
    if (!checkEntityId(entityId, sendResponse))
        return;
    $.ajax({
        url: `${serviceUrl}/api/keywordData/${entityId}/${adGroupId}`,
        method: 'GET',
        dataType: 'json',
        success: (data) => {
            sendResponse({data});
        },
        error: (xhr, status, error) => {
            sendResponse({status: xhr.status, error});
        },
    });
}

function setCampaignMetadata(entityId, campaignId, asin, sendResponse) {
    if (!checkEntityId(entityId, sendResponse))
        return;
    let data = {asin};
    $.ajax({
        url: `${serviceUrl}/api/campaignMetadata/${entityId}/${campaignId}`,
        method: 'PUT',
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: (data) => sendResponse({data}),
        error: (xhr, status, error) => sendResponse({status: xhr.status, error}),
    });
}

function setAdGroupMetadata(entityId, adGroupId, campaignId, sendResponse) {
    if (!checkEntityId(entityId, sendResponse))
        return;
    let data = {campaignId};
    $.ajax({
        url: `${serviceUrl}/api/adGroupMetadata/${entityId}/${adGroupId}`,
        method: 'PUT',
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: (data) => sendResponse({data}),
        error: (xhr, status, error) => sendResponse({status: xhr.status, error}),
    });
}

let notificationExists = false;
function notifyNeedCredentials(entityId) {
    if (!notificationExists) {
        let notificationId = `${prefix}-${entityId}-need-credentials`;
        chrome.notifications.create(notificationId, {
            type: "basic",
            iconUrl: "images/machete-128.png",
            title: "Sign in to AMS",
            message: "Machete needs you to sign in to AMS so it can keep your campaign history up-to-date.",
            contextMessage: "Click to sign in at https://ams.amazon.com/",
            isClickable: true,
            requireInteraction: true,
        });

        notificationExists = true;
        mga('event', 'credential-popup', 'show');
        chrome.notifications.onClicked.addListener((clickId) => {
            if (clickId == notificationId) {
                mga('event', 'credential-popup', 'click');
                chrome.tabs.create({ url: "https://ams.amazon.com/ads/dashboard" });
                chrome.notifications.clear(notificationId);
                notificationExists = false;
            }
        });
        chrome.notifications.onClosed.addListener(() => {
            notificationExists = false;
            mga('event', 'credential-popup', 'dismiss');
        });
    }
}
<commit_msg>added a programmatic check to only show the changelog after significant changes<commit_after>const getSessionKey = entityId => `session_${entityId}`;
const getCampaignDataKey = entityId => `campaignData_${entityId}`;
const getEntityIdFromSession = session => session.replace('session_', '');
let serviceUrl = 'https://machete-app.com';

function checkEntityId(entityId, sendResponse) {
    const valid = entityId && entityId != 'undefined' && entityId != 'null';
    if (valid)
        return valid;
    if (sendResponse)
        sendResponse({error: 'invalid entityId: ' + entityId});
    return false;
}

chrome.runtime.onInstalled.addListener(details => {
    const manifest = chrome.runtime.getManifest();
    if (details.reason == 'install') {
        chrome.tabs.create({ url: chrome.runtime.getURL('common/welcome.html') });
    }
    else if (details.reason == 'update') {
        const lastVersion = localStorage.getItem('lastVersion');
        const currentVersion = manifest.version;

        // the following comparison implicitly ignores the C in A.B.C, due to
        // the way that parseFloat works
        if (!lastVersion || parseFloat(currentVersion) > parseFloat(lastVersion)) {
            chrome.tabs.create({ url: chrome.runtime.getURL('common/changelog.html') });
        }
    }
    localStorage.setItem('lastVersion', manifest.version);
});

chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
    if (req.action == 'setSession')
        setSession(req, sendResponse);
    else if (req.action == 'getUser')
        getUser(sendResponse);
    else if (req.action == 'getAllowedCampaigns')
        getAllowedCampaigns(req.entityId, sendResponse);
    else if (req.action == 'requestData')
        requestCampaignData(req.entityId, sendResponse);
    else if (req.action == 'getDataHistory')
        getDataHistory(req.entityId, req.campaignId, sendResponse);
    else if (req.action == 'requestKeywordData')
        requestKeywordData(req.entityId, req.adGroupId, sendResponse);
    else if (req.action == 'getKeywordData')
        getKeywordData(req.entityId, req.adGroupId, sendResponse);
    else if (req.action == 'setCampaignMetadata')
        setCampaignMetadata(req.entityId, req.campaignId, req.asin, sendResponse);
    else if (req.action == 'setAdGroupMetadata')
        setAdGroupMetadata(req.entityId, req.adGroupId, req.campaignId, sendResponse);
    else
        sendResponse({error: 'unknown action'});
    return true;
});

chrome.alarms.onAlarm.addListener((session) => {
    let entityId = getEntityIdFromSession(session.name);
    if (!checkEntityId(entityId)) {
        chrome.alarms.clear(session.name, cleared => console.log("cleared useless alarm", cleared));
        return;
    }

    requestCampaignData(entityId, (response) => {
        response.error ? merror("requestCampaignData", response.error)
                       : console.log('request data success');
    });
});

function setSession(req, sendResponse) {
    let sessionKey = getSessionKey(req.entityId);

    // Always request data on login, then set the alarm
    let lastCampaignData = localStorage.getItem(getCampaignDataKey(req.entityId));
    if (!lastCampaignData || Date.now() - lastCampaignData >= span.hour) {
        requestCampaignData(req.entityId, (response) => {
            response.error ? merror("requestCampaignData", response.error)
                           : console.log('requestCampaignData success');
        });
    }
    chrome.alarms.get(sessionKey, (alarm) => {
        if (!alarm) {
            chrome.alarms.create(sessionKey, {
                when: Date.now() + 500,
                periodInMinutes: 60,
            });
            console.log('set alarm for', sessionKey);
        }
    });
    sendResponse({data: 'ok'});
}

function getUser(sendResponse) {
    return $.ajax({
        url: `${serviceUrl}/api/user`,
        method: 'GET',
        dataType: 'json',
        success: (data) => sendResponse({data}),
        error: (xhr, status, error) => sendResponse({status: xhr.status, error}),
    });
}

function getAllowedCampaigns(entityId, sendResponse) {
    if (!checkEntityId(entityId, sendResponse))
        return Promise.resolve([]);
    return $.ajax({
        url: `${serviceUrl}/api/data/${entityId}/allowed`,
        method: 'GET',
        dataType: 'json',
        success: (data) => sendResponse({data}),
        error: (xhr, status, error) => sendResponse({status: xhr.status, error}),
    });
}

function requestCampaignData(entityId, sendResponse) {
    if (!checkEntityId(entityId, sendResponse))
        return;
    let timestamp = Date.now();
    console.log('requesting campaign data for', entityId);
    $.ajax('https://ams.amazon.com/api/rta/campaigns', {
        method: 'GET',
        data: {
            entityId,
            /* TODO: use these once Amazon actually supports them
            status: null,
            startDate: null,
            endDate: null,
            */
        },
        dataType: 'json',
        success: (data) => {
            if (data && data.aaData && data.aaData.length) {
                let campaignIds = data.aaData.map(x => x.campaignId);
                requestCampaignStatus(entityId, campaignIds, timestamp);
            }
            storeDataCloud(entityId, timestamp, data)
                .then(() => sendResponse({data}))
                .fail((error) => sendResponse({error}));
        },
        error: (xhr, status, error) => {
            if (xhr.status == 401) { // Unauthorized
                notifyNeedCredentials(entityId);
                return;
            }
            sendResponse({status: xhr.status, error});
        },
    });

    localStorage.setItem(getCampaignDataKey(entityId), timestamp);
}

function requestCampaignStatus(entityId, campaignIds, timestamp) {
    $.ajax('https://ams.amazon.com/api/rta/campaign-status', {
        method: 'GET',
        data: {
            entityId,
            campaignIds: campaignIds.join(','),
        },
        dataType: 'json',
        success: (data) => {
            storeStatusCloud(entityId, timestamp, data)
                .then(() => console.log('stored campaign status data successfully'))
                .fail((error) => merror('requestCampaignStatus error', error));
        },
        error: (xhr, textStatus, error) => {
            console.log('error storing campaign status', error);
        },
    });
}

function requestKeywordData(entityId, adGroupId, sendResponse) {
    if (!checkEntityId(entityId, sendResponse))
        return;
    let timestamp = Date.now();
    console.log('requesting keyword data for', entityId, adGroupId);
    $.ajax('https://ams.amazon.com/api/sponsored-products/getAdGroupKeywordList', {
        method: 'POST',
        data: {
            entityId, adGroupId,
            /* TODO: use these once Amazon actually supports them
            status: null,
            startDate: null,
            endDate: null,
            */
        },
        dataType: 'json',
        success: (data) => {
            if (data.message) {
                sendResponse({status: 200, error: data.message});
            }
            else {
                storeKeywordDataCloud(entityId, adGroupId, timestamp, data)
                    .then(() => sendResponse({data}))
                    .fail((error) => sendResponse({error}));
            }
        },
        error: (xhr, status, error) => sendResponse({status: xhr.status, error}),
    });
}

function storeDataCloud(entityId, timestamp, data) {
    return $.ajax({
        url: `${serviceUrl}/api/data/${entityId}?timestamp=${timestamp}`,
        method: 'PUT',
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: (data, status) => console.log('cloud storage', status),
        error: (xhr, status, error) => merror('storeDataCloud', status, error),
    });
}

function storeStatusCloud(entityId, timestamp, data) {
    return $.ajax({
        url: `${serviceUrl}/api/campaignStatus/${entityId}?timestamp=${timestamp}`,
        method: 'PUT',
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: (data, status) => console.log('status storage', status),
        error: (xhr, status, error) => merror('storeStatusCloud', status, error),
    });
}

function storeKeywordDataCloud(entityId, adGroupId, timestamp, data) {
    return $.ajax({
        url: `${serviceUrl}/api/keywordData/${entityId}/${adGroupId}?timestamp=${timestamp}`,
        method: 'PUT',
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: (data, status) => console.log('keyword storage', status),
        error: (xhr, status, error) => merror('storeKeywordDataCloud', status, error),
    });
}

function getDataHistory(entityId, campaignId, sendResponse) { // TODO: date ranges, etc.
    if (!checkEntityId(entityId, sendResponse))
        return;
    $.ajax({
        url: `${serviceUrl}/api/data/${entityId}/${campaignId}`,
        method: 'GET',
        dataType: 'json',
        success: (data) => {
            sendResponse({data});
        },
        error: (xhr, status, error) => {
            sendResponse({status: xhr.status, error});
        },
    });
}

function getKeywordData(entityId, adGroupId, sendResponse) {
    if (!checkEntityId(entityId, sendResponse))
        return;
    $.ajax({
        url: `${serviceUrl}/api/keywordData/${entityId}/${adGroupId}`,
        method: 'GET',
        dataType: 'json',
        success: (data) => {
            sendResponse({data});
        },
        error: (xhr, status, error) => {
            sendResponse({status: xhr.status, error});
        },
    });
}

function setCampaignMetadata(entityId, campaignId, asin, sendResponse) {
    if (!checkEntityId(entityId, sendResponse))
        return;
    let data = {asin};
    $.ajax({
        url: `${serviceUrl}/api/campaignMetadata/${entityId}/${campaignId}`,
        method: 'PUT',
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: (data) => sendResponse({data}),
        error: (xhr, status, error) => sendResponse({status: xhr.status, error}),
    });
}

function setAdGroupMetadata(entityId, adGroupId, campaignId, sendResponse) {
    if (!checkEntityId(entityId, sendResponse))
        return;
    let data = {campaignId};
    $.ajax({
        url: `${serviceUrl}/api/adGroupMetadata/${entityId}/${adGroupId}`,
        method: 'PUT',
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: (data) => sendResponse({data}),
        error: (xhr, status, error) => sendResponse({status: xhr.status, error}),
    });
}

let notificationExists = false;
function notifyNeedCredentials(entityId) {
    if (!notificationExists) {
        let notificationId = `${prefix}-${entityId}-need-credentials`;
        chrome.notifications.create(notificationId, {
            type: "basic",
            iconUrl: "images/machete-128.png",
            title: "Sign in to AMS",
            message: "Machete needs you to sign in to AMS so it can keep your campaign history up-to-date.",
            contextMessage: "Click to sign in at https://ams.amazon.com/",
            isClickable: true,
            requireInteraction: true,
        });

        notificationExists = true;
        mga('event', 'credential-popup', 'show');
        chrome.notifications.onClicked.addListener((clickId) => {
            if (clickId == notificationId) {
                mga('event', 'credential-popup', 'click');
                chrome.tabs.create({ url: "https://ams.amazon.com/ads/dashboard" });
                chrome.notifications.clear(notificationId);
                notificationExists = false;
            }
        });
        chrome.notifications.onClosed.addListener(() => {
            notificationExists = false;
            mga('event', 'credential-popup', 'dismiss');
        });
    }
}
<|endoftext|>


<commit_before>'use strict';
const fs = require('fs');
const path = require('path');
const EventEmitter = require('events').EventEmitter;
const client = require('socket.io-client');
const { SERVER_MODE_TYPES } = require('../common/constants');
const { version: appVersion } = require('../../../package.json');
const rendererConsole = require('./utils/rendererConsole');

/**
 * 하드웨어 <-> 엔트리 워크스페이스 통신간 사용되는 클래스.
 * http[s] 서버와 socketIO 서버를 오픈한다.
 * 클라우드 모드에서 서버가 EADDRINUSE 로 실패한 경우, 클라이언트 모드로 동작한다.
 * 클라이언트 모드에서는 서버 PC 를 호스트로 엔트리와 통신한다.
 *
 * EventEmitter 는 외부로 아래와 같은 이벤트를 발생시킨다
 * - connection : 웹소켓 서버가 엔트리와 연결된 경우
 * - close : 소켓서버가 닫힘
 * - closed : 소켓, httpServer 전체가 닫힘
 * - data : 서버에서 받은 데이터. 인자는 data, type 를 발생시킨다.
 */
class Server extends EventEmitter {
    constructor(router) {
        super();
        this.router = router;
        this.packet = new Buffer([0x01, 0x00, 0x00, 0x00]);
        this.connections = [];
        this.connectionSet = {};
        this.roomCnt = 0;
        this.childServerList = {};
        this.clientTargetList = {};
        this.runningMode = SERVER_MODE_TYPES.parent;
        this.currentServerMode = SERVER_MODE_TYPES.single;
        this.masterRoomIds = [];
        this.clientRoomId = '';
        this.socketClient = undefined; // 클라이언트인 경우 세팅됨
        this.socketServer = undefined; // 호스트인 경우 세팅됨
    }

    addRoomIdsOnSecondInstance(roomId) {
        if (this.runningMode === SERVER_MODE_TYPES.parent) {
            if (this.masterRoomIds.indexOf(roomId) === -1) {
                this.masterRoomIds.push(roomId);
            }
        } else {
            if (roomId) {
                this.clientRoomId = roomId;
                this.socketClient && this.socketClient.emit('matchTarget', { roomId });
                if (this.masterRoomIds.indexOf(roomId) === -1) {
                    this.masterRoomIds.push(roomId);
                }
            }
        }
    }

    /**
     * 연결된 클라우드 PC 여부에 따라
     * single, multi 모드 전환한다.
     * 렌더러에 이미지를 표기하기 위해 사용된다.
     * currentServerMode 는 여기서 세팅만 되며,
     * 최초 구동시 메인 프로세스보다 느리게 세팅되는 렌더러 쪽에서 현재 서버모드를
     * 체크할때 가져간다.
     * @param mode
     */
    toggleServerMode(mode) {
        this.currentServerMode = mode;
        this.router.notifyServerMode(mode);
    }

    open() {
        const PORT = 23518;
        const { httpServer, address } = this._getHttpServer(PORT);

        /*
         * 에러가 발생하는 경우는 EADDRINUSE 로 상정한다.
         * 동일 IP + 클라우드 PC 환경이라고 가정하고,
         * 클라우드 내 최초 실행된 PC 가 서버, 그 뒤에 실행된 PC 에서는
         * EADDRINUSE 가 발생.
         * 그런 경우 직접 로컬호스트발 소켓 클라이언트를 연다.
         */
        httpServer.on('error', (e) => {
            this.runningMode = SERVER_MODE_TYPES.child;
            this.toggleServerMode(SERVER_MODE_TYPES.multi);

            const socket = this._createSocketClient(address);
            this.connections.push(socket);
            this.socketClient = socket;
        });

        /*
         * 서버가 정상오픈된 경우. 서버로 동작한다.
         * 일반 모드인 경우는 상관없다.
         * 클라우드 모드인 경우, 클라이언트들의 데이터까지 처리하는 부하문제가 있다.
         * 정상 오픈이 된 경우 socketIO 서버를 오픈한다.
         */
        httpServer.on('listening', (e) => {
            const mRoomIds = this.router.roomIds;
            if (mRoomIds.length > 0) {
                mRoomIds.forEach((mRoomId) => {
                    if (this.masterRoomIds.indexOf(mRoomId) === -1 && mRoomId) {
                        this.masterRoomIds.push(mRoomId);
                    }
                });
            }
            this.runningMode = SERVER_MODE_TYPES.parent;
            this.httpServer = httpServer;

            this.socketServer = this._createSocketServer(httpServer);
        });

        httpServer.listen(PORT);
    };

    /**
     * httpServer 오픈에 실패하여 (클라우드 등) 직접 socketIO 클라이언트를 만든다.
     * @param address
     * @return {SocketIOClientStatic.Socket}
     * @private
     */
    _createSocketClient(address) {
        const socket = client(address, {
            query: { childServer: true },
            reconnectionAttempts: 3,
        });

        socket.on('connect', () => {
            const roomIds = this.router.roomIds;
            if (roomIds.length > 0) {
                roomIds.forEach((roomId) => {
                    if (roomId) {
                        if (this.masterRoomIds.indexOf(roomId) === -1) {
                            this.masterRoomIds.push(roomId);
                        }
                        socket.emit('matchTarget', { roomId });
                    }
                });
            }
        });

        socket.on('message', this.router.handleServerData);

        socket.on('mode', (data) => {
            socket.mode = data;
        });

        socket.on('reconnect_failed', () => {
            socket.close();
            this.toggleServerMode(SERVER_MODE_TYPES.single);
            this.socketClient = null;
            this.open();
        });

        socket.on('disconnect', () => {
            socket.close();
            this.socketClient = null;
            this.open();
        });

        return socket;
    }

    /**
     * httpServer 오픈에 성공한 뒤, SocketIO 서버를 오픈한다.
     *
     * @param httpServer{Server}
     * @return {SocketIO.Server}
     * @private
     */
    _createSocketServer(httpServer) {
        const server = require('socket.io')(httpServer);
        server.set('transports', [
            'websocket',
            'flashsocket',
            'htmlfile',
            'xhr-polling',
            'jsonp-polling',
            'polling',
        ]);

        server.on('connection', (socket) => {
            const connection = socket;
            this.connectionSet[connection.id] = connection;
            this.connections.push(connection);
            this.emit('connection');

            rendererConsole.info('Entry connected.');

            const roomId = connection.handshake.query.roomId;
            if (connection.handshake.query.childServer === 'true') {
                this.childServerList[connection.id] = true;
            } else {
                connection.join(roomId);
                connection.roomId = roomId;
            }

            const childServerListCnt = Object.keys(this.childServerList).length;
            if (childServerListCnt > 0) {
                server.emit('mode', SERVER_MODE_TYPES.multi);
                this.toggleServerMode(SERVER_MODE_TYPES.multi);
            } else {
                server.emit('mode', SERVER_MODE_TYPES.single);
                this.toggleServerMode(SERVER_MODE_TYPES.single);
            }

            connection.on('matchTarget', (data) => {
                if (
                    connection.handshake.query.childServer === 'true' &&
                    data.roomId
                ) {
                    if (!connection.roomIds) {
                        connection.roomIds = [];
                    }

                    if (connection.roomIds.indexOf(data.roomId) === -1) {
                        connection.roomIds.push(data.roomId);
                    }

                    this.clientTargetList[data.roomId] = connection.id;
                    server.to(data.roomId).emit('matched', connection.id);
                }
            });

            connection.on('disconnect', (socket) => {
                if (connection.handshake && connection.handshake.query.childServer === 'true') {
                    if (connection.roomIds && connection.roomIds.length > 0) {
                        connection.roomIds.forEach((roomId) => {
                            server.to(roomId).emit('matching');
                        });
                    }
                    delete this.connectionSet[connection.id];
                    delete this.childServerList[connection.id];

                    const childServerListCnt = Object.keys(this.childServerList).length;
                    if (childServerListCnt <= 0) {
                        server.emit('mode', SERVER_MODE_TYPES.single);
                        this.toggleServerMode(SERVER_MODE_TYPES.single);
                    }
                } else {
                    delete this.connectionSet[connection.id];
                }
            });

            connection.on('message', (message, ack) => {
                console.log('socketServer receive : ', message);
                if (
                    message.mode === SERVER_MODE_TYPES.single ||
                    this.masterRoomIds.indexOf(connection.roomId) >= 0
                ) {
                    this.router.handleServerData(message);
                } else {
                    if (connection.handshake.query.childServer === 'true') {
                        if (
                            connection.roomIds &&
                            connection.roomIds.length > 0
                        ) {
                            connection.roomIds.forEach((roomId) => {
                                server.to(roomId).emit('message', message);
                            });
                        }
                    } else if (this.clientTargetList[connection.roomId]) {
                        server.to(this.clientTargetList[connection.roomId]).emit('message', message);
                    }
                }
                if (ack) {
                    const { key = true } = message;
                    ack(key);
                }
            });

            connection.on('close', (reasonCode, description) => {
                rendererConsole.warn('Entry disconnected.');
                this.emit('close');
                this.closeSingleConnection(this);
            });
            this.setState(this.state);
        });
        return server;
    }

    /**
     * SSL 인증서가 프로젝트에 포함되어있는 경우는 https,
     * 그렇지 않은 경우는 http 서버를 오픈한다.
     *
     * @param port{number} 오픈할 포트번호
     * @return {{address: string, httpServer: Server}}
     * @private
     */
    _getHttpServer(port) {
        let httpServer;
        let address;

        const rootDir = path.resolve(__dirname, '..', '..');
        if (fs.existsSync(path.resolve(rootDir, 'ssl', 'cert.pem'))) {
            httpServer = require('https').createServer(
                {
                    key: fs.readFileSync(path.resolve(rootDir, 'ssl', 'hardware.key')),
                    cert: fs.readFileSync(path.resolve(rootDir, 'ssl', 'cert.pem')),
                    ca: [
                        fs.readFileSync(path.resolve(rootDir, 'ssl', 'ChainCA1.crt')),
                        fs.readFileSync(path.resolve(rootDir, 'ssl', 'ChainCA2.crt')),
                        fs.readFileSync(path.resolve(rootDir, 'ssl', 'RootCA.crt')),
                    ],
                },
                (req, res) => {
                    res.writeHead(200);
                    res.end();
                }
            );
            address = `https://hardware.playentry.org:${port}`;
        } else {
            httpServer = require('http').createServer((request, response) => {
                response.writeHead(200);
                response.end();
            });
            address = `http://127.0.0.1:${port}`;
        }

        return {
            httpServer,
            address,
        };
    }

    closeSingleConnection(connection) {
        const connections = this.connections;
        const index = connections.indexOf(connection);
        if (index > -1) {
            this.connections.slice(index, 1);
            connection.close();
        }
    };

    send(data) {
        const childServerListCnt = Object.keys(this.childServerList).length;
        const payload = { data, version: appVersion };

        if (
            (this.runningMode === SERVER_MODE_TYPES.parent && childServerListCnt === 0) ||
            this.runningMode === SERVER_MODE_TYPES.child
        ) {
            if (this.connections.length !== 0) {
                this.connections.map((connection) => {
                    connection.emit('message', payload);
                });
            }
        } else if (this.masterRoomIds.length > 0) {
            this.masterRoomIds.forEach((masterRoomId) => {
                this.socketServer.to(masterRoomId).emit('message', payload);
            });
        }
    };

    setState(state) {
        this.state = state;
        if (this.connections.length) {
            const packet = this.packet;
            if (state === 'connecting') {
                packet[3] = 0x01;
                this.send(packet);
            } else if (state === 'connected') {
                packet[3] = 0x02;
                this.send(packet);
            } else if (state === 'lost') {
                packet[3] = 0x03;
                this.send(packet);
            } else if (state === 'disconnected') {
                packet[3] = 0x04;
                this.send(packet);
            }
        }
    };

    disconnectHardware() {
        this.send('disconnectHardware');
    };

    close() {
        if (this.socketServer) {
            this.socketServer.close();
            this.socketServer = undefined;
        }
        if (this.httpServer) {
            this.httpServer.close();
            this.httpServer = undefined;
        }
        this.connections = [];
        this.emit('closed');
    };
}

module.exports = Server;
<commit_msg>v1.7.5 태그 내 클라우드 PC 관련 핫픽스 적용<commit_after>'use strict';
const fs = require('fs');
const path = require('path');
const EventEmitter = require('events').EventEmitter;
const client = require('socket.io-client');
const { SERVER_MODE_TYPES } = require('../common/constants');
const { version: appVersion } = require('../../../package.json');
const rendererConsole = require('./utils/rendererConsole');

/**
 * 하드웨어 <-> 엔트리 워크스페이스 통신간 사용되는 클래스.
 * http[s] 서버와 socketIO 서버를 오픈한다.
 * 클라우드 모드에서 서버가 EADDRINUSE 로 실패한 경우, 클라이언트 모드로 동작한다.
 * 클라이언트 모드에서는 서버 PC 를 호스트로 엔트리와 통신한다.
 *
 * EventEmitter 는 외부로 아래와 같은 이벤트를 발생시킨다
 * - connection : 웹소켓 서버가 엔트리와 연결된 경우
 * - close : 소켓서버가 닫힘
 * - closed : 소켓, httpServer 전체가 닫힘
 * - data : 서버에서 받은 데이터. 인자는 data, type 를 발생시킨다.
 */
class Server extends EventEmitter {
    constructor(router) {
        super();
        this.router = router;
        this.packet = new Buffer([0x01, 0x00, 0x00, 0x00]);
        this.connections = [];
        this.connectionSet = {};
        this.roomCnt = 0;
        this.childServerList = {};
        this.clientTargetList = {};
        this.runningMode = SERVER_MODE_TYPES.parent;
        this.currentServerMode = SERVER_MODE_TYPES.single;
        this.masterRoomIds = [];
        this.clientRoomId = '';
        this.socketClient = undefined; // 클라이언트인 경우 세팅됨
        this.socketServer = undefined; // 호스트인 경우 세팅됨
    }

    addRoomIdsOnSecondInstance(roomId) {
        if (this.runningMode === SERVER_MODE_TYPES.parent) {
            if (this.masterRoomIds.indexOf(roomId) === -1) {
                this.masterRoomIds.push(roomId);
            }
        } else {
            if (roomId) {
                this.clientRoomId = roomId;
                this.socketClient && this.socketClient.emit('matchTarget', { roomId });
                if (this.masterRoomIds.indexOf(roomId) === -1) {
                    this.masterRoomIds.push(roomId);
                }
            }
        }
    }

    /**
     * 연결된 클라우드 PC 여부에 따라
     * single, multi 모드 전환한다.
     * 렌더러에 이미지를 표기하기 위해 사용된다.
     * currentServerMode 는 여기서 세팅만 되며,
     * 최초 구동시 메인 프로세스보다 느리게 세팅되는 렌더러 쪽에서 현재 서버모드를
     * 체크할때 가져간다.
     * @param mode
     */
    toggleServerMode(mode) {
        this.currentServerMode = mode;
        this.router.notifyServerMode(mode);
    }

    open() {
        const PORT = 23518;
        const { httpServer, address } = this._getHttpServer(PORT);

        /*
         * 에러가 발생하는 경우는 EADDRINUSE 로 상정한다.
         * 동일 IP + 클라우드 PC 환경이라고 가정하고,
         * 클라우드 내 최초 실행된 PC 가 서버, 그 뒤에 실행된 PC 에서는
         * EADDRINUSE 가 발생.
         * 그런 경우 직접 로컬호스트발 소켓 클라이언트를 연다.
         */
        httpServer.on('error', (e) => {
            this.runningMode = SERVER_MODE_TYPES.child;
            this.toggleServerMode(SERVER_MODE_TYPES.multi);

            const socket = this._createSocketClient(address);
            this.connections.push(socket);
            this.socketClient = socket;
        });

        /*
         * 서버가 정상오픈된 경우. 서버로 동작한다.
         * 일반 모드인 경우는 상관없다.
         * 클라우드 모드인 경우, 클라이언트들의 데이터까지 처리하는 부하문제가 있다.
         * 정상 오픈이 된 경우 socketIO 서버를 오픈한다.
         */
        httpServer.on('listening', (e) => {
            const mRoomIds = this.router.roomIds;
            if (mRoomIds.length > 0) {
                mRoomIds.forEach((mRoomId) => {
                    if (this.masterRoomIds.indexOf(mRoomId) === -1 && mRoomId) {
                        this.masterRoomIds.push(mRoomId);
                    }
                });
            }
            this.runningMode = SERVER_MODE_TYPES.parent;
            this.httpServer = httpServer;

            this.socketServer = this._createSocketServer(httpServer);
        });

        httpServer.listen(PORT);
    };

    /**
     * httpServer 오픈에 실패하여 (클라우드 등) 직접 socketIO 클라이언트를 만든다.
     * @param address
     * @return {SocketIOClientStatic.Socket}
     * @private
     */
    _createSocketClient(address) {
        const socket = client(address, {
            query: { childServer: true },
            reconnectionAttempts: 3,
        });

        socket.on('connect', () => {
            const roomIds = this.router.roomIds;
            if (roomIds.length > 0) {
                roomIds.forEach((roomId) => {
                    if (roomId) {
                        if (this.masterRoomIds.indexOf(roomId) === -1) {
                            this.masterRoomIds.push(roomId);
                        }
                        socket.emit('matchTarget', { roomId });
                    }
                });
            }
        });

        socket.on('message', (message) => {
            this.router.handleServerData(message);
        });

        socket.on('mode', (data) => {
            socket.mode = data;
        });

        socket.on('reconnect_failed', () => {
            socket.close();
            this.toggleServerMode(SERVER_MODE_TYPES.single);
            this.socketClient = null;
            this.open();
        });

        socket.on('disconnect', () => {
            socket.close();
            this.socketClient = null;
            this.open();
        });

        return socket;
    }

    /**
     * httpServer 오픈에 성공한 뒤, SocketIO 서버를 오픈한다.
     *
     * @param httpServer{Server}
     * @return {SocketIO.Server}
     * @private
     */
    _createSocketServer(httpServer) {
        const server = require('socket.io')(httpServer);
        server.set('transports', [
            'websocket',
            'flashsocket',
            'htmlfile',
            'xhr-polling',
            'jsonp-polling',
            'polling',
        ]);

        server.on('connection', (socket) => {
            const connection = socket;
            this.connectionSet[connection.id] = connection;
            this.connections.push(connection);
            this.emit('connection');

            rendererConsole.info('Entry connected.');

            const roomId = connection.handshake.query.roomId;
            if (connection.handshake.query.childServer === 'true') {
                this.childServerList[connection.id] = true;
            } else {
                connection.join(roomId);
                connection.roomId = roomId;
            }

            const childServerListCnt = Object.keys(this.childServerList).length;
            if (childServerListCnt > 0) {
                server.emit('mode', SERVER_MODE_TYPES.multi);
                this.toggleServerMode(SERVER_MODE_TYPES.multi);
            } else {
                server.emit('mode', SERVER_MODE_TYPES.single);
                this.toggleServerMode(SERVER_MODE_TYPES.single);
            }

            connection.on('matchTarget', (data) => {
                if (
                    connection.handshake.query.childServer === 'true' &&
                    data.roomId
                ) {
                    if (!connection.roomIds) {
                        connection.roomIds = [];
                    }

                    if (connection.roomIds.indexOf(data.roomId) === -1) {
                        connection.roomIds.push(data.roomId);
                    }

                    this.clientTargetList[data.roomId] = connection.id;
                    server.to(data.roomId).emit('matched', connection.id);
                }
            });

            connection.on('disconnect', (socket) => {
                if (connection.handshake && connection.handshake.query.childServer === 'true') {
                    if (connection.roomIds && connection.roomIds.length > 0) {
                        connection.roomIds.forEach((roomId) => {
                            server.to(roomId).emit('matching');
                        });
                    }
                    delete this.connectionSet[connection.id];
                    delete this.childServerList[connection.id];

                    const childServerListCnt = Object.keys(this.childServerList).length;
                    if (childServerListCnt <= 0) {
                        server.emit('mode', SERVER_MODE_TYPES.single);
                        this.toggleServerMode(SERVER_MODE_TYPES.single);
                    }
                } else {
                    delete this.connectionSet[connection.id];
                }
            });

            connection.on('message', (message, ack) => {
                console.log('socketServer receive : ', message);
                if (
                    message.mode === SERVER_MODE_TYPES.single ||
                    this.masterRoomIds.indexOf(connection.roomId) >= 0
                ) {
                    this.router.handleServerData(message);
                } else {
                    if (connection.handshake.query.childServer === 'true') {
                        if (
                            connection.roomIds &&
                            connection.roomIds.length > 0
                        ) {
                            connection.roomIds.forEach((roomId) => {
                                server.to(roomId).emit('message', message);
                            });
                        }
                    } else if (this.clientTargetList[connection.roomId]) {
                        server.to(this.clientTargetList[connection.roomId]).emit('message', message);
                    }
                }
                if (ack) {
                    const { key = true } = message;
                    ack(key);
                }
            });

            connection.on('close', (reasonCode, description) => {
                rendererConsole.warn('Entry disconnected.');
                this.emit('close');
                this.closeSingleConnection(this);
            });
            this.setState(this.state);
        });
        return server;
    }

    /**
     * SSL 인증서가 프로젝트에 포함되어있는 경우는 https,
     * 그렇지 않은 경우는 http 서버를 오픈한다.
     *
     * @param port{number} 오픈할 포트번호
     * @return {{address: string, httpServer: Server}}
     * @private
     */
    _getHttpServer(port) {
        let httpServer;
        let address;

        const rootDir = path.resolve(__dirname, '..', '..');
        if (fs.existsSync(path.resolve(rootDir, 'ssl', 'cert.pem'))) {
            httpServer = require('https').createServer(
                {
                    key: fs.readFileSync(path.resolve(rootDir, 'ssl', 'hardware.key')),
                    cert: fs.readFileSync(path.resolve(rootDir, 'ssl', 'cert.pem')),
                    ca: [
                        fs.readFileSync(path.resolve(rootDir, 'ssl', 'ChainCA1.crt')),
                        fs.readFileSync(path.resolve(rootDir, 'ssl', 'ChainCA2.crt')),
                        fs.readFileSync(path.resolve(rootDir, 'ssl', 'RootCA.crt')),
                    ],
                },
                (req, res) => {
                    res.writeHead(200);
                    res.end();
                }
            );
            address = `https://hardware.playentry.org:${port}`;
        } else {
            httpServer = require('http').createServer((request, response) => {
                response.writeHead(200);
                response.end();
            });
            address = `http://127.0.0.1:${port}`;
        }

        return {
            httpServer,
            address,
        };
    }

    closeSingleConnection(connection) {
        const connections = this.connections;
        const index = connections.indexOf(connection);
        if (index > -1) {
            this.connections.slice(index, 1);
            connection.close();
        }
    };

    send(data) {
        const childServerListCnt = Object.keys(this.childServerList).length;
        const payload = { data, version: appVersion };

        if (
            (this.runningMode === SERVER_MODE_TYPES.parent && childServerListCnt === 0) ||
            this.runningMode === SERVER_MODE_TYPES.child
        ) {
            if (this.connections.length !== 0) {
                this.connections.map((connection) => {
                    connection.emit('message', payload);
                });
            }
        } else if (this.masterRoomIds.length > 0) {
            this.masterRoomIds.forEach((masterRoomId) => {
                this.socketServer.to(masterRoomId).emit('message', payload);
            });
        }
    };

    setState(state) {
        this.state = state;
        if (this.connections.length) {
            const packet = this.packet;
            if (state === 'connecting') {
                packet[3] = 0x01;
                this.send(packet);
            } else if (state === 'connected') {
                packet[3] = 0x02;
                this.send(packet);
            } else if (state === 'lost') {
                packet[3] = 0x03;
                this.send(packet);
            } else if (state === 'disconnected') {
                packet[3] = 0x04;
                this.send(packet);
            }
        }
    };

    disconnectHardware() {
        this.send('disconnectHardware');
    };

    close() {
        if (this.socketServer) {
            this.socketServer.close();
            this.socketServer = undefined;
        }
        if (this.httpServer) {
            this.httpServer.close();
            this.httpServer = undefined;
        }
        this.connections = [];
        this.emit('closed');
    };
}

module.exports = Server;
<|endoftext|>


<commit_before>import { setupRerender } from 'preact/test-utils';
import { createElement as h, render, Component, createContext } from '../../src/index';
import { setupScratch, teardown } from '../_util/helpers';
import { Fragment } from '../../src';
import { i as ctxId } from '../../src/create-context';

/** @jsx h */

describe('createContext', () => {
	let scratch;
	let rerender;

	beforeEach(() => {
		scratch = setupScratch();
		rerender = setupRerender();
	});

	afterEach(() => {
		teardown(scratch);
	});

	it('should pass context to a consumer', () => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { a: 'a' };

		class Inner extends Component {
			render(props) {
				return
{props.a}
;
			}
		}

		sinon.spy(Inner.prototype, 'render');

		render(<Provider value={CONTEXT}>

				<Consumer>
					{data => <Inner {...data} />}
				</Consumer>

		</Provider>, scratch);

		// initial render does not invoke anything but render():
		expect(Inner.prototype.render).to.have.been.calledWithMatch(CONTEXT, {},  { ['__cC' + (ctxId - 1)]: {} });
		expect(scratch.innerHTML).to.equal('

a

');
	});

	it('should preserve provider context through nesting providers', (done) => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { a: 'a' };
		const CHILD_CONTEXT = { b: 'b' };

		class Inner extends Component {
			render(props) {
				return
{props.a} - {props.b}
;
			}
		}

		sinon.spy(Inner.prototype, 'render');

		render(<Provider value={CONTEXT}>
			<Consumer>
				{data =>
					(<Provider value={CHILD_CONTEXT}>
						<Consumer>
							{childData => <Inner {...data} {...childData} />}
						</Consumer>
					</Provider>)
				}
			</Consumer>
		</Provider>, scratch);

		// initial render does not invoke anything but render():
		expect(Inner.prototype.render).to.have.been.calledWithMatch({ ...CONTEXT, ...CHILD_CONTEXT }, {}, { ['__cC' + (ctxId - 1)]: {} });
		expect(Inner.prototype.render).to.be.calledOnce;
		expect(scratch.innerHTML).to.equal('
a - b
');
		setTimeout(() => {
			expect(Inner.prototype.render).to.be.calledOnce;
			done();
		}, 0);
	});

	it('should preserve provider context between different providers', () => {
		const { Provider: ThemeProvider, Consumer: ThemeConsumer } = createContext();
		const { Provider: DataProvider, Consumer: DataConsumer } = createContext();
		const THEME_CONTEXT = { theme: 'black' };
		const DATA_CONTEXT = { global: 'a' };

		class Inner extends Component {
			render(props) {
				return
{props.theme} - {props.global}
;
			}
		}

		sinon.spy(Inner.prototype, 'render');

		render(<ThemeProvider value={THEME_CONTEXT.theme}>
			<DataProvider value={DATA_CONTEXT}>
				<ThemeConsumer>
					{theme => (<DataConsumer>
						{data => <Inner theme={theme} {...data} />}
					</DataConsumer>)}
				</ThemeConsumer>
			</DataProvider>
		</ThemeProvider>, scratch);

		// initial render does not invoke anything but render():
		expect(Inner.prototype.render).to.have.been.calledWithMatch({ ...THEME_CONTEXT, ...DATA_CONTEXT }, {}, { ['__cC' + (ctxId - 1)]: {} });
		expect(scratch.innerHTML).to.equal('
black - a
');
	});

	it('should preserve provider context through nesting consumers', () => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { a: 'a' };

		class Inner extends Component {
			render(props) {
				return
{props.a}
;
			}
		}

		sinon.spy(Inner.prototype, 'render');

		render(<Provider value={CONTEXT}>
			<Consumer>
				{data =>
					(<Consumer>
						{childData => <Inner {...data} {...childData} />}
					</Consumer>)
				}
			</Consumer>
		</Provider>, scratch);

		// initial render does not invoke anything but render():
		expect(Inner.prototype.render).to.have.been.calledWithMatch({ ...CONTEXT }, {}, { ['__cC' + (ctxId - 1)]: {} });
		expect(scratch.innerHTML).to.equal('
a
');
	});

	it('should not emit when value does not update', () => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { a: 'a' };

		class NoUpdate extends Component {
			shouldComponentUpdate() {
				return false;
			}

			render() {
				return this.props.children;
			}
		}

		class Inner extends Component {
			render(props) {
				return
{props.a}
;
			}
		}

		sinon.spy(Inner.prototype, 'render');

		render(

				<Provider value={CONTEXT}>
					<NoUpdate>
						<Consumer>
							{data => <Inner {...data} />}
						</Consumer>
					</NoUpdate>
				</Provider>

, scratch);

		expect(Inner.prototype.render).to.have.been.calledOnce;

		render(

				<Provider value={CONTEXT}>
					<NoUpdate>
						<Consumer>
							{data => <Inner {...data} />}
						</Consumer>
					</NoUpdate>
				</Provider>

, scratch);

		expect(Inner.prototype.render).to.have.been.calledOnce;
	});

	it('should preserve provider context through nested components', () => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { a: 'a' };

		class Consumed extends Component {
			render(props) {
				return {props.a};
			}
		}

		sinon.spy(Consumed.prototype, 'render');

		class Outer extends Component {
			render() {
				return
<Inner />
;
			}
		}

		class Inner extends Component {
			render() {
				return (
					<Fragment>
						<InnerMost />
					</Fragment>
				);
			}
		}

		class InnerMost extends Component {
			render() {
				return (

						<Consumer>
							{data => <Consumed {...data} />}
						</Consumer>

				);
			}
		}

		render((
			<Provider value={CONTEXT}>
				<Outer />
			</Provider>
		), scratch);

		// initial render does not invoke anything but render():
		expect(Consumed.prototype.render).to.have.been.calledWithMatch({ ...CONTEXT }, {}, { ['__cC' + (ctxId - 1)]: {} });
		expect(scratch.innerHTML).to.equal('

a

');
	});

	it('should propagates through shouldComponentUpdate false', done => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { a: 'a' };
		const UPDATED_CONTEXT = { a: 'b' };

		class Consumed extends Component {
			render(props) {
				return {props.a};
			}
		}

		sinon.spy(Consumed.prototype, 'render');

		class Outer extends Component {
			render() {
				return
<Inner />
;
			}
		}

		class Inner extends Component {
			shouldComponentUpdate() {
				return false;
			}

			render() {
				return (
					<Fragment>
						<InnerMost />
					</Fragment>
				);
			}
		}

		class InnerMost extends Component {
			render() {
				return (

						<Consumer>
							{data => <Consumed {...data} />}
						</Consumer>

				);
			}
		}

		class App extends Component {
			render() {
				return (
					<Provider value={this.props.value}>
						<Outer />
					</Provider>
				);
			}
		}

		render((
			<App value={CONTEXT} />
		), scratch);
		expect(scratch.innerHTML).to.equal('

a

');
		expect(Consumed.prototype.render).to.have.been.calledOnce;

		render((
			<App value={UPDATED_CONTEXT} />
		), scratch);

		rerender();

		// initial render does not invoke anything but render():
		expect(Consumed.prototype.render).to.have.been.calledTwice;
		// expect(Consumed.prototype.render).to.have.been.calledWithMatch({ ...UPDATED_CONTEXT }, {}, { ['__cC' + (ctxId - 1)]: {} });
		expect(scratch.innerHTML).to.equal('

b

');
		setTimeout(() => {
			expect(Consumed.prototype.render).to.have.been.calledTwice;
			done();
		});
	});

	it('should keep the right context at the right "depth"', () => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { theme: 'a', global: 1 };
		const NESTED_CONTEXT = { theme: 'b', global: 1 };

		class Inner extends Component {
			render(props) {
				return
{props.theme} - {props.global}
;
			}
		}
		class Nested extends Component {
			render(props) {
				return
{props.theme} - {props.global}
;
			}
		}

		sinon.spy(Inner.prototype, 'render');
		sinon.spy(Nested.prototype, 'render');

		render((
			<Provider value={CONTEXT}>
				<Provider value={NESTED_CONTEXT}>
					<Consumer>
						{data => <Nested {...data} />}
					</Consumer>
				</Provider>
				<Consumer>
					{data => <Inner {...data} />}
				</Consumer>
			</Provider>
		), scratch);

		// initial render does not invoke anything but render():
		expect(Nested.prototype.render).to.have.been.calledWithMatch({ ...NESTED_CONTEXT }, {}, { ['__cC' + (ctxId - 1)]: {} });
		expect(Inner.prototype.render).to.have.been.calledWithMatch({ ...CONTEXT }, {}, { ['__cC' + (ctxId - 1)]: {} });

		expect(scratch.innerHTML).to.equal('
b - 1

a - 1
');
	});

	it('should not re-render the consumer if the context doesn\'t change', () => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { i: 1 };

		class Inner extends Component {
			render(props) {
				return
{props.i}
;
			}
		}

		sinon.spy(Inner.prototype, 'render');

		const Child = data => <Inner {...data} />;

		render(
			<Provider value={CONTEXT}>
				<Consumer>
					{Child}
				</Consumer>
			</Provider>,
			scratch
		);

		render(
			<Provider value={CONTEXT}>
				<Consumer>
					{Child}
				</Consumer>
			</Provider>,
			scratch
		);

		// Rendered twice, should called just one 'Consumer' render
		expect(Inner.prototype.render).to.have.been.calledOnce.and.calledWithMatch(CONTEXT, {},  { ['__cC' + (ctxId - 1)]: {} });
		expect(scratch.innerHTML).to.equal('
1
');

		render(
			<Provider value={{ i: 2 }}>
				<Consumer>
					{Child}
				</Consumer>
			</Provider>,
			scratch
		);

		// Rendered three times, should call 'Consumer' render two times
		expect(Inner.prototype.render).to.have.been.calledTwice.and.calledWithMatch({ i: 2 }, {},  { ['__cC' + (ctxId - 1)]: {} });
		expect(scratch.innerHTML).to.equal('
2
');
	});

	it('should re-render the consumer if the children change', () => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { i: 1 };

		class Inner extends Component {
			render(props) {
				return
{props.i}
;
			}
		}

		sinon.spy(Inner.prototype, 'render');

		render(
			<Provider value={CONTEXT}>
				<Consumer>
					{data => <Inner {...data}/>}
				</Consumer>
			</Provider>,
			scratch
		);

		render(
			<Provider value={CONTEXT}>
				<Consumer>
					{data => <Inner {...data}/>}
				</Consumer>
			</Provider>,
			scratch
		);

		// Rendered twice, with two different children for consumer, should render twice
		expect(Inner.prototype.render).to.have.been.calledTwice;
		expect(scratch.innerHTML).to.equal('
1
');
	});

	describe('class.contextType', () => {
		it('should use default value', () => {
			const ctx = createContext('foo');

			let actual;
			class App extends Component {
				render() {
					actual = this.context;
					return
bar
;
				}
			}

			App.contextType = ctx;

			render(<App />, scratch);
			expect(actual).to.deep.equal('foo');
		});

		it('should use the value of the nearest Provider', () => {
			const ctx = createContext('foo');

			let actual;
			class App extends Component {
				render() {
					actual = this.context;
					return
bar
;
				}
			}

			App.contextType = ctx;
			const Provider = ctx.Provider;

			render((
				<Provider value="bar">
					<Provider value="bob">
						<App />
					</Provider>
				</Provider>
			), scratch);
			expect(actual).to.deep.equal('bob');
		});

		it('should restore legacy context for children', () => {
			const Foo = createContext('foo');
			const spy = sinon.spy();

			class NewContext extends Component {
				render() {
					return
{this.props.children}
;
				}
			}

			class OldContext extends Component {
				getChildContext() {
					return { foo: 'foo' };
				}

				render() {
					return
{this.props.children}
;
				}
			}

			class Inner extends Component {
				render() {
					spy(this.context);
					return
Inner
;
				}
			}

			NewContext.contextType = Foo;

			render((
				<Foo.Provider value="bar">
					<OldContext>
						<NewContext>
							<Inner />
						</NewContext>
					</OldContext>
				</Foo.Provider>
			), scratch);

			expect(spy).to.be.calledWithMatch({ foo: 'foo' });
		});

		it('should call componentWillUnmount', () => {
			let Foo = createContext('foo');
			let spy = sinon.spy();

			let instance;
			class App extends Component {
				constructor(props) {
					super(props);
					instance = this;
				}

				componentWillUnmount() {
					spy(this);
				}

				render() {
					return
;
				}
			}

			App.contextType = Foo;

			render((
				<Foo.Provider value="foo">
					<App />
				</Foo.Provider>
			), scratch);

			render(null, scratch);

			expect(spy).to.be.calledOnce;
			expect(spy.getCall(0).args[0]).to.equal(instance);
		});
	});
});
<commit_msg>Fix the linting<commit_after>import { setupRerender } from 'preact/test-utils';
import { createElement as h, render, Component, createContext } from '../../src/index';
import { setupScratch, teardown } from '../_util/helpers';
import { Fragment } from '../../src';
import { i as ctxId } from '../../src/create-context';

/** @jsx h */

describe('createContext', () => {
	let scratch;
	let rerender;

	beforeEach(() => {
		scratch = setupScratch();
		rerender = setupRerender();
	});

	afterEach(() => {
		teardown(scratch);
	});

	it('should pass context to a consumer', () => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { a: 'a' };

		class Inner extends Component {
			render(props) {
				return
{props.a}
;
			}
		}

		sinon.spy(Inner.prototype, 'render');

		render(<Provider value={CONTEXT}>

				<Consumer>
					{data => <Inner {...data} />}
				</Consumer>

		</Provider>, scratch);

		// initial render does not invoke anything but render():
		expect(Inner.prototype.render).to.have.been.calledWithMatch(CONTEXT, {},  { ['__cC' + (ctxId - 1)]: {} });
		expect(scratch.innerHTML).to.equal('

a

');
	});

	it('should preserve provider context through nesting providers', (done) => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { a: 'a' };
		const CHILD_CONTEXT = { b: 'b' };

		class Inner extends Component {
			render(props) {
				return
{props.a} - {props.b}
;
			}
		}

		sinon.spy(Inner.prototype, 'render');

		render(<Provider value={CONTEXT}>
			<Consumer>
				{data =>
					(<Provider value={CHILD_CONTEXT}>
						<Consumer>
							{childData => <Inner {...data} {...childData} />}
						</Consumer>
					</Provider>)
				}
			</Consumer>
		</Provider>, scratch);

		// initial render does not invoke anything but render():
		expect(Inner.prototype.render).to.have.been.calledWithMatch({ ...CONTEXT, ...CHILD_CONTEXT }, {}, { ['__cC' + (ctxId - 1)]: {} });
		expect(Inner.prototype.render).to.be.calledOnce;
		expect(scratch.innerHTML).to.equal('
a - b
');
		setTimeout(() => {
			expect(Inner.prototype.render).to.be.calledOnce;
			done();
		}, 0);
	});

	it('should preserve provider context between different providers', () => {
		const { Provider: ThemeProvider, Consumer: ThemeConsumer } = createContext();
		const { Provider: DataProvider, Consumer: DataConsumer } = createContext();
		const THEME_CONTEXT = { theme: 'black' };
		const DATA_CONTEXT = { global: 'a' };

		class Inner extends Component {
			render(props) {
				return
{props.theme} - {props.global}
;
			}
		}

		sinon.spy(Inner.prototype, 'render');

		render(<ThemeProvider value={THEME_CONTEXT.theme}>
			<DataProvider value={DATA_CONTEXT}>
				<ThemeConsumer>
					{theme => (<DataConsumer>
						{data => <Inner theme={theme} {...data} />}
					</DataConsumer>)}
				</ThemeConsumer>
			</DataProvider>
		</ThemeProvider>, scratch);

		// initial render does not invoke anything but render():
		expect(Inner.prototype.render).to.have.been.calledWithMatch({ ...THEME_CONTEXT, ...DATA_CONTEXT }, {}, { ['__cC' + (ctxId - 1)]: {} });
		expect(scratch.innerHTML).to.equal('
black - a
');
	});

	it('should preserve provider context through nesting consumers', () => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { a: 'a' };

		class Inner extends Component {
			render(props) {
				return
{props.a}
;
			}
		}

		sinon.spy(Inner.prototype, 'render');

		render(<Provider value={CONTEXT}>
			<Consumer>
				{data =>
					(<Consumer>
						{childData => <Inner {...data} {...childData} />}
					</Consumer>)
				}
			</Consumer>
		</Provider>, scratch);

		// initial render does not invoke anything but render():
		expect(Inner.prototype.render).to.have.been.calledWithMatch({ ...CONTEXT }, {}, { ['__cC' + (ctxId - 1)]: {} });
		expect(scratch.innerHTML).to.equal('
a
');
	});

	it('should not emit when value does not update', () => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { a: 'a' };

		class NoUpdate extends Component {
			shouldComponentUpdate() {
				return false;
			}

			render() {
				return this.props.children;
			}
		}

		class Inner extends Component {
			render(props) {
				return
{props.a}
;
			}
		}

		sinon.spy(Inner.prototype, 'render');

		render(

				<Provider value={CONTEXT}>
					<NoUpdate>
						<Consumer>
							{data => <Inner {...data} />}
						</Consumer>
					</NoUpdate>
				</Provider>

, scratch);

		expect(Inner.prototype.render).to.have.been.calledOnce;

		render(

				<Provider value={CONTEXT}>
					<NoUpdate>
						<Consumer>
							{data => <Inner {...data} />}
						</Consumer>
					</NoUpdate>
				</Provider>

, scratch);

		expect(Inner.prototype.render).to.have.been.calledOnce;
	});

	it('should preserve provider context through nested components', () => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { a: 'a' };

		class Consumed extends Component {
			render(props) {
				return {props.a};
			}
		}

		sinon.spy(Consumed.prototype, 'render');

		class Outer extends Component {
			render() {
				return
<Inner />
;
			}
		}

		class Inner extends Component {
			render() {
				return (
					<Fragment>
						<InnerMost />
					</Fragment>
				);
			}
		}

		class InnerMost extends Component {
			render() {
				return (

						<Consumer>
							{data => <Consumed {...data} />}
						</Consumer>

				);
			}
		}

		render((
			<Provider value={CONTEXT}>
				<Outer />
			</Provider>
		), scratch);

		// initial render does not invoke anything but render():
		expect(Consumed.prototype.render).to.have.been.calledWithMatch({ ...CONTEXT }, {}, { ['__cC' + (ctxId - 1)]: {} });
		expect(scratch.innerHTML).to.equal('

a

');
	});

	it('should propagates through shouldComponentUpdate false', done => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { a: 'a' };
		const UPDATED_CONTEXT = { a: 'b' };

		class Consumed extends Component {
			render(props) {
				return {props.a};
			}
		}

		sinon.spy(Consumed.prototype, 'render');

		class Outer extends Component {
			render() {
				return
<Inner />
;
			}
		}

		class Inner extends Component {
			shouldComponentUpdate() {
				return false;
			}

			render() {
				return (
					<Fragment>
						<InnerMost />
					</Fragment>
				);
			}
		}

		class InnerMost extends Component {
			render() {
				return (

						<Consumer>
							{data => <Consumed {...data} />}
						</Consumer>

				);
			}
		}

		class App extends Component {
			render() {
				return (
					<Provider value={this.props.value}>
						<Outer />
					</Provider>
				);
			}
		}

		render((
			<App value={CONTEXT} />
		), scratch);
		expect(scratch.innerHTML).to.equal('

a

');
		expect(Consumed.prototype.render).to.have.been.calledOnce;

		render((
			<App value={UPDATED_CONTEXT} />
		), scratch);

		rerender();

		// initial render does not invoke anything but render():
		expect(Consumed.prototype.render).to.have.been.calledTwice;
		// expect(Consumed.prototype.render).to.have.been.calledWithMatch({ ...UPDATED_CONTEXT }, {}, { ['__cC' + (ctxId - 1)]: {} });
		expect(scratch.innerHTML).to.equal('

b

');
		setTimeout(() => {
			expect(Consumed.prototype.render).to.have.been.calledTwice;
			done();
		});
	});

	it('should keep the right context at the right "depth"', () => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { theme: 'a', global: 1 };
		const NESTED_CONTEXT = { theme: 'b', global: 1 };

		class Inner extends Component {
			render(props) {
				return
{props.theme} - {props.global}
;
			}
		}
		class Nested extends Component {
			render(props) {
				return
{props.theme} - {props.global}
;
			}
		}

		sinon.spy(Inner.prototype, 'render');
		sinon.spy(Nested.prototype, 'render');

		render((
			<Provider value={CONTEXT}>
				<Provider value={NESTED_CONTEXT}>
					<Consumer>
						{data => <Nested {...data} />}
					</Consumer>
				</Provider>
				<Consumer>
					{data => <Inner {...data} />}
				</Consumer>
			</Provider>
		), scratch);

		// initial render does not invoke anything but render():
		expect(Nested.prototype.render).to.have.been.calledWithMatch({ ...NESTED_CONTEXT }, {}, { ['__cC' + (ctxId - 1)]: {} });
		expect(Inner.prototype.render).to.have.been.calledWithMatch({ ...CONTEXT }, {}, { ['__cC' + (ctxId - 1)]: {} });

		expect(scratch.innerHTML).to.equal('
b - 1

a - 1
');
	});

	it('should not re-render the consumer if the context doesn\'t change', () => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { i: 1 };

		class Inner extends Component {
			render(props) {
				return
{props.i}
;
			}
		}

		sinon.spy(Inner.prototype, 'render');

		const Child = data => <Inner {...data} />;

		render(
			<Provider value={CONTEXT}>
				<Consumer>
					{Child}
				</Consumer>
			</Provider>,
			scratch
		);

		render(
			<Provider value={CONTEXT}>
				<Consumer>
					{Child}
				</Consumer>
			</Provider>,
			scratch
		);

		// Rendered twice, should called just one 'Consumer' render
		expect(Inner.prototype.render).to.have.been.calledOnce.and.calledWithMatch(CONTEXT, {},  { ['__cC' + (ctxId - 1)]: {} });
		expect(scratch.innerHTML).to.equal('
1
');

		render(
			<Provider value={{ i: 2 }}>
				<Consumer>
					{Child}
				</Consumer>
			</Provider>,
			scratch
		);

		// Rendered three times, should call 'Consumer' render two times
		expect(Inner.prototype.render).to.have.been.calledTwice.and.calledWithMatch({ i: 2 }, {},  { ['__cC' + (ctxId - 1)]: {} });
		expect(scratch.innerHTML).to.equal('
2
');
	});

	it('should re-render the consumer if the children change', () => {
		const { Provider, Consumer } = createContext();
		const CONTEXT = { i: 1 };

		class Inner extends Component {
			render(props) {
				return
{props.i}
;
			}
		}

		sinon.spy(Inner.prototype, 'render');

		render(
			<Provider value={CONTEXT}>
				<Consumer>
					{data => <Inner {...data} />}
				</Consumer>
			</Provider>,
			scratch
		);

		render(
			<Provider value={CONTEXT}>
				<Consumer>
					{data => <Inner {...data} />}
				</Consumer>
			</Provider>,
			scratch
		);

		// Rendered twice, with two different children for consumer, should render twice
		expect(Inner.prototype.render).to.have.been.calledTwice;
		expect(scratch.innerHTML).to.equal('
1
');
	});

	describe('class.contextType', () => {
		it('should use default value', () => {
			const ctx = createContext('foo');

			let actual;
			class App extends Component {
				render() {
					actual = this.context;
					return
bar
;
				}
			}

			App.contextType = ctx;

			render(<App />, scratch);
			expect(actual).to.deep.equal('foo');
		});

		it('should use the value of the nearest Provider', () => {
			const ctx = createContext('foo');

			let actual;
			class App extends Component {
				render() {
					actual = this.context;
					return
bar
;
				}
			}

			App.contextType = ctx;
			const Provider = ctx.Provider;

			render((
				<Provider value="bar">
					<Provider value="bob">
						<App />
					</Provider>
				</Provider>
			), scratch);
			expect(actual).to.deep.equal('bob');
		});

		it('should restore legacy context for children', () => {
			const Foo = createContext('foo');
			const spy = sinon.spy();

			class NewContext extends Component {
				render() {
					return
{this.props.children}
;
				}
			}

			class OldContext extends Component {
				getChildContext() {
					return { foo: 'foo' };
				}

				render() {
					return
{this.props.children}
;
				}
			}

			class Inner extends Component {
				render() {
					spy(this.context);
					return
Inner
;
				}
			}

			NewContext.contextType = Foo;

			render((
				<Foo.Provider value="bar">
					<OldContext>
						<NewContext>
							<Inner />
						</NewContext>
					</OldContext>
				</Foo.Provider>
			), scratch);

			expect(spy).to.be.calledWithMatch({ foo: 'foo' });
		});

		it('should call componentWillUnmount', () => {
			let Foo = createContext('foo');
			let spy = sinon.spy();

			let instance;
			class App extends Component {
				constructor(props) {
					super(props);
					instance = this;
				}

				componentWillUnmount() {
					spy(this);
				}

				render() {
					return
;
				}
			}

			App.contextType = Foo;

			render((
				<Foo.Provider value="foo">
					<App />
				</Foo.Provider>
			), scratch);

			render(null, scratch);

			expect(spy).to.be.calledOnce;
			expect(spy.getCall(0).args[0]).to.equal(instance);
		});
	});
});
<|endoftext|>


<commit_before>import {
  binarySearch,
  equals,
  extend,
  find,
  findIndex,
  isSorted,
  linearFindNearest,
  numberSafeCompareFunction,
  remove,
  reverseSubArray,
  stableSort,
} from '../../../../src/ol/array.js';

describe('ol.array', function () {
  describe('binarySearch', function () {
    const insertionPoint = function (position) {
      return -(position + 1);
    };
    const revNumCompare = function (a, b) {
      return b - a;
    };

    describe('default comparison on array of String(s)', function () {
      const a = [
        '1000',
        '9',
        'AB',
        'ABC',
        'ABCABC',
        'ABD',
        'ABDA',
        'B',
        'B',
        'B',
        'C',
        'CA',
        'CC',
        'ZZZ',
        'ab',
        'abc',
        'abcabc',
        'abd',
        'abda',
        'b',
        'c',
        'ca',
        'cc',
        'zzz',
      ];

      it("should find '1000' at index 0", function () {
        expect(binarySearch(a, '1000')).to.be(0);
      });
      it("should find 'zzz' at index " + (a.length - 1), function () {
        expect(binarySearch(a, 'zzz')).to.be(a.length - 1);
      });
      it("should find 'C' at index 10", function () {
        expect(binarySearch(a, 'C')).to.be(10);
      });
      it("should find 'B' at index 7 || 8 || 9", function () {
        const pos = binarySearch(a, 'B');
        expect(pos == 7 || pos == 8 || pos == 9).to.be.ok();
      });
      it("should not find '100'", function () {
        const pos = binarySearch(a, '100');
        expect(pos < 0).to.be.ok();
      });
      it("should have an insertion point of 0 for '100'", function () {
        const pos = binarySearch(a, '100');
        expect(insertionPoint(pos)).to.be(0);
      });
      it("should not find 'zzz0'", function () {
        const pos = binarySearch(a, 'zzz0');
        expect(pos < 0).to.be.ok();
      });
      it(
        'should have an insertion point of ' + a.length + " for 'zzz0'",
        function () {
          const pos = binarySearch(a, 'zzz0');
          expect(insertionPoint(pos)).to.be(a.length);
        }
      );
      it("should not find 'BA'", function () {
        const pos = binarySearch(a, 'zzz0');
        expect(pos < 0).to.be.ok();
      });
      it("should have an insertion point of 10 for 'BA'", function () {
        const pos = binarySearch(a, 'BA');
        expect(insertionPoint(pos)).to.be(10);
      });
    });

    describe('0 length array with default comparison', function () {
      const b = [];
      it("should not find 'a'", function () {
        expect(binarySearch(b, 'a') < 0).to.be.ok();
      });
      it("should have an insertion point of 0 for 'a'", function () {
        const pos = binarySearch(b, 'a');
        expect(insertionPoint(pos)).to.be(0);
      });
    });

    describe('single element array with default lexiographical comparison', function () {
      const c = ['only item'];
      it("should find 'only item' at index 0", function () {
        expect(binarySearch(c, 'only item')).to.be(0);
      });
      it("should not find 'a'", function () {
        expect(binarySearch(c, 'a') < 0).to.be.ok();
      });
      it("should have an insertion point of 0 for 'a'", function () {
        const pos = binarySearch(c, 'a');
        expect(insertionPoint(pos)).to.be(0);
      });
      it("should not find 'z'", function () {
        expect(binarySearch(c, 'z') < 0).to.be.ok();
      });
      it("should have an insertion point of 1 for 'z'", function () {
        const pos = binarySearch(c, 'z');
        expect(insertionPoint(pos)).to.be(1);
      });
    });

    describe('default comparison on array of Number(s)', function () {
      const d = [
        -897123.9,
        -321434.58758,
        -1321.3124,
        -324,
        -9,
        -3,
        0,
        0,
        0,
        0.31255,
        5,
        142.88888708,
        334,
        342,
        453,
        54254,
      ];
      it('should find -897123.9 at index 0', function () {
        expect(binarySearch(d, -897123.9)).to.be(0);
      });
      it('should find 54254 at index ' + (d.length - 1), function () {
        expect(binarySearch(d, 54254)).to.be(d.length - 1);
      });
      it('should find -3 at index 5', function () {
        expect(binarySearch(d, -3)).to.be(5);
      });
      it('should find 0 at index 6 || 7 || 8', function () {
        const pos = binarySearch(d, 0);
        expect(pos == 6 || pos == 7 || pos == 8).to.be(true);
      });
      it('should not find -900000', function () {
        const pos = binarySearch(d, -900000);
        expect(pos < 0).to.be(true);
      });
      it('should have an insertion point of 0 for -900000', function () {
        const pos = binarySearch(d, -900000);
        expect(insertionPoint(pos)).to.be(0);
      });
      it('should not find 54255', function () {
        const pos = binarySearch(d, 54255);
        expect(pos < 0).to.be(true);
      });
      it(
        'should have an insertion point of ' + d.length + ' for 54255',
        function () {
          const pos = binarySearch(d, 54255);
          expect(insertionPoint(pos)).to.be(d.length);
        }
      );
      it('should not find 1.1', function () {
        const pos = binarySearch(d, 1.1);
        expect(pos < 0).to.be(true);
      });
      it('should have an insertion point of 10 for 1.1', function () {
        const pos = binarySearch(d, 1.1);
        expect(insertionPoint(pos)).to.be(10);
      });
    });

    describe('custom comparison function, which reverse orders numbers', function () {
      const e = [
        54254,
        453,
        342,
        334,
        142.88888708,
        5,
        0.31255,
        0,
        0,
        0,
        -3,
        -9,
        -324,
        -1321.3124,
        -321434.58758,
        -897123.9,
      ];
      it('should find 54254 at index 0', function () {
        const pos = binarySearch(e, 54254, revNumCompare);
        expect(pos).to.be(0);
      });
      it('should find -897123.9 at index ' + (e.length - 1), function () {
        const pos = binarySearch(e, -897123.9, revNumCompare);
        expect(pos).to.be(e.length - 1);
      });
      it('should find -3 at index 10', function () {
        const pos = binarySearch(e, -3, revNumCompare);
        expect(pos).to.be(10);
      });
      it('should find 0 at index 7 || 8 || 9', function () {
        const pos = binarySearch(e, 0, revNumCompare);
        expect(pos == 7 || pos == 8 || pos == 9).to.be(true);
      });
      it('should not find 54254.1', function () {
        const pos = binarySearch(e, 54254.1, revNumCompare);
        expect(pos < 0).to.be(true);
      });
      it('should have an insertion point of 0 for 54254.1', function () {
        const pos = binarySearch(e, 54254.1, revNumCompare);
        expect(insertionPoint(pos)).to.be(0);
      });
      it('should not find -897124', function () {
        const pos = binarySearch(e, -897124, revNumCompare);
        expect(pos < 0).to.be(true);
      });
      it(
        'should have an insertion point of ' + e.length + ' for -897124',
        function () {
          const pos = binarySearch(e, -897124, revNumCompare);
          expect(insertionPoint(pos)).to.be(e.length);
        }
      );
      it('should not find 1.1', function () {
        const pos = binarySearch(e, 1.1, revNumCompare);
        expect(pos < 0).to.be(true);
      });
      it('should have an insertion point of 0 for 1.1', function () {
        const pos = binarySearch(e, 1.1, revNumCompare);
        expect(insertionPoint(pos)).to.be(6);
      });
    });

    describe('0 length array with custom comparison function', function () {
      const f = [];
      it('should not find 0', function () {
        const pos = binarySearch(f, 0, revNumCompare);
        expect(pos < 0).to.be(true);
      });
      it('should have an insertion point of 0 for 0', function () {
        const pos = binarySearch(f, 0, revNumCompare);
        expect(insertionPoint(pos)).to.be(0);
      });
    });

    describe('single element array with custom comparison function', function () {
      const g = [1];
      it('should find 1 at index 0', function () {
        const pos = binarySearch(g, 1, revNumCompare);
        expect(pos).to.be(0);
      });
      it('should not find 2', function () {
        const pos = binarySearch(g, 2, revNumCompare);
        expect(pos < 0).to.be(true);
      });
      it('should have an insertion point of 0 for 2', function () {
        const pos = binarySearch(g, 2, revNumCompare);
        expect(insertionPoint(pos)).to.be(0);
      });
      it('should not find 0', function () {
        const pos = binarySearch(g, 0, revNumCompare);
        expect(pos < 0).to.be(true);
      });
      it('should have an insertion point of 1 for 0', function () {
        const pos = binarySearch(g, 0, revNumCompare);
        expect(insertionPoint(pos)).to.be(1);
      });
    });

    describe('finding first index when multiple candidates', function () {
      it('should find the index of the first 0', function () {
        expect(binarySearch([0, 0, 1], 0)).to.be(0);
      });
      it('should find the index of the first 1', function () {
        expect(binarySearch([0, 1, 1], 1)).to.be(1);
      });
    });

    describe("Don't use Array#slice, Function#apply and Function#call", function () {
      const a = [1, 5, 7, 11, 13, 16, 19, 24, 28, 31, 33, 36, 40, 50, 52, 55];
      const calls = {
        'Array#slice': false,
        'Function#apply': false,
        'Function#call': false,
      };
      let origArraySlice;
      let origFunctionApply;
      let origFunctionCall;

      it('does not use potentially slow methods (default & custom compare)', function () {
        // Mockup (I failed to use sinon.spy and beforeEach-hooks)
        origArraySlice = Array.prototype.slice;
        origFunctionApply = Function.prototype.apply;
        origFunctionCall = Function.prototype.call;
        Array.prototype.slice = function () {
          calls['Array#slice'] = true;
        };
        Function.prototype.apply = function () {
          calls['Function#apply'] = true;
        };
        Function.prototype.call = function () {
          calls['Function#call'] = true;
        };

        // Now actually call and test the method twice
        binarySearch(a, 48);
        binarySearch(a, 13, function (a, b) {
          return a > b ? 1 : a < b ? -1 : 0;
        });

        // Restore mocked up methods
        Array.prototype.slice = origArraySlice;
        Function.prototype.apply = origFunctionApply;
        Function.prototype.call = origFunctionCall;

        // Expectations
        expect(calls['Array#slice']).to.be(false);
        expect(calls['Function#apply']).to.be(false);
        expect(calls['Function#call']).to.be(false);
      });
    });

    describe('when items are not found', function () {
      const arr = [1, 2, 2, 2, 3, 5, 9];

      it('should return the index of where the item would go plus one, negated, if the item is not found', function () {
        expect(binarySearch(arr, 4)).to.equal(-6);
      });
      it('should work even on empty arrays', function () {
        expect(binarySearch([], 42)).to.equal(-1);
      });
      it('should work even on arrays of doubles', function () {
        expect(binarySearch([0.0, 0.1, 0.2, 0.3, 0.4], 0.25)).to.equal(-4);
      });
    });
  });

  describe('equals', function () {
    it('returns true for [] == []', function () {
      expect(equals([], [])).to.be(true);
    });
    it('returns true for [1] == [1]', function () {
      expect(equals([1], [1])).to.be(true);
    });
    it("returns true for ['1'] == ['1']", function () {
      expect(equals(['1'], ['1'])).to.be(true);
    });
    it("returns false for [1] == ['1']", function () {
      expect(equals([1], ['1'])).to.be(false);
    });
    it('returns true for [null] == [null]', function () {
      expect(equals([null], [null])).to.be(true);
    });
    it('returns false for [null] == [undefined]', function () {
      expect(equals([null], [undefined])).to.be(false);
    });
    it('returns true for [1, 2] == [1, 2]', function () {
      expect(equals([1, 2], [1, 2])).to.be(true);
    });
    it('returns false for [1, 2] == [2, 1]', function () {
      expect(equals([1, 2], [2, 1])).to.be(false);
    });
    it('returns false for [1, 2] == [1]', function () {
      expect(equals([1, 2], [1])).to.be(false);
    });
    it('returns false for [1] == [1, 2]', function () {
      expect(equals([1], [1, 2])).to.be(false);
    });
    it('returns false for [{}] == [{}]', function () {
      expect(equals([{}], [{}])).to.be(false);
    });
  });
  describe('extend', function () {
    it('extends an array in place with an array', function () {
      const a = [0, 1];
      extend(a, [2, 3]);
      expect(a).to.eql([0, 1, 2, 3]);
    });
    it('extends an array in place with a number', function () {
      const a = [0, 1];
      extend(a, 2);
      expect(a).to.eql([0, 1, 2]);
    });
    it('extends an array in place with a big array', function () {
      const a = [];
      let i = 250000; // original test has 1.000.000, but that was too slow
      const bigArray = Array(i);
      while (i--) {
        bigArray[i] = i;
      }
      extend(a, bigArray);
      expect(a).to.eql(bigArray);
    });
  });

  describe('find', function () {
    it('finds numbers in an array', function () {
      const a = [0, 1, 2, 3];
      const b = find(a, function (val, index, a2) {
        expect(a).to.equal(a2);
        expect(typeof index).to.be('number');
        return val > 1;
      });
      expect(b).to.be(2);
    });

    it('returns null when an item in an array is not found', function () {
      const a = [0, 1, 2, 3];
      const b = find(a, function (val, index, a2) {
        return val > 100;
      });
      expect(b).to.be(null);
    });

    it('finds items in an array-like', function () {
      const a = 'abCD';
      const b = find(a, function (val, index, a2) {
        expect(a).to.equal(a2);
        expect(typeof index).to.be('number');
        return val >= 'A' && val <= 'Z';
      });
      expect(b).to.be('C');
    });

    it('returns null when nothing in an array-like is found', function () {
      const a = 'abcd';
      const b = find(a, function (val, index, a2) {
        return val >= 'A' && val <= 'Z';
      });
      expect(b).to.be(null);
    });
  });

  describe('findIndex', function () {
    it('finds index of numbers in an array', function () {
      const a = [0, 1, 2, 3];
      const b = findIndex(a, function (val, index, a2) {
        expect(a).to.equal(a2);
        expect(typeof index).to.be('number');
        return val > 1;
      });
      expect(b).to.be(2);
    });

    it('returns -1 when an item in an array is not found', function () {
      const a = [0, 1, 2, 3];
      const b = findIndex(a, function (val, index, a2) {
        return val > 100;
      });
      expect(b).to.be(-1);
    });
  });

  describe('isSorted', function () {
    it('works with just an array as argument', function () {
      expect(isSorted([1, 2, 3])).to.be(true);
      expect(isSorted([1, 2, 2])).to.be(true);
      expect(isSorted([1, 2, 1])).to.be(false);
    });

    it('works with strict comparison without compare function', function () {
      expect(isSorted([1, 2, 3], null, true)).to.be(true);
      expect(isSorted([1, 2, 2], null, true)).to.be(false);
      expect(isSorted([1, 2, 1], null, true)).to.be(false);
    });

    it('works with a compare function', function () {
      function compare(a, b) {
        return b - a;
      }
      expect(isSorted([1, 2, 3], compare)).to.be(false);
      expect(isSorted([3, 2, 2], compare)).to.be(true);
    });
  });

  describe('linearFindNearest', function () {
    it('returns expected value', function () {
      const arr = [1000, 500, 100];

      expect(linearFindNearest(arr, 10000, 0)).to.eql(0);
      expect(linearFindNearest(arr, 10000, 1)).to.eql(0);
      expect(linearFindNearest(arr, 10000, -1)).to.eql(0);

      expect(linearFindNearest(arr, 1000, 0)).to.eql(0);
      expect(linearFindNearest(arr, 1000, 1)).to.eql(0);
      expect(linearFindNearest(arr, 1000, -1)).to.eql(0);

      expect(linearFindNearest(arr, 900, 0)).to.eql(0);
      expect(linearFindNearest(arr, 900, 1)).to.eql(0);
      expect(linearFindNearest(arr, 900, -1)).to.eql(1);

      expect(linearFindNearest(arr, 750, 0)).to.eql(1);
      expect(linearFindNearest(arr, 750, 1)).to.eql(0);
      expect(linearFindNearest(arr, 750, -1)).to.eql(1);

      expect(linearFindNearest(arr, 550, 0)).to.eql(1);
      expect(linearFindNearest(arr, 550, 1)).to.eql(0);
      expect(linearFindNearest(arr, 550, -1)).to.eql(1);

      expect(linearFindNearest(arr, 500, 0)).to.eql(1);
      expect(linearFindNearest(arr, 500, 1)).to.eql(1);
      expect(linearFindNearest(arr, 500, -1)).to.eql(1);

      expect(linearFindNearest(arr, 450, 0)).to.eql(1);
      expect(linearFindNearest(arr, 450, 1)).to.eql(1);
      expect(linearFindNearest(arr, 450, -1)).to.eql(2);

      expect(linearFindNearest(arr, 300, 0)).to.eql(2);
      expect(linearFindNearest(arr, 300, 1)).to.eql(1);
      expect(linearFindNearest(arr, 300, -1)).to.eql(2);

      expect(linearFindNearest(arr, 200, 0)).to.eql(2);
      expect(linearFindNearest(arr, 200, 1)).to.eql(1);
      expect(linearFindNearest(arr, 200, -1)).to.eql(2);

      expect(linearFindNearest(arr, 100, 0)).to.eql(2);
      expect(linearFindNearest(arr, 100, 1)).to.eql(2);
      expect(linearFindNearest(arr, 100, -1)).to.eql(2);

      expect(linearFindNearest(arr, 50, 0)).to.eql(2);
      expect(linearFindNearest(arr, 50, 1)).to.eql(2);
      expect(linearFindNearest(arr, 50, -1)).to.eql(2);
    });
  });

  describe('numberSafeCompareFunction', function () {
    it('sorts as expected', function () {
      const arr = [40, 200, 3000];
      // default sort would yield [200, 3000, 40]
      arr.sort(numberSafeCompareFunction);
      expect(arr).to.eql(arr);
    });
  });

  describe('remove', function () {
    it('removes elements from an array', function () {
      const a = ['a', 'b', 'c', 'd'];
      remove(a, 'c');
      expect(a).to.eql(['a', 'b', 'd']);
      remove(a, 'x');
      expect(a).to.eql(['a', 'b', 'd']);
    });
  });

  describe('reverseSubArray', function () {
    it('returns expected value', function () {
      let arr;
      const expected = [1, 2, 3, 4, 5, 6];

      arr = [1, 5, 4, 3, 2, 6];
      reverseSubArray(arr, 1, 4);
      expect(arr).to.eql(expected);

      arr = [3, 2, 1, 4, 5, 6];
      reverseSubArray(arr, 0, 2);
      expect(arr).to.eql(expected);

      arr = [1, 2, 3, 6, 5, 4];
      reverseSubArray(arr, 3, 5);
      expect(arr).to.eql(expected);

      arr = [6, 5, 4, 3, 2, 1];
      reverseSubArray(arr, 0, 5);
      expect(arr).to.eql(expected);
    });
  });

  describe('stableSort', function () {
    let arr, wantedSortedValues;

    beforeEach(function () {
      arr = [
        {key: 3, val: 'a'},
        {key: 2, val: 'b'},
        {key: 3, val: 'c'},
        {key: 4, val: 'd'},
        {key: 3, val: 'e'},
      ];
      wantedSortedValues = ['b', 'a', 'c', 'e', 'd'];
    });

    it('works on an array with custom comparison function', function () {
      function comparisonFn(obj1, obj2) {
        return obj1.key - obj2.key;
      }
      stableSort(arr, comparisonFn);
      const sortedValues = [];
      for (let i = 0; i < arr.length; i++) {
        sortedValues.push(arr[i].val);
      }
      expect(wantedSortedValues).to.eql(sortedValues);
    });
  });
});
<commit_msg>Array test already run in node<commit_after><|endoftext|>


<commit_before>/**
 * Created by dantegg on 17-1-4.
 */
import React,{Component} from 'react'
// import {PrismCode} from 'react-prism'
import homeStyle from '../css/home.css'
//import ReactMarkdown from 'react-markdown'
import {Button} from 'antd'
//import QueueAnim from 'rc-queue-anim'
import Animate from 'rc-animate'
import Head from './head'
import marked from 'marked'

export default class Test extends Component{
    constructor(props){
        super(props)
        this.state={
            showSlogan:true
        }
    }
    componentDidMount(){
    }

    onEnter(){
        this.setState({
            showSlogan:false
        })
    }

    go2blog(id){
        console.log('blog',id)
        window.location.href='/blog/'+id
    }

    render(){
            let comp = this
            return(

                    <Animate showProp="visible" transitionName="fade-leave">
                        {this.state.showSlogan ?

吾生也有涯，而知也无涯，以有涯随无涯，殆已

——— 庄子

                                <Button type="ghost" onClick={this.onEnter.bind(this)} key="3">进入</Button>

:null
                        }
                    </Animate>
                    <Animate showProp="visible" transitionName="fade-enter">

                        {!this.state.showSlogan ?

                                {this.props.welcomeInfo.map(x=>{
                                    {/*let newdate = new Date()*/}
                                    {/*newdate.setTime(x.createTime)*/}
                                    //console.log(newdate.toLocaleDateString())
                                    return(

this.go2blog(x.id)}>

{x.title}

{x.createTime}

                                            {/*<ReactMarkdown source={x.content} key="4"/>*/}
                                                {/*{marked(x.content)}*/}

                                    )
                                })}

:null
                        }

                    </Animate>

            )
    }
}<commit_msg>update<commit_after>/**
 * Created by dantegg on 17-1-4.
 */
import React,{Component} from 'react'
// import {PrismCode} from 'react-prism'
import homeStyle from '../css/home.css'
//import ReactMarkdown from 'react-markdown'
import {Button,Icon} from 'antd'
//import QueueAnim from 'rc-queue-anim'
import Animate from 'rc-animate'
import Head from './head'
import marked from 'marked'

export default class Test extends Component{
    constructor(props){
        super(props)
        this.state={
            showSlogan:true
        }
    }
    componentDidMount(){
    }

    onEnter(){
        this.setState({
            showSlogan:false
        })
    }

    go2blog(id){
        console.log('blog',id)
        window.location.href='/blog/'+id
    }

    render(){
            let comp = this
            return(

                        <Icon type="github" style={{cursor:'pointer'}} onClick={function () {
                            window.open('https://github.com/dantegg')
                        }}/>

                    <Animate showProp="visible" transitionName="fade-leave">
                        {this.state.showSlogan ?

吾生也有涯，而知也无涯，以有涯随无涯，殆已

——— 庄子

                                <Button type="ghost" onClick={this.onEnter.bind(this)} key="3">进入</Button>

:null
                        }
                    </Animate>
                    <Animate showProp="visible" transitionName="fade-enter">

                        {!this.state.showSlogan ?

                                {this.props.welcomeInfo.map(x=>{
                                    {/*let newdate = new Date()*/}
                                    {/*newdate.setTime(x.createTime)*/}
                                    //console.log(newdate.toLocaleDateString())
                                    return(

this.go2blog(x.id)}>

{x.title}

{x.createTime}

                                            {/*<ReactMarkdown source={x.content} key="4"/>*/}
                                                {/*{marked(x.content)}*/}

                                    )
                                })}

                                    more

                                    2017

:null
                        }

                    </Animate>

            )
    }
}<|endoftext|>