repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
khalifagroup/vscode-docker
src/utils/platform.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ export type PlatformOS = 'Windows' | 'Linux'; export type Platform = 'Node.js' | '.NET: ASP.NET Core' | '.NET: Core Console' | 'Python: Django' | 'Python: Flask' | 'Python: General' | 'Java' | 'C++' | 'Go' | 'Ruby' | 'Other';
khalifagroup/vscode-docker
src/debugging/DebugHelper.ts
<gh_stars>0 /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationToken, debug, DebugConfiguration, ExtensionContext, workspace, WorkspaceFolder } from 'vscode'; import { IActionContext, registerCommand } from 'vscode-azureextensionui'; import { initializeForDebugging } from '../commands/debugging/initializeForDebugging'; import { DockerRunTaskDefinition } from '../tasks/DockerRunTaskProvider'; import { DockerTaskScaffoldContext, getDefaultContainerName } from '../tasks/TaskHelper'; import ChildProcessProvider from './coreclr/ChildProcessProvider'; import CliDockerClient from './coreclr/CliDockerClient'; import { DockerServerReadyAction } from './DockerDebugConfigurationBase'; import { DockerDebugConfiguration, DockerDebugConfigurationProvider } from './DockerDebugConfigurationProvider'; import { DockerPlatform } from './DockerPlatformHelper'; import { registerServerReadyAction } from './DockerServerReadyAction'; import { netCoreDebugHelper } from './netcore/NetCoreDebugHelper'; import { nodeDebugHelper } from './node/NodeDebugHelper'; import { pythonDebugHelper } from './python/PythonDebugHelper'; export interface DockerDebugContext { // Same as DockerTaskContext but intentionally does not extend it, since we never need to pass a DockerDebugContext to tasks folder: WorkspaceFolder; platform: DockerPlatform; actionContext: IActionContext; cancellationToken?: CancellationToken; runDefinition?: DockerRunTaskDefinition; } /* eslint-disable-next-line @typescript-eslint/no-empty-interface */ export interface DockerDebugScaffoldContext extends DockerTaskScaffoldContext { } export interface ResolvedDebugConfigurationOptions { containerNameToKill?: string; dockerServerReadyAction?: DockerServerReadyAction; removeContainerAfterDebug?: boolean; } export interface ResolvedDebugConfiguration extends DebugConfiguration { dockerOptions?: ResolvedDebugConfigurationOptions; } export interface DebugHelper { provideDebugConfigurations(context: DockerDebugScaffoldContext): Promise<DockerDebugConfiguration[]>; resolveDebugConfiguration(context: DockerDebugContext, debugConfiguration: DockerDebugConfiguration): Promise<ResolvedDebugConfiguration | undefined>; } export function registerDebugProvider(ctx: ExtensionContext): void { ctx.subscriptions.push( debug.registerDebugConfigurationProvider( 'docker', new DockerDebugConfigurationProvider( new CliDockerClient(new ChildProcessProvider()), { netCore: netCoreDebugHelper, node: nodeDebugHelper, python: pythonDebugHelper, } ) ) ); registerServerReadyAction(ctx); registerCommand('vscode-docker.debugging.initializeForDebugging', initializeForDebugging); } // TODO: This is stripping out a level of indentation, but the tasks one isn't export async function addDebugConfiguration(newConfig: DockerDebugConfiguration, overwrite: boolean | undefined): Promise<boolean> { // Using config API instead of tasks API means no wasted perf on re-resolving the tasks, and avoids confusion on resolved type !== true type const workspaceLaunch = workspace.getConfiguration('launch'); const allConfigs = workspaceLaunch && workspaceLaunch.configurations as DebugConfiguration[] || []; const existingConfigIndex = allConfigs.findIndex(c => c.name === newConfig.name); if (existingConfigIndex >= 0) { // If a task of the same label exists already if (overwrite) { // If overwriting, do so allConfigs[existingConfigIndex] = newConfig; } else { // If not overwriting, return false return false; } } else { allConfigs.push(newConfig); } await workspaceLaunch.update('configurations', allConfigs); return true; } export function inferContainerName(debugConfiguration: DockerDebugConfiguration, context: DockerDebugContext, defaultNameHint: string, defaultTag?: 'dev' | 'latest'): string { return (debugConfiguration && debugConfiguration.containerName) || (context && context.runDefinition && context.runDefinition.dockerRun && context.runDefinition.dockerRun.containerName) || getDefaultContainerName(defaultNameHint, defaultTag); } export function resolveDockerServerReadyAction(debugConfiguration: DockerDebugConfiguration, defaultDockerSRA: DockerServerReadyAction, createIfUserUndefined: boolean): DockerServerReadyAction | undefined { let numBrowserOptions = [debugConfiguration.launchBrowser, debugConfiguration.serverReadyAction, debugConfiguration.dockerServerReadyAction].filter(item => item !== undefined).length; if (numBrowserOptions > 1) { // Multiple user-provided options is not valid throw new Error(`Only at most one of the 'launchBrowser', 'serverReadyAction', and 'dockerServerReadyAction' properties may be set at a time.`); } else if (numBrowserOptions === 1 && !debugConfiguration.dockerServerReadyAction) { // One user-provided option that is not DockerServerReadyAction--return nothing return undefined; } else if (numBrowserOptions === 0 && !createIfUserUndefined) { // No user-provided option, and not creating if nothing user-defined--return nothing return undefined } // Otherwise create one based on user-defined and default options const providedDockerSRA = debugConfiguration.dockerServerReadyAction || {}; return { containerName: providedDockerSRA.containerName || defaultDockerSRA.containerName, pattern: providedDockerSRA.pattern || defaultDockerSRA.pattern, action: providedDockerSRA.action || defaultDockerSRA.action, uriFormat: providedDockerSRA.uriFormat || defaultDockerSRA.uriFormat, webRoot: providedDockerSRA.webRoot || defaultDockerSRA.webRoot, }; }
khalifagroup/vscode-docker
test/telemetry/TelemetryPublisher.test.ts
<gh_stars>0 /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { TelemetryPublisher } from '../../extension.bundle'; suite('telemetry/TelemetryPublisher', () => { test('Listeners are notified of published events', () => { const eventName = 'event'; const measurements = {}; const properties = {}; let wasPublished = false; const publisher = new TelemetryPublisher(); publisher.onEvent( e => { assert.equal(e.eventName, eventName); assert.equal(e.measurements, measurements); assert.equal(e.properties, properties); wasPublished = true; }); publisher.publishEvent({ eventName, measurements, properties }); assert(wasPublished); }); });
khalifagroup/vscode-docker
src/configureWorkspace/configurePython.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as fse from 'fs-extra'; import * as path from "path"; import vscode = require('vscode'); import { TelemetryProperties } from 'vscode-azureextensionui'; import { DockerDebugScaffoldContext } from '../debugging/DebugHelper'; import { dockerDebugScaffoldingProvider, PythonScaffoldingOptions } from '../debugging/DockerDebugScaffoldingProvider'; import { ext } from "../extensionVariables"; import { PythonExtensionHelper } from '../tasks/python/PythonExtensionHelper'; import { getPythonProjectType, inferPythonArgs, PythonDefaultDebugPort, PythonDefaultPorts, PythonFileExtension, PythonFileTarget, PythonModuleTarget, PythonProjectType, PythonTarget } from "../utils/pythonUtils"; import { getComposePorts, getExposeStatements } from './configure'; import { ConfigureTelemetryProperties, genCommonDockerIgnoreFile, quickPickGenerateComposeFiles } from './configUtils'; import { ScaffolderContext, ScaffoldFile } from './scaffolding'; interface LaunchFilePrompt { prompt: string, defaultFile: string } const defaultLaunchFile: Map<PythonProjectType, LaunchFilePrompt> = new Map<PythonProjectType, LaunchFilePrompt>([ ['django', { prompt: 'Enter the relative path to the application (e.g. manage.py)', defaultFile: 'manage.py' }], ['flask', { prompt: 'Enter the relative path to the application (e.g. \'app.py\' or \'app\')', defaultFile: 'app.py' }], ['general', { prompt: 'Enter the relative path to the application (e.g. \'app.py\' or \'app\')', defaultFile: 'app.py' }], ]); const pythonDockerfile = `# For more information, please refer to https://aka.ms/vscode-docker-python FROM python $expose_statements$ # Install pip requirements ADD requirements.txt . RUN python -m pip install -r requirements.txt WORKDIR /app ADD . /app $cmd$ `; const dockerComposefile = `version: '3.4' services: $service_name$: image: $service_name$ build: context: . dockerfile: Dockerfile $ports$`; const dockerComposeDebugfile = `version: '3.4' services: $service_name$: image: $service_name$ build: context: . dockerfile: Dockerfile $dbg_volume$ entrypoint: $entrypoint$ $ports$`; const djangoRequirements = `django gunicorn`; const flaskRequirements = `flask gunicorn`; function genDockerFile(serviceName: string, target: PythonTarget, projectType: PythonProjectType, ports: number[]): string { const exposeStatements = getExposeStatements(ports); let command = ''; if (projectType === 'general') { if ((target as PythonFileTarget).file) { command = `CMD ["python", "${(target as PythonFileTarget).file}"]`; } else { command = `CMD ["python", "-m", "${(target as PythonModuleTarget).module}"]`; } } else if (projectType === 'django') { // For Django apps, there **usually** exists a "wsgi" module, so our best guess is to use the folder name. command = `CMD ["gunicorn", "--bind", "0.0.0.0:${ports ? ports[0] : PythonDefaultPorts[projectType]}", "${serviceName}.wsgi"]`; } else if (projectType === 'flask') { // For Flask apps, our guess is to assume there is a callable "app" object in the file/module that the user provided. command = `CMD ["gunicorn", "--bind", "0.0.0.0:${ports ? ports[0] : PythonDefaultPorts[projectType]}", "${inferPythonWsgiModule(target)}:app"]`; } else { // Unlikely throw new Error(`Unknown project type: ${projectType}`); } return pythonDockerfile .replace(/\$expose_statements\$/g, exposeStatements) .replace(/\$cmd\$/g, command); } function genDockerCompose(serviceName: string, ports: number[]): string { return dockerComposefile .replace(/\$service_name\$/g, serviceName) .replace(/\$ports\$/g, getComposePorts(ports)); } async function genDockerComposeDebug(serviceName: string, projectType: PythonProjectType, ports: number[], target: PythonTarget): Promise<string> { const defaultDebugOptions : PythonExtensionHelper.DebugLaunchOptions = { host: '0.0.0.0', port: PythonDefaultDebugPort, wait: true }; const args = inferPythonArgs(projectType, ports); const launcherCommand = PythonExtensionHelper.getRemotePtvsdCommand(target, args, defaultDebugOptions); const entrypoint = 'python '.concat(launcherCommand); const launcherFolder = await PythonExtensionHelper.getLauncherFolderPath(); let dbgVolume : string = ''; if (launcherFolder) { dbgVolume = ` volumes:\n - ${launcherFolder}:/pydbg`; } return dockerComposeDebugfile .replace(/\$service_name\$/g, serviceName) .replace(/\$dbg_volume\$/g, dbgVolume) .replace(/\$entrypoint\$/g, entrypoint) .replace(/\$ports\$/g, getComposePorts(ports, PythonDefaultDebugPort)); } function genRequirementsFile(projectType: PythonProjectType): string { let contents = '# Add requirements when needed' switch (projectType) { case 'django': contents = djangoRequirements; break; case 'flask': contents = flaskRequirements break; default: } return contents; } async function initializeForDebugging(context: ScaffolderContext, dockerfile: string, ports: number[], generateComposeFiles: boolean, target: PythonTarget, projectType: PythonProjectType): Promise<void> { const scaffoldContext: DockerDebugScaffoldContext = { folder: context.folder, platform: 'python', actionContext: context, dockerfile: dockerfile, generateComposeTask: generateComposeFiles, ports: ports } const pyOptions: PythonScaffoldingOptions = { projectType: projectType, target: target } await dockerDebugScaffoldingProvider.initializePythonForDebugging(scaffoldContext, pyOptions); } function inferPythonWsgiModule(target: PythonTarget): string { let wsgiModule: string; if ('module' in target) { wsgiModule = target.module; } else if ('file' in target) { // Get rid of the file extension. wsgiModule = target.file.replace(/\.[^/.]+$/, ''); } // Replace forward-slashes with dots. return wsgiModule.replace(/\//g, '.'); } export async function promptForLaunchFile(projectType?: PythonProjectType) : Promise<PythonTarget> { const launchFilePrompt = defaultLaunchFile.get(projectType); const opt: vscode.InputBoxOptions = { placeHolder: launchFilePrompt.defaultFile, prompt: launchFilePrompt.prompt, value: launchFilePrompt.defaultFile, validateInput: (value: string): string | undefined => { return value && value.trim().length > 0 ? undefined : 'Enter a valid Python file path/module.' } }; const file = await ext.ui.showInputBox(opt); // If the input has the .py extension, then assume it is a file. if (path.extname(file).toLocaleUpperCase() === PythonFileExtension.toLocaleUpperCase()) { return { file: file.replace(/\\/g, '/') }; } else { return { module: file}; } } export async function scaffoldPython(context: ScaffolderContext): Promise<ScaffoldFile[]> { const properties: TelemetryProperties & ConfigureTelemetryProperties = context.telemetry.properties; const serviceName = context.folder.name; const rootFolderPath: string = context.rootFolder; const outputFolder = context.outputFolder ?? rootFolderPath; const generateComposeFiles = await context.captureStep('compose', quickPickGenerateComposeFiles)(); const projectType = getPythonProjectType(context.platform); const defaultPort = PythonDefaultPorts.get(projectType); let ports = []; if (defaultPort) { ports = await context.promptForPorts([ defaultPort ]); } const launchFile = await context.captureStep('pythonFile', promptForLaunchFile)(projectType); const dockerFileContents = genDockerFile(serviceName, launchFile, projectType, ports); const files: ScaffoldFile[] = [ { fileName: 'Dockerfile', contents: dockerFileContents, open: true }, { fileName: '.dockerignore', contents: genCommonDockerIgnoreFile(context.platform) } ]; const requirementsFileExists = await fse.pathExists(path.join(outputFolder, 'requirements.txt')); if (!requirementsFileExists) { files.push({ fileName: 'requirements.txt', contents: genRequirementsFile(projectType) }); } if (generateComposeFiles) { properties.orchestration = 'docker-compose'; const dockerComposeFile = genDockerCompose(serviceName, ports); const dockerComposeDebugFile = await genDockerComposeDebug(serviceName, projectType, ports, launchFile); files.push( { fileName: 'docker-compose.yml', contents: dockerComposeFile }, { fileName: 'docker-compose.debug.yml', contents: dockerComposeDebugFile }); } files.forEach(file => { // Remove multiple empty lines with single empty lines, as might be produced // if $expose_statements$ or another template variable is an empty string. file.contents = file.contents .replace(/(\r\n){3,4}/g, '\r\n\r\n') .replace(/(\n){3,4}/g, '\n\n'); }); if (context.initializeForDebugging) { await initializeForDebugging(context, path.join(outputFolder, 'Dockerfile'), ports, generateComposeFiles, launchFile, projectType); } return files; }
khalifagroup/vscode-docker
extension.bundle.ts
<gh_stars>1-10 /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ /** * This is the external face of extension.bundle.js, the main webpack bundle for the extension. * Anything needing to be exposed outside of the extension sources must be exported from here, because * everything else will be in private modules in extension.bundle.js. */ // Export activate and deactivate for main.js export { activateInternal } from './src/extension'; export { deactivateInternal } from './src/extension'; // Exports for tests // The tests are not packaged with the webpack bundle and therefore only have access to code exported from this file. // // The tests should import '../extension.bundle.ts'. At design-time they live in tests/ and so will pick up this file (extension.bundle.ts). // At runtime the tests live in dist/tests and will therefore pick up the main webpack bundle at dist/extension.bundle.js. export { configure, ConfigureApiOptions } from './src/configureWorkspace/configure'; export { splitPorts } from './src/configureWorkspace/configUtils'; export { configPrefix } from './src/constants'; export { ProcessProvider } from './src/debugging/coreclr/ChildProcessProvider'; export { DockerBuildImageOptions, DockerClient } from './src/debugging/coreclr/CliDockerClient'; export { CommandLineBuilder } from './src/utils/commandLineBuilder'; export { DotNetClient } from './src/debugging/coreclr/CommandLineDotNetClient'; export { compareBuildImageOptions, LaunchOptions } from './src/debugging/coreclr/dockerManager'; export { FileSystemProvider } from './src/debugging/coreclr/fsProvider'; export { LineSplitter } from './src/debugging/coreclr/lineSplitter'; export { OSProvider } from './src/debugging/coreclr/LocalOSProvider'; export { DockerDaemonIsLinuxPrerequisite, DockerfileExistsPrerequisite, DotNetSdkInstalledPrerequisite, LinuxUserInDockerGroupPrerequisite, MacNuGetFallbackFolderSharedPrerequisite } from './src/debugging/coreclr/prereqManager'; export { ext } from './src/extensionVariables'; export { globAsync } from './src/utils/globAsync'; export { httpsRequestBinary } from './src/utils/httpRequest'; export { IKeytar } from './src/utils/keytar'; export { inferCommand, inferPackageName, InspectMode, NodePackage } from './src/utils/nodeUtils'; export { nonNullProp } from './src/utils/nonNull'; export { getDockerOSType, isWindows10RS3OrNewer, isWindows10RS4OrNewer, isWindows10RS5OrNewer, isWindows1019H1OrNewer } from "./src/utils/osUtils"; export { Platform, PlatformOS } from './src/utils/platform'; export { DefaultTerminalProvider } from './src/utils/TerminalProvider'; export { trimWithElipsis } from './src/utils/trimWithElipsis'; export { recursiveFindTaskByType } from './src/tasks/TaskHelper'; export { TaskDefinitionBase } from './src/tasks/TaskDefinitionBase'; export { DebugConfigurationBase } from './src/debugging/DockerDebugConfigurationBase'; export { TelemetryPublisher } from './src/telemetry/TelemetryPublisher'; export { TelemetryReporterProxy } from './src/telemetry/TelemetryReporterProxy'; export { ITelemetryPublisher, TelemetryEvent } from './src/telemetry/TelemetryPublisher'; export { activeUseSurvey } from './src/telemetry/surveys/activeUseSurvey'; export * from 'vscode-azureextensionui';
khalifagroup/vscode-docker
test/telemetry/surveys/activeUseSurvey.test.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import * as vscode from 'vscode'; import { activeUseSurvey } from '../../../extension.bundle'; import { TelemetryEvent } from '../../../extension.bundle'; import { ITelemetryPublisher } from '../../../src/telemetry/TelemetryPublisher'; interface TelemetryEventData { date: string; event: TelemetryEvent; }; interface TestOptions { activationDate: string; lastUseDate?: string; isCandidate?: boolean; isSelected?: boolean; isChosenLanguage?: boolean; promptResponse?: boolean; preActivationTelemetry?: TelemetryEventData[]; postActivationTelemetry?: TelemetryEventData[]; } suite('telemetry/surveys/activeUseSurvey', () => { const lastUseDateKey = 'telemetry.surveys.activeUseSurvey.lastUseDate'; const isCandidateKey = 'telemetry.surveys.activeUseSurvey.isCandidate'; function buildTest(name: string, options: TestOptions) { test(name, async () => { const eventPublisher = new vscode.EventEmitter<TelemetryEvent>() const publisher: ITelemetryPublisher = { onEvent: eventPublisher.event, publishEvent: undefined }; const lastUseDateUpdates = []; const isCandidateUpdates = []; const state: vscode.Memento = { get: (key, defaultValue = undefined) => { switch (key) { case lastUseDateKey: return options.lastUseDate ?? defaultValue; case isCandidateKey: return options.isCandidate ?? defaultValue; } return defaultValue; }, update: (key, value) => { switch (key) { case lastUseDateKey: lastUseDateUpdates.push(value); break; case isCandidateKey: isCandidateUpdates.push(value); break; } return Promise.resolve(); } } let wasSelected = false; let wasPrompted = false; let wasOpened = false; const selector = () => { wasSelected = true; return options.isSelected; }; const surveyPrompt = () => { wasPrompted = true; return Promise.resolve(options.promptResponse); }; const surveyOpen = () => { wasOpened = true; return Promise.resolve(); } const nonActivationPostActivationTelemetry = (options.postActivationTelemetry ?? []).filter(telemetry => telemetry.event.properties?.isActivationEvent !== 'true'); const dates = [ new Date(options.activationDate), ...(options.preActivationTelemetry ?? []).map(event => new Date(event.date)), ...nonActivationPostActivationTelemetry.map(event => new Date(event.date)) ]; const clock = () => { return dates.shift(); }; const survey = activeUseSurvey( 10, clock, () => options.isChosenLanguage ?? true, publisher, selector, state, surveyPrompt, surveyOpen); if (options.preActivationTelemetry) { options.preActivationTelemetry.forEach(telemetry => eventPublisher.fire(telemetry.event)); } await survey.postActivationTask; if (options.postActivationTelemetry) { options.postActivationTelemetry.forEach(telemetry => eventPublisher.fire(telemetry.event)); } // If this was the first activation, the "last use" should be set to the activation date. if (options.lastUseDate === undefined) { assert(lastUseDateUpdates.length === 1 && lastUseDateUpdates[0] === options.activationDate); } // If the user is a known candidate, she should not go through the selection process. if (options.isCandidate !== undefined) { assert(!wasSelected); } // If the user was selected, their candidicy should first be saved. if (options.isCandidate === undefined && options.isSelected !== undefined) { assert(isCandidateUpdates.length > 0 && isCandidateUpdates[0] === options.isSelected); } // If the user responded, their candidicy should lastly be revoked. if (options.promptResponse !== undefined) { assert(isCandidateUpdates.length > 0 && isCandidateUpdates[isCandidateUpdates.length - 1] === false); } // The last use update should be the last non-activation-event telemetry date. if (nonActivationPostActivationTelemetry.length > 0) { assert(lastUseDateUpdates.length > 0 && lastUseDateUpdates[lastUseDateUpdates.length - 1] === nonActivationPostActivationTelemetry[nonActivationPostActivationTelemetry.length - 1].date); } assert((options.isSelected !== undefined && wasSelected) || (options.isSelected === undefined && !wasSelected)); assert((options.promptResponse !== undefined && wasPrompted) || (options.promptResponse === undefined && !wasPrompted)); assert((options.promptResponse === true && wasOpened) || (options.promptResponse !== true && !wasOpened)); }); } buildTest('First activation, no use', { activationDate: '2020-01-24' }); buildTest('Activation, no use, previous use within limits', { activationDate: '2020-01-24', lastUseDate: '2020-01-03' }); buildTest('Activation, no use, previous use within limits, with post non-activation events', { activationDate: '2020-01-20', lastUseDate: '2020-01-03', postActivationTelemetry: [{date: '2020-01-21', event: { eventName: 'docker-build' } }, {date: '2020-01-22', event: { eventName: 'docker-build' } }] }); buildTest('Activation, no use, previous use within limits, with post activation events', { activationDate: '2020-01-20', lastUseDate: '2020-01-03', postActivationTelemetry: [{date: '2020-01-21', event: { eventName: 'docker-build', properties: { 'isActivationEvent': 'true' } } }] }); buildTest('Activation, no use, previous use outside limits, not candidate', { activationDate: '2020-01-24', lastUseDate: '2020-01-01', isCandidate: false }); buildTest('Activation, no use, previous use outside limits, candidate, negative response', { activationDate: '2020-01-24', lastUseDate: '2020-01-01', isCandidate: true, promptResponse: false }); buildTest('Activation, no use, previous use outside limits, candidate, positive response', { activationDate: '2020-01-24', lastUseDate: '2020-01-01', isCandidate: true, promptResponse: true }); buildTest('Activation, no use, previous use outside limits, unknown candidate, not selected', { activationDate: '2020-01-24', lastUseDate: '2020-01-01', isSelected: false }); buildTest('Activation, no use, previous use outside limits, unknown candidate, selected, non-native language', { activationDate: '2020-01-24', lastUseDate: '2020-01-01', isSelected: true, isChosenLanguage: false }); buildTest('Activation, no use, previous use outside limits, unknown candidate, selected, negative response', { activationDate: '2020-01-24', lastUseDate: '2020-01-01', isSelected: true, promptResponse: false }); buildTest('Activation, no use, previous use outside limits, unknown candidate, selected, positive response', { activationDate: '2020-01-24', lastUseDate: '2020-01-01', isSelected: true, promptResponse: true }); buildTest('Activation, no use, previous use at limits, unknown candidate, selected, positive response', { activationDate: '2020-01-23', lastUseDate: '2020-01-01', isSelected: true, promptResponse: true }); });
thisisviniciosilva/ignite
tests/main-test-02-hook/src/types.ts
<gh_stars>1-10 export interface Product { id: number; title: string; price: number; image: string; amount: number; } export interface Stock { id: number; amount: number; }
thisisviniciosilva/ignite
tests/main-test-02-hook/src/pages/Cart/styles.ts
import styled from 'styled-components'; import { darken, lighten } from 'polished'; export const Container = styled.div` padding: 30px; background: #fff; border-radius: 4px; footer { margin-top: 30px; display: flex; justify-content: space-between; align-items: center; button { background: #7159c1; color: #fff; border: 0; border-radius: 4px; padding: 12px 20px; font-weight: bold; text-transform: uppercase; transition: background 0.2s; &:hover { background: ${darken(0.06, '#7159c1')}; } } } `; export const ProductTable = styled.table` width: 100%; thead th { color: #999; text-align: left; padding: 12px; } tbody td { padding: 12px; border-bottom: 1px solid #eee; } img { height: 100px; } strong { color: #333; display: block; } span { display: block; margin-top: 5px; font-size: 18px; font-weight: bold; } div { display: flex; align-items: center; input { border: 1px solid #ddd; border-radius: 4px; color: #666; padding: 6px; width: 50px; } } button { background: none; border: 0; padding: 6px; svg { color: #7159c1; transition: color 0.2s; } &:hover { svg { color: ${darken(0.06, '#7159c1')}; } } &:disabled { svg { color: ${lighten(0.25, '#7159c1')}; cursor: not-allowed; } } } `; export const Total = styled.div` display: flex; align-items: baseline; span { color: #999; font-weight: bold; } strong { font-size: 28px; margin-left: 5px; } `;
kenko-apps/oncosafe
src/validators/questionTabac.ts
import { FormGroup } from '@angular/forms'; export class TabacValidator { static isValid(group: FormGroup): any { var userTabac = group.controls.tabac_check.value; var frequenceTabac = group.controls.frequence_tabac.value; var dateTabac = group.controls.date_tabac.value; if(userTabac =="oui"){ if (dateTabac =="" || frequenceTabac ==""){ if (dateTabac =="" && frequenceTabac ==""){ group.controls.date_tabac.setErrors({"date_empty": true}); group.controls.frequence_tabac.setErrors({"freq_empty": true}); return { "empty": true }; } if(dateTabac ==""){ group.controls.date_tabac.setErrors({"date_empty": true}); return { "empty": true }; } if(frequenceTabac ==""){ group.controls.frequence_tabac.setErrors({"freq_empty": true}); return { "empty": true }; } }else{ return null; } } } }
kenko-apps/oncosafe
src/validators/questionTherapie.ts
<gh_stars>0 import { FormGroup } from '@angular/forms'; export class TherapieValidator { static isValid(group: FormGroup): any { var therapies = group.controls.therapies_check.value; var phytotherapie = group.controls.phytotherapie.value; var extrait = group.controls.extrait.value; var homeopathie = group.controls.homeopathie.value; var acupuncture = group.controls.acupuncture.value; var aromatherapie = group.controls.aromatherapie.value; var autres = group.controls.autres.value; var autres_text = group.controls.autres_text.value; if(therapies =="oui"){ if (autres && autres_text==''){ group.controls.autres_text.setErrors({"autres_empty": true}); } if (!phytotherapie && !extrait && !homeopathie && !acupuncture && !aromatherapie && !autres){ return { "empty": true }; }else{ return null; } } } }
kenko-apps/oncosafe
src/pages/formulaire-quatre/formulaire-quatre.ts
import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { Component } from '@angular/core'; import { MenuController, NavController } from 'ionic-angular'; import { TranslateService } from '@ngx-translate/core'; import { TherapieValidator } from '../../validators/questionTherapie' import { FormulaireResultat } from '../formulaire-resultat/formulaire-resultat'; import { FormulairePageCinq } from '../formulaire-cinq/formulaire-cinq'; @Component({ selector: 'formulaire-quatre', templateUrl: 'formulaire-quatre.html' }) export class FormulairePageQuatre { slideQuatreForm: FormGroup; submitAttempt: boolean = false; questionsTherapie: boolean = false; checkAutres: boolean = false; constructor(public navCtrl: NavController, public menu: MenuController, translate: TranslateService, public formBuilder: FormBuilder) { this.slideQuatreForm = formBuilder.group({ therapies_check: ['',Validators.required], phytotherapie: [false], extrait: [false], homeopathie: [false], acupuncture: [false], aromatherapie: [false], autres: [false], autres_text: [''] },{ validator: TherapieValidator.isValid}); } therapieOui() { this.questionsTherapie = true; } therapieNon() { this.questionsTherapie = false; this.slideQuatreForm.controls.phytotherapie.setValue(false); this.slideQuatreForm.controls.extrait.setValue(false); this.slideQuatreForm.controls.homeopathie.setValue(false); this.slideQuatreForm.controls.acupuncture.setValue(false); this.slideQuatreForm.controls.aromatherapie.setValue(false); this.slideQuatreForm.controls.autres.setValue(false); this.slideQuatreForm.controls.autres_text.setValue(''); } autres(){ if(this.checkAutres == false){ this.checkAutres = true; }else{ this.checkAutres = false; this.slideQuatreForm.controls.autres.setValue(false); this.slideQuatreForm.controls.autres_text.setValue(''); } } nextPage() { this.submitAttempt = true; if(this.slideQuatreForm.valid){ if (this.slideQuatreForm.controls.phytotherapie.value){ this.navCtrl.push(FormulairePageCinq); }else{ this.navCtrl.push(FormulaireResultat); } console.log("success!"); console.log(this.slideQuatreForm.value); } } }
kenko-apps/oncosafe
src/pages/formulaire-un/formulaire-un.ts
import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { Component } from '@angular/core'; import { MenuController, NavController } from 'ionic-angular'; import { TranslateService } from '@ngx-translate/core'; import { FormulairePageDeux } from '../formulaire-deux/formulaire-deux'; @Component({ selector: 'formulaire-un', templateUrl: 'formulaire-un.html' }) export class FormulairePageUn { slideUnForm: FormGroup; submitAttempt: boolean = false; constructor(public navCtrl: NavController, public menu: MenuController, translate: TranslateService, public formBuilder: FormBuilder) { this.slideUnForm = formBuilder.group({ prenom: ['', Validators.compose([Validators.maxLength(30), Validators.pattern('([a-zA-Zéèêëàäâùüûïîöôçÿ ]*)([\-]?)([a-zA-Zéèêëàäâùüûïîöôçÿ ]*)'), Validators.required])], nom: ['', Validators.compose([Validators.maxLength(30), Validators.pattern('([a-zA-Zéèêëàäâùüûïîöôçÿ ]*)([\-]?)([a-zA-Zéèêëàäâùüûïîöôçÿ ]*)'), Validators.required])], date_naissance: ['', Validators.required], onco_ref: ['', Validators.compose([Validators.maxLength(30), Validators.pattern('([a-zA-Zéèêëàäâùüûïîöôçÿ. ]*)([\-]?)([a-zA-Zéèêëàäâùüûïîöôçÿ ]*)')])], }); } nextPage() { this.submitAttempt = true; if(this.slideUnForm.valid){ this.navCtrl.push(FormulairePageDeux); console.log("success!") console.log(this.slideUnForm.value); } } }
kenko-apps/oncosafe
src/pages/choix/choix.ts
import { WelcomePage } from './../welcome/welcome'; import { FirstRunPage } from './../pages'; import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; /** * The Welcome Page is a splash page that quickly describes the app, * and then directs the user to create an account or log in. * If you'd like to immediately put the user onto a login/signup page, * we recommend not using the Welcome page. */ @Component({ selector: 'page-choix', templateUrl: 'choix.html' }) export class ChoixPage { constructor(public navCtrl: NavController) { } lancerDemo() { this.navCtrl.push(FirstRunPage); } lancerAppli() { this.navCtrl.push(WelcomePage); } }
kenko-apps/oncosafe
src/pages/formulaire-trois/formulaire-trois.ts
<reponame>kenko-apps/oncosafe import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { Component } from '@angular/core'; import { MenuController, NavController } from 'ionic-angular'; import { TranslateService } from '@ngx-translate/core'; import { TabacValidator } from '../../validators/questionTabac' import { FormulairePageQuatre } from '../formulaire-quatre/formulaire-quatre'; @Component({ selector: 'formulaire-trois', templateUrl: 'formulaire-trois.html' }) export class FormulairePageTrois { slideTroisForm: FormGroup; submitAttempt: boolean = false; labelFrequenceTabac: boolean = false; questionsTabac: boolean = false; constructor(public navCtrl: NavController, public menu: MenuController, translate: TranslateService, public formBuilder: FormBuilder) { this.slideTroisForm = formBuilder.group({ tabac_check: ['', Validators.required], frequence_tabac: [''], date_tabac: [''], activite_check: ['', Validators.required] },{ validator: TabacValidator.isValid}); } fumeOui() { this.questionsTabac = true; } fumeNon() { this.questionsTabac = false; this.slideTroisForm.controls.frequence_tabac.setValue(""); this.slideTroisForm.controls.date_tabac.setValue(""); } changeLabel() { this.labelFrequenceTabac = true; } nextPage() { this.submitAttempt = true; if(this.slideTroisForm.valid){ this.navCtrl.push(FormulairePageQuatre); console.log("success!") console.log(this.slideTroisForm.value); } } }
kenko-apps/oncosafe
src/pages/formulaire-deux/formulaire-deux.ts
<gh_stars>0 import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { Component } from '@angular/core'; import { MenuController, NavController } from 'ionic-angular'; import { TranslateService } from '@ngx-translate/core'; import { FormulairePageTrois } from '../formulaire-trois/formulaire-trois'; @Component({ selector: 'formulaire-deux', templateUrl: 'formulaire-deux.html' }) export class FormulairePageDeux { slideDeuxForm: FormGroup; submitAttempt: boolean = false; constructor(public navCtrl: NavController, public menu: MenuController, translate: TranslateService, public formBuilder: FormBuilder) { this.slideDeuxForm = formBuilder.group({ organe_primitif: ['', Validators.compose([ Validators.pattern('([a-zA-Zéèêëàäâùüûïîöôçÿ ]*)([\-]?)([a-zA-Zéèêëàäâùüûïîöôçÿ ]*)'), Validators.required])], date_diagnostic: ['', Validators.required], maladie_check: ['', Validators.required], chimio_check: ['', Validators.required], therapie_check: ['', Validators.required], nom_traitement: ['',Validators.compose([ Validators.pattern('([a-zA-Zéèêëàäâùüûïîöôçÿ ]*)([\-]*)'), Validators.required])] }); } nextPage() { this.submitAttempt = true; if(this.slideDeuxForm.valid){ this.navCtrl.push(FormulairePageTrois); console.log("success!") console.log(this.slideDeuxForm.value); } } }
kenko-apps/oncosafe
src/pages/formulaire-resultat/formulaire-resultat.ts
<filename>src/pages/formulaire-resultat/formulaire-resultat.ts import { FormGroup, FormArray, FormBuilder, Validators } from '@angular/forms'; import { Component, OnInit } from '@angular/core'; import { MenuController, NavController } from 'ionic-angular'; import { TranslateService } from '@ngx-translate/core'; @Component({ selector: 'formulaire-resultat', templateUrl: 'formulaire-resultat.html' }) export class FormulaireResultat { }
kenko-apps/oncosafe
src/pages/formulaire-cinq/formulaire-cinq.ts
<reponame>kenko-apps/oncosafe import { FormGroup, FormArray, FormBuilder, Validators } from '@angular/forms'; import { Component, OnInit } from '@angular/core'; import { MenuController, NavController } from 'ionic-angular'; import { TranslateService } from '@ngx-translate/core'; import { FormulaireResultat } from '../formulaire-resultat/formulaire-resultat'; @Component({ selector: 'formulaire-cinq', templateUrl: 'formulaire-cinq.html' }) export class FormulairePageCinq { slideCinqForm: FormGroup; submitAttempt: boolean = false; checkTraitement: boolean = false; constructor(public navCtrl: NavController, public menu: MenuController, translate: TranslateService, public formBuilder: FormBuilder) { } ngOnInit() { // we will initialize our form here this.slideCinqForm = this.formBuilder.group({ phytotraitement: this.formBuilder.array([ this.initPhytoNom(), ]) }); } initPhytoNom() { // initialize our phyto treatment return this.formBuilder.group({ phytonom: ['', Validators.compose([ Validators.pattern('([a-zA-Zéèêëàäâùüûïîöôçÿ ]*)([\-]*)'), Validators.required])], phytodate: [''] }); } addPhyto() { if (this.slideCinqForm.valid){ // add phyto treatment to the list const control = <FormArray>this.slideCinqForm.controls['phytotraitement']; control.push(this.initPhytoNom()); this.checkTraitement = false; this.submitAttempt = false; }else{ this.checkTraitement = true; } } removePhyto(i: number) { // remove phyto treatment from the list const control = <FormArray>this.slideCinqForm.controls['phytotraitement']; control.removeAt(i); } nextPage() { this.submitAttempt = true; if(this.slideCinqForm.valid){ this.navCtrl.push(FormulaireResultat); console.log("success!") console.log(this.slideCinqForm.value); } } }
kenko-apps/oncosafe
src/app/app.component.ts
import { Component, ViewChild } from '@angular/core'; import { Platform, Nav, Config } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { CardsPage } from '../pages/cards/cards'; import { ContentPage } from '../pages/content/content'; import { PremierePage } from './../pages/pages'; import { ListMasterPage } from '../pages/list-master/list-master'; import { LoginPage } from '../pages/login/login'; import { MapPage } from '../pages/map/map'; import { MenuPage } from '../pages/menu/menu'; import { SearchPage } from '../pages/search/search'; import { SettingsPage } from '../pages/settings/settings'; import { SignupPage } from '../pages/signup/signup'; import { TabsPage } from '../pages/tabs/tabs'; import { TutorialPage } from '../pages/tutorial/tutorial'; import { WelcomePage } from '../pages/welcome/welcome'; import { ChoixPage } from '../pages/choix/choix'; import { FormulairePage } from './../pages/formulaire/formulaire'; import { FormulairePageUn } from './../pages/formulaire-un/formulaire-un'; import { FormulairePageDeux } from './../pages/formulaire-deux/formulaire-deux'; import { FormulairePageTrois } from './../pages/formulaire-trois/formulaire-trois'; import { FormulairePageQuatre } from './../pages/formulaire-quatre/formulaire-quatre'; import { FormulairePageCinq } from './../pages/formulaire-cinq/formulaire-cinq'; import { FormulaireResultat } from './../pages/formulaire-resultat/formulaire-resultat'; import { Settings } from '../providers/providers'; import { TranslateService } from '@ngx-translate/core' @Component({ template: `<ion-menu [content]="content"> <ion-header> <ion-toolbar> <ion-title>Pages</ion-title> </ion-toolbar> </ion-header> <ion-content> <ion-list> <button menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)"> {{p.title}} </button> </ion-list> </ion-content> </ion-menu> <ion-nav #content [root]="rootPage"></ion-nav>` }) export class MyApp { rootPage = PremierePage; @ViewChild(Nav) nav: Nav; pages: any[] = [ { title: 'formulaire-un', component: FormulairePageUn }, { title: 'formulaire-deux', component: FormulairePageDeux }, { title: 'formulaire-trois', component: FormulairePageTrois }, { title: 'formulaire-quatre', component: FormulairePageQuatre }, { title: 'formulaire-cinq', component: FormulairePageCinq }, { title: 'formulaire-resultat', component: FormulaireResultat }, { title: 'formulaire', component: FormulairePage }, { title: 'Choix', component: ChoixPage }, { title: 'Tutorial', component: TutorialPage }, { title: 'Welcome', component: WelcomePage }, { title: 'Tabs', component: TabsPage }, { title: 'Cards', component: CardsPage }, { title: 'Content', component: ContentPage }, { title: 'Login', component: LoginPage }, { title: 'Signup', component: SignupPage }, { title: 'Map', component: MapPage }, { title: 'Master Detail', component: ListMasterPage }, { title: 'Menu', component: MenuPage }, { title: 'Settings', component: SettingsPage }, { title: 'Search', component: SearchPage } ] constructor(private translate: TranslateService, private platform: Platform, settings: Settings, private config: Config, private statusBar: StatusBar, private splashScreen: SplashScreen) { this.initTranslate(); } ionViewDidLoad() { this.platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. this.statusBar.styleDefault(); this.splashScreen.hide(); }); } initTranslate() { // Set the default language for translation strings, and the current language. this.translate.setDefaultLang('en'); if (this.translate.getBrowserLang() !== undefined) { this.translate.use(this.translate.getBrowserLang()); } else { this.translate.use('en'); // Set your language here } this.translate.get(['BACK_BUTTON_TEXT']).subscribe(values => { this.config.set('ios', 'backButtonText', values.BACK_BUTTON_TEXT); }); } openPage(page) { // Reset the content nav to have just this page // we wouldn't want the back button to show in this scenario this.nav.setRoot(page.component); } }
ElreyB/candyhunt
src/app/welcome/welcome.component.ts
<reponame>ElreyB/candyhunt import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Location } from '@angular/common'; import { Player } from '../player.model'; import { Storyline } from '../storyline.model'; import { STORYLINE } from '../mock-storyline'; import { PlayerService } from '../player.service'; import { StorylineService } from '../storyline.service'; import { COSTUMES, PRANKS, CANDY } from '../mock-characteristics'; @Component({ selector: 'app-welcome', templateUrl: './welcome.component.html', styleUrls: ['./welcome.component.css'], providers: [PlayerService, StorylineService] }) export class WelcomeComponent implements OnInit { player: Player; storyline: Storyline[]; storylineId: number; costumes: string[]; constructor( private playerService: PlayerService, private storylineService: StorylineService, private router: Router ) { } ngOnInit() { // this.storyline = this.storylineService.getStorylineById(); } getValueFromSelect(newName: string, selectedCostume: string, selectedPrank: string, selectedCandy: string) { this.player = new Player( newName, selectedCostume, selectedPrank, selectedCandy ) } makeChoice(direction) { if (direction === 1){ this.player.location += 1; } else { this.player.location += 6; } console.log(this.player.location); return this.player.location } goToNextHouse(clickedButton: Storyline) { this.router.navigate(['house', this.player.location]); } }
ElreyB/candyhunt
src/app/app.module.ts
<reponame>ElreyB/candyhunt import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { WelcomeComponent } from './welcome/welcome.component'; import { routing } from './app.routing'; import { SuccessComponent } from './success/success.component'; import { GameOverComponent } from './game-over/game-over.component'; import { HouseComponent } from './house/house.component'; @NgModule({ declarations: [ AppComponent, WelcomeComponent, SuccessComponent, GameOverComponent, HouseComponent ], imports: [ BrowserModule, FormsModule, HttpModule, routing ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
ElreyB/candyhunt
src/app/storyline.service.ts
<reponame>ElreyB/candyhunt import { Injectable } from '@angular/core'; import { Storyline } from './storyline.model'; import { STORYLINE } from './mock-storyline'; @Injectable() export class StorylineService { constructor() { } getStoryline() { return STORYLINE; } getStorylineById(storylineId: number) { for (let i = 0; i <= STORYLINE.length - 1; i++) { if (STORYLINE[i].id === storylineId) { return STORYLINE[i]; } } } }
ElreyB/candyhunt
src/app/house/house.component.ts
<reponame>ElreyB/candyhunt import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { Location } from '@angular/common'; import { Player } from '../player.model'; import { Storyline } from '../storyline.model'; import { STORYLINE } from '../mock-storyline'; import { PlayerService } from '../player.service'; import { StorylineService } from '../storyline.service'; @Component({ selector: 'app-house', templateUrl: './house.component.html', styleUrls: ['./house.component.css'], providers: [PlayerService, StorylineService] }) export class HouseComponent implements OnInit { sub; player: Player; storylineToDisplay: Storyline; storylineId: number; prankOrRing: string; constructor( private router: Router, private route: ActivatedRoute, private location: Location, private playerService: PlayerService, private storylineService: StorylineService ) { } ngOnInit() { this.player = this.playerService.getPlayer(); this.sub = this.route.params.subscribe(params => { this.storylineId = params['id']; // this.storyline = this.storylineService.getStorylineById(this.storylineId); }); this.storylineToDisplay = this.storylineService.getStorylineById(this.storylineId); } makeChoice(direction) { if (direction === 1){ this.player.location += 1; } else { this.player.location += 6; } console.log(this.player.location); return this.player.location } trickOrTreat(choice){ if(choice === "trick"){ this.prankOrRing = "prank"; } else { this.prankOrRing = "ringBell"; } } }
ElreyB/candyhunt
src/app/storyline.model.ts
export class Storyline { public choiceA = 'Ring the doorbell'; public choiceB = 'Prank the house'; constructor (public description: string, public candy: string[], public id: number) { } }
ElreyB/candyhunt
src/app/player.model.ts
export class Player { public candyCount = 5; public location = 0; constructor (public name: string, public costume: string, public prank: string, public candy: string) {} }
ElreyB/candyhunt
src/app/app.routing.ts
<filename>src/app/app.routing.ts import { ModuleWithProviders } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { WelcomeComponent } from './welcome/welcome.component'; import { GameOverComponent } from './game-over/game-over.component'; import { SuccessComponent } from './success/success.component'; const appRoutes: Routes = [ { path: '', component: WelcomeComponent }, { path: 'game-over', component: GameOverComponent }, { path: 'success', component: SuccessComponent } ]; export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
ElreyB/candyhunt
src/app/player.service.ts
import { Injectable } from '@angular/core'; import { Player } from './player.model'; @Injectable() export class PlayerService { player: Player; constructor() { } setPlayer() { } getPlayer() { return this.player; } }
ElreyB/candyhunt
src/app/mock-characteristics.ts
export const COSTUMES: string[] = [ "ghost", "witch", "devil", "cowboy", "princess", "black cat", "pirate" ]; export const PRANKS: string[] = [ "egg house", "toilet paper house", "ding dong ditching", "silly string the car", "soap the windows" ]; export const CANDY: string[] = [ "candy corn", "caramel apple", "candy cigarettes", "black licorice", "candy pumpkins" ];
mastermind88/portainer
app/portainer/home/HomepageFilter.tsx
import { components, OptionProps } from 'react-select'; import { Select } from '@/portainer/components/form-components/ReactSelect'; import { Filter } from '@/portainer/home/types'; interface Props { filterOptions: Filter[]; onChange: (filterOptions: Filter[]) => void; placeHolder: string; value: Filter[]; } function Option(props: OptionProps<Filter, true>) { const { isSelected, label } = props; return ( <div> <components.Option // eslint-disable-next-line react/jsx-props-no-spreading {...props} > <input type="checkbox" checked={isSelected} onChange={() => null} />{' '} <label>{label}</label> </components.Option> </div> ); } export function HomepageFilter({ filterOptions, onChange, placeHolder, value, }: Props) { return ( <Select placeholder={placeHolder} options={filterOptions} value={value} isMulti components={{ Option }} onChange={(option) => onChange(option as Filter[])} /> ); }
mastermind88/portainer
app/portainer/settings/edge-compute/EdgeComputeSettings/EdgeComputeSettings.tsx
import { Formik, Form } from 'formik'; import { Switch } from '@/portainer/components/form-components/SwitchField/Switch'; import { FormControl } from '@/portainer/components/form-components/FormControl'; import { Select } from '@/portainer/components/form-components/Input/Select'; import { Widget, WidgetBody, WidgetTitle } from '@/portainer/components/widget'; import { LoadingButton } from '@/portainer/components/Button/LoadingButton'; import { TextTip } from '@/portainer/components/Tip/TextTip'; import { Settings } from '../types'; import styles from './EdgeComputeSettings.module.css'; import { validationSchema } from './EdgeComputeSettings.validation'; export interface FormValues { EdgeAgentCheckinInterval: number; EnableEdgeComputeFeatures: boolean; EnforceEdgeID: boolean; } interface Props { settings?: Settings; onSubmit(values: FormValues): void; } const checkinIntervalOptions = [ { value: 5, label: '5 seconds', }, { value: 10, label: '10 seconds', }, { value: 30, label: '30 seconds', }, ]; export function EdgeComputeSettings({ settings, onSubmit }: Props) { if (!settings) { return null; } const initialValues: FormValues = { EdgeAgentCheckinInterval: settings.EdgeAgentCheckinInterval, EnableEdgeComputeFeatures: settings.EnableEdgeComputeFeatures, EnforceEdgeID: settings.EnforceEdgeID, }; return ( <div className="row"> <Widget> <WidgetTitle icon="fa-laptop" title="Edge Compute settings" /> <WidgetBody> <Formik initialValues={initialValues} enableReinitialize validationSchema={() => validationSchema()} onSubmit={onSubmit} validateOnMount > {({ values, errors, handleSubmit, setFieldValue, isSubmitting, isValid, dirty, }) => ( <Form className="form-horizontal" onSubmit={handleSubmit} noValidate > <FormControl inputId="edge_checkin" label="Edge agent default poll frequency" size="medium" tooltip="Interval used by default by each Edge agent to check in with the Portainer instance. Affects Edge environment management and Edge compute features." errors={errors.EdgeAgentCheckinInterval} > <Select value={values.EdgeAgentCheckinInterval} onChange={(e) => setFieldValue( 'EdgeAgentCheckinInterval', parseInt(e.currentTarget.value, 10) ) } options={checkinIntervalOptions} /> </FormControl> <FormControl inputId="edge_checkin" label="Enable Edge Compute features" size="medium" errors={errors.EnableEdgeComputeFeatures} > <Switch id="edge_enable" name="edge_enable" className="space-right" checked={values.EnableEdgeComputeFeatures} onChange={(e) => setFieldValue('EnableEdgeComputeFeatures', e) } /> </FormControl> <TextTip color="blue"> When enabled, this will enable Portainer to execute Edge Device features. </TextTip> <FormControl inputId="edge_enforce_id" label="Enforce use of Portainer generated Edge ID" size="medium" tooltip="This setting only applies to manually created environments." errors={errors.EnforceEdgeID} > <Switch id="edge_enforce_id" name="edge_enforce_id" className="space-right" checked={values.EnforceEdgeID} onChange={(e) => setFieldValue('EnforceEdgeID', e.valueOf()) } /> </FormControl> <div className="form-group"> <div className="col-sm-12"> <LoadingButton disabled={!isValid || !dirty} dataCy="settings-edgeComputeButton" className={styles.saveButton} isLoading={isSubmitting} loadingText="Saving settings..." > Save Settings </LoadingButton> </div> </div> </Form> )} </Formik> </WidgetBody> </Widget> </div> ); }
mastermind88/portainer
app/portainer/environments/environment.service/index.ts
import axios, { parseAxiosError } from '@/portainer/services/axios'; import { type EnvironmentGroupId } from '@/portainer/environment-groups/types'; import { type TagId } from '@/portainer/tags/types'; import { UserId } from '@/portainer/users/types'; import { TeamId } from '@/portainer/teams/types'; import type { Environment, EnvironmentId, EnvironmentType, EnvironmentSettings, } from '../types'; import { arrayToJson, buildUrl } from './utils'; export interface EnvironmentsQueryParams { search?: string; types?: EnvironmentType[]; tagIds?: TagId[]; endpointIds?: EnvironmentId[]; tagsPartialMatch?: boolean; groupId?: EnvironmentGroupId; edgeDeviceFilter?: 'all' | 'trusted' | 'untrusted'; } export async function getEndpoints( start: number, limit: number, { types, tagIds, endpointIds, ...query }: EnvironmentsQueryParams = {} ) { if (tagIds && tagIds.length === 0) { return { totalCount: 0, value: <Environment[]>[] }; } const url = buildUrl(); const params: Record<string, unknown> = { start, limit, ...query }; if (types) { params.types = arrayToJson(types); } if (tagIds) { params.tagIds = arrayToJson(tagIds); } if (endpointIds) { params.endpointIds = arrayToJson(endpointIds); } try { const response = await axios.get<Environment[]>(url, { params }); const totalCount = response.headers['x-total-count']; const totalAvailable = response.headers['x-total-available']; return { totalCount: parseInt(totalCount, 10), value: response.data, totalAvailable: parseInt(totalAvailable, 10), }; } catch (e) { throw parseAxiosError(e as Error); } } export async function getEndpoint(id: EnvironmentId) { try { const { data: endpoint } = await axios.get<Environment>(buildUrl(id)); return endpoint; } catch (e) { throw parseAxiosError(e as Error); } } export async function snapshotEndpoints() { try { await axios.post<void>(buildUrl(undefined, 'snapshot')); } catch (e) { throw parseAxiosError(e as Error); } } export async function snapshotEndpoint(id: EnvironmentId) { try { await axios.post<void>(buildUrl(id, 'snapshot')); } catch (e) { throw parseAxiosError(e as Error); } } export async function endpointsByGroup( start: number, limit: number, search: string, groupId: EnvironmentGroupId ) { return getEndpoints(start, limit, { search, groupId }); } export async function disassociateEndpoint(id: EnvironmentId) { try { await axios.delete(buildUrl(id, 'association')); } catch (e) { throw parseAxiosError(e as Error); } } interface UpdatePayload { TLSCACert?: File; TLSCert?: File; TLSKey?: File; Name: string; PublicURL: string; GroupID: EnvironmentGroupId; TagIds: TagId[]; EdgeCheckinInterval: number; TLS: boolean; TLSSkipVerify: boolean; TLSSkipClientVerify: boolean; AzureApplicationID: string; AzureTenantID: string; AzureAuthenticationKey: string; } async function uploadTLSFilesForEndpoint( id: EnvironmentId, tlscaCert?: File, tlsCert?: File, tlsKey?: File ) { await Promise.all([ uploadCert('ca', tlscaCert), uploadCert('cert', tlsCert), uploadCert('key', tlsKey), ]); function uploadCert(type: 'ca' | 'cert' | 'key', cert?: File) { if (!cert) { return null; } try { return axios.post<void>(`upload/tls/${type}`, cert, { params: { folder: id }, }); } catch (e) { throw parseAxiosError(e as Error); } } } export async function updateEndpoint( id: EnvironmentId, payload: UpdatePayload ) { try { await uploadTLSFilesForEndpoint( id, payload.TLSCACert, payload.TLSCert, payload.TLSKey ); const { data: endpoint } = await axios.put<Environment>( buildUrl(id), payload ); return endpoint; } catch (e) { throw parseAxiosError(e as Error, 'Unable to update environment'); } } export async function deleteEndpoint(id: EnvironmentId) { try { await axios.delete(buildUrl(id)); } catch (e) { throw parseAxiosError(e as Error); } } export async function updatePoolAccess( id: EnvironmentId, resourcePool: string, usersToAdd: UserId[], teamsToAdd: TeamId[], usersToRemove: UserId[], teamsToRemove: TeamId[] ) { try { await axios.put<void>(`${buildUrl(id, 'pools')}/${resourcePool}/access`, { usersToAdd, teamsToAdd, usersToRemove, teamsToRemove, }); } catch (e) { throw parseAxiosError(e as Error); } } export async function forceUpdateService( id: EnvironmentId, serviceID: string, pullImage: boolean ) { try { await axios.put(buildUrl(id, 'forceupdateservice'), { serviceID, pullImage, }); } catch (e) { throw parseAxiosError(e as Error); } } export async function updateSettings( id: EnvironmentId, settings: EnvironmentSettings ) { try { await axios.put(buildUrl(id, 'settings'), settings); } catch (e) { throw parseAxiosError(e as Error); } } export async function trustEndpoint(id: EnvironmentId) { try { const { data: endpoint } = await axios.put<Environment>(buildUrl(id), { UserTrusted: true, }); return endpoint; } catch (e) { throw parseAxiosError(e as Error, 'Unable to update environment'); } }
mastermind88/portainer
app/portainer/home/EnvironmentList/EnvironmentList.tsx
<filename>app/portainer/home/EnvironmentList/EnvironmentList.tsx import { ReactNode, useEffect, useState } from 'react'; import clsx from 'clsx'; import { PaginationControls } from '@/portainer/components/pagination-controls'; import { usePaginationLimitState } from '@/portainer/hooks/usePaginationLimitState'; import { Environment, EnvironmentType, EnvironmentStatus, } from '@/portainer/environments/types'; import { Button } from '@/portainer/components/Button'; import { useIsAdmin } from '@/portainer/hooks/useUser'; import { FilterSearchBar, useSearchBarState, } from '@/portainer/components/datatables/components/FilterSearchBar'; import { SortbySelector } from '@/portainer/components/datatables/components/SortbySelector'; import { HomepageFilter } from '@/portainer/home/HomepageFilter'; import { TableActions, TableContainer, TableTitle, } from '@/portainer/components/datatables/components'; import { TableFooter } from '@/portainer/components/datatables/components/TableFooter'; import { useDebounce } from '@/portainer/hooks/useDebounce'; import { useEnvironmentList } from '@/portainer/environments/queries'; import { useGroups } from '@/portainer/environment-groups/queries'; import { useTags } from '@/portainer/tags/queries'; import { Filter } from '@/portainer/home/types'; import { EnvironmentItem } from './EnvironmentItem'; import { KubeconfigButton } from './KubeconfigButton'; import styles from './EnvironmentList.module.css'; import { NoEnvironmentsInfoPanel } from './NoEnvironmentsInfoPanel'; interface Props { onClickItem(environment: Environment): void; onRefresh(): void; } export function EnvironmentList({ onClickItem, onRefresh }: Props) { const isAdmin = useIsAdmin(); const storageKey = 'home_endpoints'; const allEnvironmentType = [ EnvironmentType.Docker, EnvironmentType.AgentOnDocker, EnvironmentType.Azure, EnvironmentType.EdgeAgentOnDocker, EnvironmentType.KubernetesLocal, EnvironmentType.AgentOnKubernetes, EnvironmentType.EdgeAgentOnKubernetes, ]; const [platformType, setPlatformType] = useState(allEnvironmentType); const [searchBarValue, setSearchBarValue] = useSearchBarState(storageKey); const [pageLimit, setPageLimit] = usePaginationLimitState(storageKey); const [page, setPage] = useState(1); const debouncedTextFilter = useDebounce(searchBarValue); const [statusFilter, setStatusFilter] = useState<number[]>([]); const [tagFilter, setTagFilter] = useState<number[]>([]); const [groupFilter, setGroupFilter] = useState<number[]>([]); const [sortByFilter, setSortByFilter] = useState<string>(''); const [sortByDescending, setSortByDescending] = useState(false); const [sortByButton, setSortByButton] = useState(false); const [platformState, setPlatformState] = useState<Filter[]>([]); const [statusState, setStatusState] = useState<Filter[]>([]); const [tagState, setTagState] = useState<Filter[]>([]); const [groupState, setGroupState] = useState<Filter[]>([]); const groupsQuery = useGroups(); const { isLoading, environments, totalCount, totalAvailable } = useEnvironmentList( { page, pageLimit, types: platformType, search: debouncedTextFilter }, true ); useEffect(() => { setPage(1); }, [searchBarValue]); interface Collection { Status: number[]; TagIds: number[]; GroupId: number[]; } const PlatformOptions = [ { value: EnvironmentType.Docker, label: 'Docker' }, { value: EnvironmentType.Azure, label: 'Azure' }, { value: EnvironmentType.KubernetesLocal, label: 'Kubernetes' }, ]; const status = [ { value: EnvironmentStatus.Up, label: 'Up' }, { value: EnvironmentStatus.Down, label: 'Down' }, ]; const SortByOptions = [ { value: 1, label: 'Name' }, { value: 2, label: 'Group' }, { value: 3, label: 'Status' }, ]; const groupOptions = [...(groupsQuery.data || [])]; const uniqueGroup = [ ...new Map(groupOptions.map((item) => [item.Id, item])).values(), ].map(({ Id: value, Name: label }) => ({ value, label, })); const alltags = useTags(); const tagOptions = [...(alltags.tags || [])]; const uniqueTag = [ ...new Map(tagOptions.map((item) => [item.ID, item])).values(), ].map(({ ID: value, Name: label }) => ({ value, label, })); const collection = { Status: statusFilter, TagIds: tagFilter, GroupId: groupFilter, }; function multiPropsFilter( environments: Environment[], collection: Collection, sortByFilter: string, sortByDescending: boolean ) { const filterKeys = Object.keys(collection); const filterResult = environments.filter((environment: Environment) => filterKeys.every((key) => { if (!collection[key as keyof Collection].length) return true; if (Array.isArray(environment[key as keyof Collection])) { return (environment[key as keyof Collection] as number[]).some( (keyEle) => collection[key as keyof Collection].includes(keyEle) ); } return collection[key as keyof Collection].includes( environment[key as keyof Collection] as number ); }) ); switch (sortByFilter) { case 'Name': return sortByDescending ? filterResult.sort((a, b) => b.Name.toUpperCase() > a.Name.toUpperCase() ? 1 : -1 ) : filterResult.sort((a, b) => a.Name.toUpperCase() > b.Name.toUpperCase() ? 1 : -1 ); case 'Group': return sortByDescending ? filterResult.sort((a, b) => b.GroupId - a.GroupId) : filterResult.sort((a, b) => a.GroupId - b.GroupId); case 'Status': return sortByDescending ? filterResult.sort((a, b) => b.Status - a.Status) : filterResult.sort((a, b) => a.Status - b.Status); case 'None': return filterResult; default: return filterResult; } } const filteredEnvironments: Environment[] = multiPropsFilter( environments, collection, sortByFilter, sortByDescending ); function platformOnChange(filterOptions: Filter[]) { setPlatformState(filterOptions); const dockerBaseType = EnvironmentType.Docker; const kubernetesBaseType = EnvironmentType.KubernetesLocal; const dockerRelateType = [ EnvironmentType.AgentOnDocker, EnvironmentType.EdgeAgentOnDocker, ]; const kubernetesRelateType = [ EnvironmentType.AgentOnKubernetes, EnvironmentType.EdgeAgentOnKubernetes, ]; let finalFilterEnvironment: number[] = []; if (filterOptions.length === 0) { setPlatformType(allEnvironmentType); } else { const filteredEnvironment = [ ...new Set( filterOptions.map( (filterOptions: { value: number }) => filterOptions.value ) ), ]; if (filteredEnvironment.includes(dockerBaseType)) { finalFilterEnvironment = [...filteredEnvironment, ...dockerRelateType]; } if (filteredEnvironment.includes(kubernetesBaseType)) { finalFilterEnvironment = [ ...filteredEnvironment, ...kubernetesRelateType, ]; } setPlatformType(finalFilterEnvironment); } } function statusOnChange(filterOptions: Filter[]) { setStatusState(filterOptions); if (filterOptions.length === 0) { setStatusFilter([]); } else { const filteredStatus = [ ...new Set( filterOptions.map( (filterOptions: { value: number }) => filterOptions.value ) ), ]; setStatusFilter(filteredStatus); } } function groupOnChange(filterOptions: Filter[]) { setGroupState(filterOptions); if (filterOptions.length === 0) { setGroupFilter([]); } else { const filteredGroups = [ ...new Set( filterOptions.map( (filterOptions: { value: number }) => filterOptions.value ) ), ]; setGroupFilter(filteredGroups); } } function tagOnChange(filterOptions: Filter[]) { setTagState(filterOptions); if (filterOptions.length === 0) { setTagFilter([]); } else { const filteredTags = [ ...new Set( filterOptions.map( (filterOptions: { value: number }) => filterOptions.value ) ), ]; setTagFilter(filteredTags); } } function clearFilter() { setSearchBarValue(''); setPlatformState([]); setPlatformType(allEnvironmentType); setStatusState([]); setStatusFilter([]); setTagState([]); setTagFilter([]); setGroupState([]); setGroupFilter([]); } function sortOnchange(filterOptions: Filter) { if (filterOptions !== null) { setSortByFilter(filterOptions.label); setSortByButton(true); } else { setSortByFilter('None'); setSortByButton(false); } } function sortOndescending() { setSortByDescending(!sortByDescending); } return ( <> {totalAvailable === 0 && <NoEnvironmentsInfoPanel isAdmin={isAdmin} />} <div className="row"> <div className="col-sm-12"> <TableContainer> <TableTitle icon="fa-plug" label="Environments" /> <TableActions className={styles.actionBar}> <div className={styles.description}> <i className="fa fa-exclamation-circle blue-icon space-right" /> Click on an environment to manage </div> {isAdmin && ( <Button onClick={onRefresh} data-cy="home-refreshEndpointsButton" className={clsx(styles.refreshEnvironmentsButton)} > <i className="fa fa-sync space-right" aria-hidden="true" /> Refresh </Button> )} <KubeconfigButton environments={environments} /> </TableActions> <div className={styles.filterContainer}> <div className={styles.filterLeft}> <HomepageFilter filterOptions={PlatformOptions} onChange={platformOnChange} placeHolder="Platform" value={platformState} /> </div> <div className={styles.filterLeft}> <HomepageFilter filterOptions={status} onChange={statusOnChange} placeHolder="Status" value={statusState} /> </div> <div className={styles.filterLeft}> <HomepageFilter filterOptions={uniqueTag} onChange={tagOnChange} placeHolder="Tags" value={tagState} /> </div> <div className={styles.filterLeft}> <HomepageFilter filterOptions={uniqueGroup} onChange={groupOnChange} placeHolder="Groups" value={groupState} /> </div> <div className={styles.filterLeft}> <FilterSearchBar value={searchBarValue} onChange={setSearchBarValue} placeholder="Search...." data-cy="home-endpointsSearchInput" /> </div> <div className={styles.filterButton}> <Button size="medium" onClick={clearFilter}> Clear </Button> </div> <div className={styles.filterRight}> <SortbySelector filterOptions={SortByOptions} onChange={sortOnchange} onDescending={sortOndescending} placeHolder="Sort By" sortByDescending={sortByDescending} sortByButton={sortByButton} /> </div> </div> <div className="blocklist" data-cy="home-endpointList"> {renderItems( isLoading, totalCount, filteredEnvironments.map((env) => ( <EnvironmentItem key={env.Id} environment={env} groupName={ groupsQuery.data?.find((g) => g.Id === env.GroupId)?.Name } onClick={onClickItem} /> )) )} </div> <TableFooter> <PaginationControls showAll={totalCount <= 100} pageLimit={pageLimit} page={page} onPageChange={setPage} totalCount={totalCount} onPageLimitChange={setPageLimit} /> </TableFooter> </TableContainer> </div> </div> </> ); } function renderItems( isLoading: boolean, totalCount: number, items: ReactNode ) { if (isLoading) { return ( <div className="text-center text-muted" data-cy="home-loadingEndpoints"> Loading... </div> ); } if (!totalCount) { return ( <div className="text-center text-muted" data-cy="home-noEndpoints"> No environments available. </div> ); } return items; }
rytsh/repeatit
_web/src/lib/helper/code.ts
const fullScreenKeys = { "F11": (cm: CodeMirror.Editor) => cm.setOption("fullScreen", !cm.getOption("fullScreen")), "Esc": (cm: CodeMirror.Editor) => cm.setOption("fullScreen", false), }; export { fullScreenKeys };
rytsh/repeatit
_web/src/lib/helper/run.ts
<reponame>rytsh/repeatit<filename>_web/src/lib/helper/run.ts import { codes, convertConfig } from "@/lib/store"; import { get } from "svelte/store"; import update from "immutability-helper"; const run = async () => { const values = get(codes); const config = get(convertConfig); const render = window["render"]; if (render) { let output: string; try { output = await render(values.input == "" ? "null" : values.input, values.template, config.template, [...config.functions.keys()].join(",")); } catch (error) { codes.update((v) => update(v, { output: { $set: error.toString() }, trigger: { $set: !v.trigger }, triggerError: { $set: !v.triggerError }, error: { $set: true }, success: { $set: false }, })); return; } codes.update((v) => update(v, { output: { $set: output }, trigger: { $set: !v.trigger }, triggerError: { $set: !v.triggerError }, error: { $set: false }, success: { $set: true }, })); } }; export { run };
rytsh/repeatit
_web/src/hooks.ts
import { minify } from "html-minifier"; import type { Options as minifyOptions } from "html-minifier"; import { prerendering } from "$app/env"; const repeatitVersion = import.meta.env.VITE_REPEATIT_VERSION; const minificationOptions: minifyOptions = { collapseBooleanAttributes: true, collapseWhitespace: true, conservativeCollapse: true, decodeEntities: true, html5: true, ignoreCustomComments: [/^#/], minifyCSS: true, minifyJS: false, removeAttributeQuotes: true, removeComments: true, removeOptionalTags: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true, sortAttributes: true, sortClassName: true, }; const analytics = ` <script async src="https://www.googletagmanager.com/gtag/js?id=G-DLDSWZ7265"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'G-DLDSWZ7265'); </script>`; const injectFn = (s: string) => { return s.replace(/<!-- <%- analytics %> -->/g, analytics); }; /** @type {import('@sveltejs/kit').Handle} */ export async function handle({ event, resolve }) { const response = await resolve(event); if (process.env.npm_lifecycle_event != "build") { return response; } if (prerendering && response.headers.get("content-type") === "text/html") { console.log("> Prerendering hook function called"); let tx = await response.text(); if (repeatitVersion != "test") { tx = injectFn(tx); } return new Response( minify( tx, minificationOptions ), { status: response.status, headers: response.headers, }); } return response; }
rytsh/repeatit
_web/src/lib/store/versions.ts
<gh_stars>1-10 const goVersion = import.meta.env.VITE_GO_VERSION; const sprigVersion = import.meta.env.VITE_SPRIG_VERSION; const repeatitVersion = import.meta.env.VITE_REPEATIT_VERSION; const versions = [ { name: "go", version: goVersion, link: "https://golang.org/doc/devel/release.html", }, { name: "sprig", version: sprigVersion, link: "https://masterminds.github.io/sprig", }, ]; export { versions, repeatitVersion };
rytsh/repeatit
_web/src/lib/helper/wasm.ts
import { loading } from "@/lib/store"; import "./wasm_exec.js"; const initWasm = (wasmFile = "./wasm/repeatit.wasm") => { if (!WebAssembly.instantiateStreaming) { // polyfill WebAssembly.instantiateStreaming = async (resp, importObject) => { const source = await (await resp).arrayBuffer(); return await WebAssembly.instantiate(source, importObject); }; } const go = new Go(); WebAssembly.instantiateStreaming(fetch(wasmFile), go.importObject).then((result) => { go.run(result.instance); loading.set(false); }).catch((err) => { console.error(err); }); }; export { initWasm };
rytsh/repeatit
_web/src/lib/helper/drag.ts
<reponame>rytsh/repeatit const moveElement = (move:HTMLElement, Y: boolean, fn: (ch: number)=>void, down: ()=>void) => { let pos = 0; let posChange = 0; move.onmousedown = dragMouseDown; function dragMouseDown(e:MouseEvent) { e.preventDefault(); // get the mouse cursor position at startup: if (Y) { pos = e.clientY; } else { pos = e.clientX; } document.onmouseup = closeDragElement; // call a function whenever the cursor moves: document.onmousemove = elementDrag; down(); } function elementDrag(e:MouseEvent) { e.preventDefault(); // calculate the new cursor position: if (Y) { posChange = pos - e.clientY; pos = e.clientY; } else { posChange = pos - e.clientX; pos = e.clientX; } // set the element's new position: fn(posChange); } function closeDragElement() { // stop moving when mouse button is released: document.onmouseup = null; document.onmousemove = null; } }; export { moveElement };
rytsh/repeatit
_web/src/examples/hello/index.ts
<gh_stars>1-10 import input from "./input?raw"; import template from "./template?raw"; const hello = { name: "hello", template: template, input: input, }; export { hello };
rytsh/repeatit
_web/src/lib/helper/init.ts
import "codemirror/mode/yaml/yaml"; import "codemirror/addon/edit/matchbrackets"; import "codemirror/addon/edit/trailingspace"; import "codemirror/addon/selection/active-line"; import "codemirror/addon/display/fullscreen"; import "codemirror/addon/display/placeholder"; import { initWasm } from "@/lib/helper/wasm"; initWasm();
rytsh/repeatit
_web/src/lib/helper/copy.ts
const copyClip = (text: string) => { return navigator.clipboard.writeText(text); }; export { copyClip };
rytsh/repeatit
_web/src/examples/index.ts
<gh_stars>1-10 import { hello } from "./hello"; import { planet } from "./planet"; interface IExample { template: string; input: string; } const convert = (v: {template: string, input: string}) => { return { template: v.template, input: v.input, } as IExample; }; const examples = new Map<string, IExample>(); examples.set(hello.name, convert(hello)); examples.set(planet.name, convert(planet)); export default examples;
rytsh/repeatit
_web/src/lib/store/index.ts
import { fullScreenKeys } from "@/lib/helper/code"; import { writable } from "svelte/store"; const initialEditorConfig: CodeMirror.EditorConfiguration = { mode: "yaml", lineNumbers: true, tabSize: 2, lineWrapping: true, styleActiveLine: true, matchBrackets: true, showTrailingSpace: true, extraKeys: fullScreenKeys, }; export const examples = writable(undefined); export const editorConfig = writable(initialEditorConfig); // Loading export const loading = writable(true); // Loading export const codeTheme = writable("light"); // Codes const initialCodes = { template: "", input: "", output: "", trigger: false, triggerError: false, error: false, success: false, }; export type codesKeys = "template" | "input" | "output"; export const codes = writable(initialCodes); // Convert settings export const convertTemplates = ["text", "html"]; export const convertFunctions = ["sprig"]; export const options = ["live"]; const initialConvertConfig = { template: "text" as typeof convertTemplates[number], functions: new Set(convertFunctions), options: new Set(options), }; export const convertConfig = writable(initialConvertConfig); // UI settings const initialUISettings = { showSettings: false, }; export const uiConfig = writable(initialUISettings);
rytsh/repeatit
_web/src/examples/planet/index.ts
<filename>_web/src/examples/planet/index.ts<gh_stars>1-10 import input from "./input?raw"; import template from "./template?raw"; const planet = { name: "planet", template: template, input: input, }; export { planet };
andriyor/xlwings
xlwings/js/xlwings.ts
async function main(workbook: ExcelScript.Workbook) { // String arguments are actual values or keys in xlwings.conf sheet await runPython( workbook, "URL", "API_KEY" ); } /** * xlwings dev (for Microsoft Office Scripts) * Copyright (C) 2014 - present, Zoomer Analytics GmbH. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ async function runPython( workbook: ExcelScript.Workbook, url: string, apiKey: string, exclude: string = "" ): Promise<void> { // Read config from optional xlwings.conf sheet let configSheet = workbook.getWorksheet("xlwings.conf"); let config = {}; if (configSheet) { const configValues = workbook .getWorksheet("xlwings.conf") .getRange("A1") .getExtendedRange(ExcelScript.KeyboardDirection.down) .getExtendedRange(ExcelScript.KeyboardDirection.right) .getValues(); configValues.forEach((el) => (config[el[0].toString()] = el[1].toString())); } // Prepare config values let url_: string = getConfig(url, config); let headerApiKey: string = getConfig(apiKey, config); let excludeString: string = getConfig(exclude, config); let excludeArray: string[] = []; excludeArray = excludeString.split(",").map((item: string) => item.trim()); // Request payload let sheets = workbook.getWorksheets(); let payload: {} = {}; payload["client"] = "Microsoft Office Scripts"; payload["version"] = "dev"; payload["book"] = { name: workbook.getName(), active_sheet_index: workbook.getActiveWorksheet().getPosition(), selection: workbook.getSelectedRange().getAddress().split('!').pop(), }; payload["sheets"] = []; let lastCellCol: number; let lastCellRow: number; let values: (string | number | boolean)[][]; let categories: ExcelScript.NumberFormatCategory[][]; sheets.forEach((sheet) => { if (sheet.getUsedRange() !== undefined) { let lastCell = sheet.getUsedRange().getLastCell(); lastCellCol = lastCell.getColumnIndex(); lastCellRow = lastCell.getRowIndex(); } else { lastCellCol = 0; lastCellRow = 0; } if (excludeArray.includes(sheet.getName())) { values = [[]]; } else { let range = sheet.getRangeByIndexes( 0, 0, lastCellRow + 1, lastCellCol + 1 ); values = range.getValues(); categories = range.getNumberFormatCategories(); // Handle dates values.forEach( (valueRow: (string | number | boolean)[], rowIndex: number) => { const categoryRow = categories[rowIndex]; valueRow.forEach((value, colIndex: number) => { const category = categoryRow[colIndex]; if ( (category.toString() === "Date" || category.toString() === "Time") && typeof value === "number" ) { values[rowIndex][colIndex] = new Date( Math.round((value - 25569) * 86400 * 1000) ).toISOString(); } }); } ); } payload["sheets"].push({ name: sheet.getName(), values: values, }); }); // console.log(payload); // Headers let headers = { "Content-Type": "application/json", Authorization: headerApiKey, }; for (const property in config) { if (property.toLowerCase().startsWith("header_")) { headers[property.substring(7)] = config[property]; } } // API call let response = await fetch(url_, { method: "POST", headers: headers, body: JSON.stringify(payload), }); // Parse JSON response let rawData: { actions: Action[] }; if (response.status !== 200) { throw `Server responded with error ${response.status}`; } else { rawData = await response.json(); } // console.log(rawData); // Run Functions if (rawData !== null) { const forceSync = ["sheet"]; rawData["actions"].forEach((action) => { if (forceSync.some((el) => action.func.toLowerCase().includes(el))) { console.log(); // Force sync to prevent writing to wrong sheet } funcs[action.func](workbook, action); }); } } // Helpers interface Action { func: string; args: (string | number | boolean)[]; values: (string | number | boolean)[][]; sheet_position: number; start_row: number; start_column: number; row_count: number; column_count: number; } function getRange(workbook: ExcelScript.Workbook, action: Action) { return workbook .getWorksheets() [action.sheet_position].getRangeByIndexes( action.start_row, action.start_column, action.row_count, action.column_count ); } function getConfig(keyOrValue: string, config: {}) { if (keyOrValue in config) { return config[keyOrValue]; } else { return keyOrValue; } } // Functions map let funcs = { setValues: setValues, clearContents: clearContents, addSheet: addSheet, setSheetName: setSheetName, setAutofit: setAutofit, setRangeColor: setRangeColor, activateSheet: activateSheet, }; // Functions function setValues(workbook: ExcelScript.Workbook, action: Action) { // Handle DateTime (TODO: backend should deliver indices with datetime obj) let dt: Date; let dtString: string; action.values.forEach((valueRow, rowIndex) => { valueRow.forEach((value: string | number | boolean, colIndex) => { if (typeof value === "string") { dt = new Date(Date.parse(value)); dtString = dt.toLocaleDateString(); if (dtString !== "Invalid Date") { if ( dt.getHours() + dt.getMinutes() + dt.getSeconds() + dt.getMilliseconds() !== 0 ) { dtString += " " + dt.toLocaleTimeString(); } action.values[rowIndex][colIndex] = dtString; } } }); }); getRange(workbook, action).setValues(action.values); } function clearContents(workbook: ExcelScript.Workbook, action: Action) { getRange(workbook, action).clear(ExcelScript.ClearApplyTo.contents); } function addSheet(workbook: ExcelScript.Workbook, action: Action) { let sheet = workbook.addWorksheet(); sheet.setPosition(parseInt(action.args[0].toString())); } function setSheetName(workbook: ExcelScript.Workbook, action: Action) { workbook .getWorksheets() [action.sheet_position].setName(action.args[0].toString()); } function setAutofit(workbook: ExcelScript.Workbook, action: Action) { if (action.args[0] === "columns") { getRange(workbook, action).getFormat().autofitColumns(); } else { getRange(workbook, action).getFormat().autofitRows(); } } function setRangeColor(workbook: ExcelScript.Workbook, action: Action) { getRange(workbook, action) .getFormat() .getFill() .setColor(action.args[0].toString()); } function activateSheet(workbook: ExcelScript.Workbook, action: Action) { workbook.getWorksheets()[parseInt(action.args[0].toString())].activate(); }
sashkopavlenko/serverless-plugin-static
src/serve.ts
import * as http from 'http'; import * as url from 'url'; import * as path from 'path'; import { promises as fs } from 'fs'; import Serverless = require('serverless'); interface ContentTypeMap { readonly [key: string]: string; } const fileExtToContentTypeMap: ContentTypeMap = { '.ico': 'image/x-icon', '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword', }; const handler = (folder: string) => async (req: http.IncomingMessage, res: http.ServerResponse) => { try { const parsedUrl = url.parse(String(req.url)); const pathname = path.join(folder, String(parsedUrl.pathname)); const { ext } = path.parse(pathname); const data = await fs.readFile(pathname); res.setHeader( 'Content-Type', fileExtToContentTypeMap[ext] || 'text/plain' ); return res.end(data); } catch (error: any) { if (error.code === 'ENOENT') { res.statusCode = 404; return res.end(`File not found`); } res.statusCode = 500; return res.end(`Error getting the file: ${error}.`); } }; interface PluginSettings { folder: string; port: number; } export default (serverless: Serverless, { folder, port }: PluginSettings) => new Promise((resolve) => { const requestHandler = handler(folder); const server = http.createServer(requestHandler); server.listen(port, () => { serverless.cli.log( `[ Static ] serving static files from ${folder} folder` ); serverless.cli.log( `[ Static ] serving static files on http://localhost:${port}` ); resolve(server); }); });
sashkopavlenko/serverless-plugin-static
src/serve.spec.ts
/* eslint-disable max-classes-per-file */ import { Server } from 'https'; import * as request from 'supertest'; import { promises as fs } from 'fs'; import serve from './serve'; import Serverless = require('serverless'); class FileNotFound extends Error { code = 'ENOENT'; } class PermissionDenied extends Error { code = 'EACCES'; } const files: { [path: string]: string } = { 'static/favicon.ico': 'image/x-icon', 'static/index.html': 'text/html', 'static/index.js': 'text/javascript', 'static/file.json': '{ "contentType": "application/json" }', 'static/file.css': 'text/css', 'static/image.png': 'image/png', 'static/image.jpg': 'image/jpeg', 'static/audio.wav': 'audio/wav', 'static/audio.mp3': 'audio/mpeg', 'static/pic.svg': 'image/svg+xml', 'static/doc.pdf': 'application/pdf', 'static/doc.doc': 'application/msword', 'static/index': 'text/plain', }; jest .spyOn(fs, 'readFile') .mockName('readFile') .mockImplementation((pathname) => { if (pathname === 'static/denied') { throw new PermissionDenied(); } const file = files[String(pathname)]; if (!file) { throw new FileNotFound(); } return Promise.resolve(file); }); const serverless = { cli: { log: jest.fn() }, } as any; describe('Server', () => { let server: Server; beforeAll(async () => { server = (await serve(<Serverless>serverless, { folder: 'static', port: 8080, })) as Server; }); afterAll(() => server.close()); it('should be defined', () => { expect(server).toBeDefined(); }); it('GET /not-exists - 404 status code', () => request(server).get('/not-exists').expect(404)); it('GET /favicon.ico - 200 status code', () => request(server).get('/favicon.ico').expect(200)); it('GET /index.html - text/html Content-Type', () => request(server) .get('/index.html') .expect('Content-Type', /text\/html/)); it('GET /index.js - text/javascript response', async () => { const response = await request(server).get('/index.js'); expect(response.text).toBe('text/javascript'); }); it('GET /denied - 500 status code', () => request(server).get('/denied').expect(500)); it('GET /denied - 500 status code', () => request(server).get('/denied').expect(500)); it('GET /index - text/plain Content-Type', () => request(server) .get('/index') .expect('Content-Type', /text\/plain/)); it('GET /file.json - application/json Content-Type', () => request(server) .get('/file.json') .expect('Content-Type', /application\/json/)); it('GET /file.css - text/css Content-Type', () => request(server) .get('/file.css') .expect('Content-Type', /text\/css/)); it('GET /image.png - image/png Content-Type', () => request(server) .get('/image.png') .expect('Content-Type', /image\/png/)); it('GET /image.jpg - image/jpeg Content-Type', () => request(server) .get('/image.jpg') .expect('Content-Type', /image\/jpeg/)); it('GET /audio.wav - audio/wav Content-Type', () => request(server) .get('/audio.wav') .expect('Content-Type', /audio\/wav/)); it('GET /audio.mp3 - audio/mpeg Content-Type', () => request(server) .get('/audio.mp3') .expect('Content-Type', /audio\/mpeg/)); it('GET /pic.svg - image/svg+xml Content-Type', () => request(server) .get('/pic.svg') .expect('Content-Type', /image\/svg\+xml/)); it('GET /doc.pdf - application/pdf Content-Type', () => request(server) .get('/doc.pdf') .expect('Content-Type', /application\/pdf/)); it('GET /doc.doc - application/msword Content-Type', () => request(server) .get('/doc.doc') .expect('Content-Type', /application\/msword/)); it('GET /index - text/plain Content-Type', () => request(server) .get('/index') .expect('Content-Type', /text\/plain/)); });
sashkopavlenko/serverless-plugin-static
src/plugin.spec.ts
import StaticPlugin from './plugin'; import * as ServerModule from './serve'; import Serverless = require('serverless'); const serveMock = jest .spyOn(ServerModule, 'default') .mockImplementation(() => Promise.resolve()); describe('Plugin without options', () => { const serverless = { service: {}, }; const options = { stage: '', region: '', }; const plugin = new StaticPlugin(<Serverless>serverless, options); beforeAll(() => { serveMock.mockClear(); plugin.hooks['serve:start'](); }); it('should be defined', () => { expect(plugin).toBeDefined(); }); it('should run before offline plugin', () => { expect(plugin.hooks['before:offline:start:init']).toBeInstanceOf(Function); }); it('should run on serve command', () => { expect(plugin.hooks['serve:start']).toBeInstanceOf(Function); }); const defaultPort = 8080; it(`should pass default ${defaultPort} port to server`, async () => { plugin.hooks['serve:start'](); const [, settings] = serveMock.mock.calls[0]; expect(settings.port).toBe(defaultPort); }); const defaultFolder = './static'; it(`should pass default ${defaultFolder} folder to server`, async () => { plugin.hooks['serve:start'](); const [, settings] = serveMock.mock.calls[0]; expect(settings.folder).toBe(defaultFolder); }); }); describe('Plugin with yaml config', () => { const serverless = { service: { custom: { static: { folder: 'dist', port: 3000, }, }, }, } as any as Serverless; const options = { stage: '', region: '', }; const plugin = new StaticPlugin(serverless, options); beforeAll(() => { serveMock.mockClear(); plugin.hooks['serve:start'](); }); it(`should pass port from YML config to server`, async () => { const [, settings] = serveMock.mock.calls[0]; expect(settings.port).toBe(serverless.service.custom.static.port); }); it(`should pass folder from YML config to server`, async () => { const [, settings] = serveMock.mock.calls[0]; expect(settings.folder).toBe(serverless.service.custom.static.folder); }); }); describe('Plugin with cli arguments', () => { const serverless = { service: {}, }; const options = { stage: '', region: '', folder: 'build', port: '8000', }; const plugin = new StaticPlugin(<Serverless>serverless, options); beforeAll(() => { serveMock.mockClear(); plugin.hooks['serve:start'](); }); it(`should pass port from --port argument to server`, async () => { const [, settings] = serveMock.mock.calls[0]; expect(settings.port).toBe(Number(options.port)); }); it(`should pass folder from --folder argument to server`, async () => { const [, settings] = serveMock.mock.calls[0]; expect(settings.folder).toBe(options.folder); }); }); describe('Plugin with cli shortcuts arguments', () => { const serverless = { service: {}, }; const options = { stage: '', region: '', f: 'build-shortcut', p: '5000', }; const plugin = new StaticPlugin(<Serverless>serverless, options); beforeAll(() => { serveMock.mockClear(); plugin.hooks['serve:start'](); }); it(`should pass port from --p argument to server`, async () => { const [, settings] = serveMock.mock.calls[0]; expect(settings.port).toBe(Number(options.p)); }); it(`should pass folder from --f argument to server`, async () => { const [, settings] = serveMock.mock.calls[0]; expect(settings.folder).toBe(options.f); }); });
sashkopavlenko/serverless-plugin-static
src/index.ts
import StaticPlugin from './plugin'; module.exports = StaticPlugin;
sashkopavlenko/serverless-plugin-static
src/plugin.ts
import serve from './serve'; import Serverless = require('serverless'); import Plugin = require('serverless/classes/Plugin'); interface PluginOptions extends Serverless.Options { port?: string; p?: string; folder?: string; f?: string; } const defaults = { port: 8080, folder: './static', }; export default class ServerlessStaticLocalPlugin implements Plugin { commands = { serve: { usage: 'serve local directory', lifecycleEvents: ['start'], options: { port: { usage: `Static server port, default: ${defaults.port}`, shortcut: 'p', type: 'string', }, folder: { usage: `Static folder path, default: ${defaults.folder}`, shortcut: 'f', type: 'string', }, }, }, }; hooks: Plugin['hooks']; constructor(serverless: Serverless, options: PluginOptions) { const serverlessConfig = serverless.service.custom && serverless.service.custom.static ? serverless.service.custom.static : {}; const settings = { port: Number(options.port) || Number(options.p) || serverlessConfig.port || defaults.port, folder: options.folder || options.f || serverlessConfig.folder || defaults.folder, }; const startServer = () => serve(serverless, settings); this.hooks = { 'before:offline:start:init': startServer, 'serve:start': startServer, }; } }
mskim5383/safe-dynamicTest-generator
src/util/Ansicolors.ts
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // colorize output import Util = require('./Util') var use_color = true export function set_use_color(val: boolean) { use_color = val } export function green(s: string) { return xterm(2)(s); } export function red(s: string) { return xterm(1)(s); } export function xterm(n: number): (s: string) => string { return (s: string) => { if (!use_color) return s return '\033[38;5;'+n+'m' + s + '\033[0m' } } export function lightgrey(s: string) { return xterm(240)(s); } export function Gray(s: string) { Util.print(xterm(242)(s)) } export function Green(s: string) { Util.print(xterm(2)(s)) } export function Red(s: string) { Util.print(xterm(1)(s)) }
mskim5383/safe-dynamicTest-generator
src/Metric.ts
<reponame>mskim5383/safe-dynamicTest-generator /* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Functionality to evaluate programs. * * @author <NAME> <<EMAIL>> */ import Data = require('./Data') import Util = require('./util/Util') import Recorder = require('./Recorder') import Compile = require('./Compile') import Search = require('./Search') var print = Util.print var log = Util.log var line = Util.line var DISTANCE_NORM = 100 var W_ERROR_EXIT = 2 var W_EXIT = 1 var W_EXHAUSTED = 50000 var W_ASSIGN_FIELD = 0.6 var W_ASSIGN_VALUE = 0.5 var W_ASSIGN_WRONG = 0.9 var W_ASSIGN_MISSING = 1 var W_DELETE_FIELD = 0.5 var W_DELETE_WRONG = 0.9 var W_DELETE_MISSING = 1 var W_GET_FIELD = 0.2 var W_GET_WRONG = 0.3 var W_GET_MISSING = 0.4 var W_WRONG_PARAM = 0.5 var W_CALL_WRONG = 0.9 var W_CALL_MISSING = 1 /** * Evaluate how well program `p' behaves on the given inputs (the traces in `realTraces' are used as the * gold standard). Returns a non-negative value, where 0 means the program behaves identically (w.r.t. to our * metric) and the higher the number, the less similar `p's behavior. */ export function evaluate(p: Data.Program, inputs: any[][], realTraces: Data.Trace[], config: Search.SearchConfig, finalizing: boolean = false): number { return evaluate2(Compile.compile(p), inputs, realTraces, config, p.body.transitiveAnychildren().length, finalizing, p) } export function evaluate2(f: (...a: any[]) => any, inputs: any[][], realTraces: Data.Trace[], config: Search.SearchConfig, programLength: number = 10, finalizing: boolean = false, p = null): number { var badness = 0 for (var i = 0; i < inputs.length; i++) { var base = realTraces[i].events.length // give a budget of 150% compared to the real trace, but always // give at least 20 more, but don't exceed than 100 more var budget = base + Math.min(100, Math.max(20, 0.5 * base)) var candidateTrace = Recorder.record(f, inputs[i], budget) var td = traceDistance(realTraces[i], candidateTrace, config, p) Util.assert(td >= 0, () => "negative distance for " + realTraces[i] + " vs " + candidateTrace) badness += td } badness /= inputs.length if (finalizing) { var W_LENGTH = 0.0001 badness += W_LENGTH * programLength } return badness } /** * Determine how 'close' two traces are, and return a number describing the closeness. 0 is identical, * and the higher, the less similar the traces are. This is a metric. */ export function traceDistance(a: Data.Trace, b: Data.Trace, config: Search.SearchConfig, p = null): number { var debug = false var newDistance = config.metric == 0 if (newDistance) { return traceDistanceNew(a, b, p) } var naiveDistance = config.metric == 1 if (naiveDistance) { return traceDistanceNaive(a, b, p) } Util.assert(config.metric == 2) if (debug) { print(p) } var badness = 0 // exhausting computational budget is bad Util.assert(!a.isExhaustedBudget, () => "a should not have exhausted it's budget") if (b.isExhaustedBudget) { return W_EXHAUSTED } // compare all set events var aa0 = <Data.ESet[]>a.eventsOfKind(Data.EventKind.ESet) var bb0 = <Data.ESet[]>b.eventsOfKind(Data.EventKind.ESet) var notInB = 0 var used = new Map<number, boolean>() var notInA = bb0.length aa0.forEach((aevent) => { var ao = aevent.target var af = aevent.name var av = aevent.value var found = false for (var i = 0; i < bb0.length; i++) { if (!used.has(i)) { var bevent = bb0[i] var bo = bevent.target var bf = bevent.name var bv = bevent.value if (exprEquiv(ao, bo)) { if (exprEquiv(af, bf)) { if (!exprEquiv(av, bv)) { // receiver and field matches, but not the value badness += W_ASSIGN_VALUE * exprDistance(av, bv) / DISTANCE_NORM } } else { // receiver matches, but not field badness += W_ASSIGN_FIELD * exprDistance(af, bf) / DISTANCE_NORM } used.set(i, true) found = true notInA-- break } } } if (!found) { notInB++ } }) badness += Math.abs(notInA-notInB) * W_ASSIGN_MISSING badness += Math.min(notInA,notInB) * W_ASSIGN_WRONG if (debug) print("after set: " + badness) // compare all delete property events var aa1 = <Data.EDeleteProperty[]>a.eventsOfKind(Data.EventKind.EDeleteProperty) var bb1 = <Data.EDeleteProperty[]>b.eventsOfKind(Data.EventKind.EDeleteProperty) notInB = 0 used = new Map<number, boolean>() notInA = bb1.length aa1.forEach((aevent) => { var ao = aevent.target var af = aevent.name var found = false for (var i = 0; i < bb1.length; i++) { if (!used.has(i)) { var bevent = bb1[i] var bo = bevent.target var bf = bevent.name if (exprEquiv(ao, bo)) { if (!exprEquiv(af, bf)) { // receiver matches, but not field badness += W_DELETE_FIELD * exprDistance(af, bf) / DISTANCE_NORM } used.set(i, true) found = true notInA-- break } } } if (!found) { notInB++ } }) badness += Math.abs(notInA-notInB) * W_DELETE_MISSING badness += Math.min(notInA,notInB) * W_DELETE_WRONG if (debug) print("after delete: " + badness) // compare all get property events var aa1 = <Data.EGet[]>a.eventsOfKind(Data.EventKind.EGet) var bb1 = <Data.EGet[]>b.eventsOfKind(Data.EventKind.EGet) notInB = 0 used = new Map<number, boolean>() notInA = bb1.length aa1.forEach((aevent) => { var ao = aevent.target var af = aevent.name var found = false for (var i = 0; i < bb1.length; i++) { if (!used.has(i)) { var bevent = bb1[i] var bo = bevent.target var bf = bevent.name if (exprEquiv(ao, bo)) { if (!exprEquiv(af, bf)) { // receiver matches, but not field badness += W_GET_FIELD * exprDistance(af, bf) / DISTANCE_NORM } notInA-- found = true used.set(i, true) break } } } if (!found) { notInB++ } }) badness += Math.abs(notInA-notInB) * W_GET_MISSING badness += Math.min(notInA,notInB) * W_GET_WRONG if (debug) print("after get: " + badness) // compare all apply events var aa2 = <Data.EApply[]>a.eventsOfKind(Data.EventKind.EApply) var bb2 = <Data.EApply[]>b.eventsOfKind(Data.EventKind.EApply) notInB = 0 used = new Map<number, boolean>() notInA = bb2.length aa2.forEach((aevent) => { var arecv = aevent.receiver var af = aevent.target var aargs = aevent.args var found = false for (var i = 0; i < bb2.length; i++) { if (!used.has(i)) { var bevent = bb2[i] var brecv = bevent.receiver var bf = bevent.target var bargs = bevent.args if (arecv === brecv || exprEquiv(arecv, brecv)) { if (exprEquiv(af, bf)) { Util.assert(aargs.length === bargs.length, () => "different length of argument list") var argbadness = 0 for (var k = 0; k < aargs.length; k++) { if (!exprEquiv(aargs[k], bargs[k])) { // receiver and function matches, but not this argument argbadness += W_WRONG_PARAM * exprDistance(aargs[k], bargs[k]) / DISTANCE_NORM } else { } } if (aargs.length > 0) { badness += argbadness / aargs.length } used.set(i, true) found = true notInA-- break } } } } if (!found) { notInB++ } }) badness += Math.abs(notInA-notInB) * W_CALL_MISSING badness += Math.min(notInA,notInB) * W_CALL_WRONG if (debug) print("after call: " + badness) // normalize by the length of a if (a.events.length > 0) { badness /= a.events.length } // compare the last statement (return or throw) if (a.isNormalReturn === b.isNormalReturn) { if (a.isNormalReturn) { badness += W_EXIT * exprDistance(a.getResult(), b.getResult())/DISTANCE_NORM } else { badness += W_EXIT * exprDistance(a.getException(), b.getException())/DISTANCE_NORM } } else { // different way to return badness += W_ERROR_EXIT } if (debug) print("result: " + badness) return badness } function dist(a: Data.Event, b: Data.Event) { var aa = a.getParts() var bb = b.getParts() var badness = 0 for (var i = 0; i < aa.length; i++) { badness += exprDistance(aa[i], bb[i])/DISTANCE_NORM } return badness / aa.length } /** * Determine how 'close' two traces are, and return a number describing the closeness. 0 is identical, * and the higher, the less similar the traces are. This is a metric. */ export function traceDistanceNew(a: Data.Trace, b: Data.Trace, p = null): number { var debug = false if (debug) { print(p) } var badness = 0 // exhausting computational budget is bad Util.assert(!a.isExhaustedBudget, () => "a should not have exhausted it's budget") if (b.isExhaustedBudget) { return W_EXHAUSTED } var kinds = [Data.EventKind.EGet, Data.EventKind.EHas, Data.EventKind.ESet, Data.EventKind.EApply, Data.EventKind.EDeleteProperty] var events = kinds.map((kind) => [a.eventsOfKind(kind), b.eventsOfKind(kind)]) for (var tmp in events) { var aa = events[tmp][0] var bb = events[tmp][1] for (var i = 0; i < Math.min(aa.length, bb.length); i++) { badness += 0.5 * dist(aa[i], bb[i]) } badness += Math.abs(aa.length - bb.length) } // normalize by the length of a if (a.events.length > 0) { //badness /= a.events.length } // compare the last statement (return or throw) if (a.isNormalReturn === b.isNormalReturn) { if (a.isNormalReturn) { badness += W_EXIT * exprDistance(a.getResult(), b.getResult())/DISTANCE_NORM } else { badness += W_EXIT * exprDistance(a.getException(), b.getException())/DISTANCE_NORM } } else { // different way to return badness += W_ERROR_EXIT } if (debug) print("result: " + badness) return badness } export function traceDistanceNaive(a: Data.Trace, b: Data.Trace, p = null): number { var debug = false if (debug) { print(p) } var badness = 0 // exhausting computational budget is bad Util.assert(!a.isExhaustedBudget, () => "a should not have exhausted it's budget") if (b.isExhaustedBudget) { return W_EXHAUSTED } var kinds = [Data.EventKind.EGet, Data.EventKind.EHas, Data.EventKind.ESet, Data.EventKind.EApply, Data.EventKind.EDeleteProperty] var events = kinds.map((kind) => [a.eventsOfKind(kind), b.eventsOfKind(kind)]) for (var tmp in events) { var aa = events[tmp][0] var bb = events[tmp][1] for (var i = 0; i < Math.min(aa.length, bb.length); i++) { badness += (dist(aa[i], bb[i]) == 0 ? 0 : 1) } badness += Math.abs(aa.length - bb.length) } // normalize by the length of a if (a.events.length > 0) { //badness /= a.events.length } // compare the last statement (return or throw) if (a.isNormalReturn === b.isNormalReturn) { if (a.isNormalReturn) { badness += W_EXIT * exprDistance(a.getResult(), b.getResult())/DISTANCE_NORM } else { badness += W_EXIT * exprDistance(a.getException(), b.getException())/DISTANCE_NORM } } else { // different way to return badness += W_ERROR_EXIT } if (debug) print("result: " + badness) return badness } /** Returns a distance metric for two trace allocations */ function allocDist(va: Data.TraceAlloc, vb: Data.TraceAlloc): number { var fieldsA = [] var fieldsB = [] for (var f in va) { if (va.hasOwnProperty(f)) { fieldsA.push(f) } } for (var f in vb) { if (vb.hasOwnProperty(f)) { fieldsB.push(f) } } // TODO: this only works for primitive values at the moment var found = 0 var wrongVal = 0 var missing = 0 for (var fa in fieldsA) { if (fa in fieldsB) { found += 1 if (va[fa] !== vb[fa]) { // field present, but value is different wrongVal += 1 } else { // field equivalent, happy } } else { missing += 1 } } var tooMany = fieldsB.length - found var div = fieldsA.length if (div == 0) div = 1 return (wrongVal * 0.6 + missing + tooMany) * DISTANCE_NORM / div } /** * Compare two TraceExpr by considering their pre-state expressions. * Returns true if the two expressions are either the same primitive constant, or refer to the same * object (in the pre-state). */ function exprEquiv(a: Data.TraceExpr, b: Data.TraceExpr): boolean { if (a.type !== b.type) { return false } if (a.type === Data.TraceExprType.Const) { var va = (<Data.TraceConst>a).val var vb = (<Data.TraceConst>b).val if (va !== va) { // correct handling of NaN return vb !== vb } return va === vb } else if (a.type === Data.TraceExprType.General) { var as = a.preStateStrings() var bs = b.preStateStrings() return as.some((a) => bs.indexOf(a) !== -1) } else if (a.type === Data.TraceExprType.Alloc) { var va = (<Data.TraceAlloc>a).val var vb = (<Data.TraceAlloc>b).val return allocDist(va, vb) === 0 } Util.assert(false) return false } function exprDistance(a: Data.TraceExpr, b: Data.TraceExpr) { if (exprEquiv(a, b)) { return 0 } if (a.type === Data.TraceExprType.Alloc && b.type === Data.TraceExprType.Alloc) { var va = (<Data.TraceAlloc>a).val var vb = (<Data.TraceAlloc>b).val return allocDist(va, vb) } return DISTANCE_NORM }
mskim5383/safe-dynamicTest-generator
src/Score.ts
import Builtin = require('./Builtin') import Ansi = require('./util/Ansicolors') export function testInput(testSet) { var fName = testSet.name var f = Builtin.getFunction(fName) var score if (f === undefined) { score = -1 } else { score = test(f, testSet.inputs) } Ansi.Red(fName + " score : " + score) testSet.score = score return testSet } export function test(f, args: any) { var fstr = whileUnroll(f.toString(), 2) var fsplit = fstr.split(/{/) var len = fsplit.length var scoreLen = 0 var newfstr = fsplit[0] for (var i = 1; i < len; i++) { if ((fsplit[i-1].search('if') == -1) && (fsplit[i-1].search('else') == -1) && (fsplit[i-1].search('while') == -1) && (fsplit[i-1].search('for') == -1)) { newfstr += '{' + fsplit[i] } else { newfstr += '{\n_score[' + scoreLen + '] = 1;\n' + fsplit[i] scoreLen += 1 } } console.log(newfstr) var _score = new Array(scoreLen) var newFunc = eval('[' + newfstr + ']')[0] for (var i = 0; i < args.length; i++) { var arg = args[i] var thisVal = arg.thisVal var argument = arg.args try { newFunc.apply(thisVal, argument) } catch (err) { // TODO console.log("runtime error") throw err } } var scoreNum = 0 for (var i = 0; i < scoreLen; i++) { if (_score[i] == 1) { scoreNum++ } console.log('score[' + i + '] = ' + _score[i]) } return scoreNum / scoreLen } export function whileUnroll(fstr, depth) { var whileIdx = fstr.search('while') if (whileIdx == -1) { return fstr } var idx = whileIdx while (fstr[idx] != '(') { idx += 1 } var startIdx = idx idx += 1 var cnt = 1 while (cnt > 0) { if (fstr[idx] == '(') { cnt += 1 } else if (fstr[idx] == ')') { cnt -= 1 } idx += 1 } var endIdx = idx var condition = fstr.substring(startIdx, endIdx + 1) while (fstr[idx] != '{') { idx += 1 } startIdx = idx idx += 1 var cnt = 1 while (cnt > 0) { if (fstr[idx] == '{') { cnt += 1 } else if (fstr[idx] == '}') { cnt -= 1 } idx += 1 } endIdx = idx var fbody = fstr.substring(startIdx + 1, endIdx - 1) var newfstr = '' for (var i = 0; i < depth; i++) { newfstr += 'if ' + condition + '{\n' + fbody + '\n' } newfstr += 'while ' + condition + '{\n' + fbody + '\n' for (var i = 0; i < depth + 1; i++) { newfstr += '}\n' } return fstr.substring(0, whileIdx - 1) + newfstr + whileUnroll(fstr.substring(endIdx + 1), depth) } var ToObject = Builtin.ToObject var ToString = Builtin.ToString var ToNumber = Builtin.ToNumber var ToInt32 = Builtin.ToInt32 var ToUint32 = Builtin.ToUint32 var HasProperty = Builtin.HasProperty var ToInteger = Builtin.ToInteger var DefineOwnProperty = Builtin.DefineOwnProperty
mskim5383/safe-dynamicTest-generator
src/util/Util.ts
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Various utility functions. * * @author <NAME> <<EMAIL>> */ /// <reference path="../../ts-decl/node.d.ts" /> import util = require('util'); var random = require('random-js') export function print(s: any) { if (typeof s === "object" && s != null && "toString" in s) { console.log(s.toString()) } else { console.log(s) } } export function printnln(s: any) { process.stdout.write(s) } export function line(str?: any) { print("------------------------ " + (str || "")) } export function linereturn(str?: any) { return ("------------------------ " + (str || "")) } export function line2(str?: any) { print("======================== " + (str || "")) } export function log(o: any, colors?: boolean) { print(util.inspect(o, { colors: colors })) } export function log2(o: any, colors?: boolean) { print(util.inspect(o, { colors: colors, depth: 3 })) } export function log3(o: any, colors?: boolean) { print(util.inspect(o, { colors: colors, depth: 4 })) } export function logall(o: any, colors?: boolean) { print(util.inspect(o, { colors: colors, depth: null })) } export function inspect(o: any, colors: boolean = true): string { return util.inspect(o, { colors: colors }) } export function argv(i: number) { return process.argv[i] } export function argvlength() { return process.argv.length } // for now we keep this here, as it creates various spurious errors export function rrr(v: number) { if (v == -1) { v = Math.floor(Math.random() * 100000); print("Seed: " + v) } return new random(random.engines.mt19937().seed(v)) } export function isPrimitive(arg: any) { var type = typeof arg; return arg == null || (type != "object" && type != "function"); } export function assert(condition: boolean, message?: () => string) { if (!condition) { if (message) { throw new AssertionError("" + message() + "\n" + console.trace()) } throw new AssertionError("Assertion failed\n" + console.trace()) } } export function assert2(condition: boolean, message?: string) { if (!condition) { if (message) { throw new AssertionError("" + message + "\n" + console.trace()) } throw new AssertionError("Assertion failed\n" + console.trace()) } } export function dedup<T>(a: T[]): T[] { return a.filter(function(elem, pos) { return a.indexOf(elem) == pos; }) } export function dedup2<T>(a: T[]): T[] { return a.filter(function(elem, pos) { return indexOfEquals(a, elem) == pos; }) } export function indexOfEquals<T>(a: T[], item: T, start: number = 0): number { var j = start var count = a.length while (!(<any>a[j++]).equals(item) && j < count) {} j-- return (j === count) ? -1 : j } /** Sort the array `arr' in-place, using a list of functions that map an element to an integer property by which to sort. */ export function sortBy<T>(arr: T[], fns: { (a: T): number; }[]) { arr.sort((a, b) => { var r = 0 for (var i = 0; i < fns.length; i++) { r = fns[i](a) - fns[i](b) if (r !== 0) { return r } } return r }) } // non-ideal clone method // taken from: http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object export function clone<T>(obj: T): T { // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { var copy1 = new Date(); copy1.setTime((<Date> <any> obj).getTime()); return <T> <any> copy1; } // Handle Array if (obj instanceof Array) { var copy2 = []; for (var i = 0, len = (<any> obj).length; i < len; i++) { if (i in obj) { copy2[i] = clone(obj[i]); } } return <T> <any> copy2; } // Handle Object if (obj instanceof Object) { var copy3 = Object.create(Object.getPrototypeOf(obj)); for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy3[attr] = clone(obj[attr]); } return <T> <any> copy3; } throw new Error("Unable to copy obj! Its type isn't supported."); } export class AssertionError { constructor(public message: string) { } toString() { return "Assertion failure: " + this.message } } export function sum(a: number[]) { return a.reduce((a,b) => a+b, 0) } export function max(a: number[]) { return a.reduce((a,b) => a > b ? a : b, 0) } export function start(): number { return new Date().getTime() } export function stop(s: number): number { return start() - s } export function pad(n, width, z) { z = z || '0'; n = n + ''; return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n; } export function isInt(s: string) { return /^(\-|\+)?([0-9]+)$/.test(s) } export function hash(s: string) { var hash = 0, i, chr, len; if (s.length == 0) return hash; for (i = 0, len = s.length; i < len; i++) { chr = s.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; } export function indent(s: string, ind: string = ' ') { return ind + s.replace(/\n/g, "\n" + ind) } export function flatten<T>(as: T[][]): T[] { return as.reduce(function(a, b) { return a.concat(b); }) } export function arrayEquals<T>(a: T[], b: T[]): boolean { if (a.length !== b.length) { return false } for (var i = 0; i < a.length; i++) { if (!(<any>a[i]).equals(b[i])) { return false } } return true } export function join(arr: string[], sep: string) { var res = "" var first = true for (var i = 0; i < arr.length; i++) { if (!first) { res += sep } first = false res += arr[i] } return res } export function exit(code: number = 0) { process.exit(code) }
mskim5383/safe-dynamicTest-generator
src/util/Random.ts
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Randomness utilities - various small wrapper function for generating random values * and making random decicions * * @author <NAME> <<EMAIL>> */ import Util = require('./Util') // our source of randomness var randomness = null export function resetRandomness(val?: number) { randomness = Util.rrr(val) } /** * Returns a random number in [min,max), or [0,min) if max is not specified. */ export function randInt(min: number, max?: number): number { if (max == null) { max = min; min = 0; } return randomness.integer(min, max-1); } /** Returns a random floating point number. */ export function randFloat(min: number, max: number, inclusive: boolean = false): number { return randomness.real(min, max, inclusive); } /** Returns a random element from an array. */ export function randArr<T>(arr: T[]): T { Util.assert(arr.length > 0) return arr[randInt(arr.length)] } /** A class for weighted random samples, see pick below. */ export class WeightedPair<T> { constructor(public w: number, public e: T) { } } /** Return a random element from an array of weight/element pairs */ export function randArrW<T>(arr: T[], weights: number[]): T { Util.assert(arr.length > 0 && arr.length === weights.length) var total = weights.reduce((s, w) => w + s, 0) var rand = randFloat(0, total) var choice = 0 var sofar = 0 while (sofar <= rand) { sofar += weights[choice] choice += 1 } Util.assert(choice-1 < arr.length) return arr[choice-1] } /** Returns true with probability 'yesProbability'. */ export function maybe(yesProbability: number = 0.5) { return randFloat(0, 1) < yesProbability } /** Return a random element (respecting their weight). */ export function pick<T>(arr: WeightedPair<T>[]): T { return randArrW(arr.map((x) => x.e), arr.map((x) => x.w)) } /** * Return at most `n' randomly chosen elements from `arr' in a fresh array. */ export function pickN<T>(arr: T[], n: number): T[] { if (n >= arr.length) { return arr.slice(0) } var res = [] while (res.length < n) { var r = randInt(arr.length) if (res.indexOf(r) === -1) { res.push(r) } } return res.map((i) => arr[i]) }
mskim5383/safe-dynamicTest-generator
src/Search.ts
<filename>src/Search.ts<gh_stars>0 /* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Random search over javascript programs to find models. * * @author <NAME> <<EMAIL>> */ import Data = require('./Data') import Util = require('./util/Util') import Random = require('./util/Random') import Recorder = require('./Recorder') import Metric = require('./Metric') import Compile = require('./Compile') import StructureInference = require('./StructureInference') import InputGen = require('./InputGen') import ProgramGen = require('./ProgramGen') import Ansi = require('./util/Ansicolors') var maybe = Random.maybe var pick = Random.pick var print = Util.print var log = Util.log var line = Util.line var Gray = Ansi.Gray /** * Search for a model of a given function. */ export function search(f: (...a: any[]) => any, args: any[][], config: SearchConfig = new SearchConfig()): any[][] { if (config.debug) Ansi.Gray("Recording original execution...") var trace = Recorder.record(f, args[0]) if (config.debug) print(trace) if (config.debug) Ansi.Gray("Input generation...") var inputs = InputGen.generateInputs(f, args) var traces = inputs.map((i) => Recorder.record(f, i)) if (config.debug) Ansi.Gray("Found " + inputs.length + " inputs.") if (config.debug) console.log(inputs) if (config.debug) Ansi.Gray("Loop inference...") var loops = StructureInference.infer(traces) var loop = null var loopindex = -1 if (config.loopIndex != -1) { if (config.loopIndex >= 0) { loopindex = config.loopIndex loop = loops[loopindex] } } else { if (loops.length > 0) { var i = 0 if (config.debug) print(loops.filter((x) => i++ < 6).join("\n")) // randomly choose a loop if (Random.maybe(config.alphaloop)) { loopindex = 0 while (Random.maybe(1-config.alpha) && loopindex < loops.length-1) { loopindex += 1 } loop = loops[loopindex] } } } if (config.debug) Ansi.Gray("Found " + loops.length + " possible loops.") if (config.debug && loop != null) Ansi.Gray("Using this loop [" + loopindex + "]: " + loop) if (config.debug) Ansi.Gray("Input categorization...") var categories = InputGen.categorize(inputs, traces, loop) if (config.debug) Ansi.Gray("Found " + categories.length + " categories of inputs.") var realTraces = inputs.map((i) => Recorder.record(f, i)) var t = Recorder.record(f, inputs[0]) var p = Compile.compileTrace(t, loop) inputs = InputGen.selectInputs(inputs, realTraces, (i, t) => Metric.evaluate(p, [i], [t], config)) // TODO: use categories if (config.debug) Ansi.Gray("Selected " + inputs.length + " inputs.") if (config.debug) console.log(inputs) return inputs; } function isEqualModulaVar(a: Data.Expr, b: Data.Expr, vm: Map<Data.Var, Data.Var>) { if (a.type !== b.type) { return false } var rec = (a, b) => isEqualModulaVar(a, b, vm) var aa, bb switch (a.type) { case Data.ExprType.Field: aa = <Data.Field>a bb = <Data.Field>b return rec(aa.o, bb.o) && rec(aa.f, bb.f) case Data.ExprType.Const: aa = <Data.Const>a bb = <Data.Const>b return aa.val === bb.val case Data.ExprType.Arg: aa = <Data.Argument>a bb = <Data.Argument>b return rec(aa.i, bb.i) case Data.ExprType.Var: aa = <Data.Var>a bb = <Data.Var>b return vm.get(aa) === bb default: return false } } export function combinePrograms(progs: Data.Stmt[]) { if (progs.length === 1) { return progs[0] } var b = progs.pop() var a = progs.pop() var isLocalVarAssign = (s: Data.Stmt) => s.type === Data.StmtType.Assign && (<Data.Assign>s).isDecl && (<Data.Assign>s).rhs != null && (<Data.Assign>s).rhs.type === Data.ExprType.Field var isMarker = (s: Data.Stmt) => s.type === Data.StmtType.Marker var isResultAssign = (s: Data.Stmt) => s.type === Data.StmtType.Assign && (<Data.Assign>s).lhs.type === Data.ExprType.Var && (<Data.Var>((<Data.Assign>s).lhs)).name === "result" var getVar = (s: Data.Stmt) => <Data.Var>(<Data.Assign>s).lhs var getRhs = (s: Data.Stmt) => (<Data.Assign>s).rhs var prefix: Data.Stmt[] = [] var vm = new Map<Data.Var, Data.Var>() var aind = 0 var bind = 0 while (true) { var as = a.allStmts() var bs = b.allStmts() if (as.length <= aind || bs.length <= bind) { break } var a0 = as[aind] var b0 = bs[bind] // skip result assignments and markers if (isResultAssign(a0) || isMarker(a0)) { aind += 1 continue } if (isResultAssign(b0) || isMarker(b0)) { bind += 1 continue } // we can only deal with variable assignments here if (!isLocalVarAssign(a0) || !isLocalVarAssign(b0)) { break } var av = getVar(a0) var arhs = getRhs(a0) var bv = getVar(b0) var brhs = getRhs(b0) if (isEqualModulaVar(arhs, brhs, vm)) { vm.set(av, bv) prefix.push(a0) if (av.name != bv.name) { prefix.push(new Data.Assign(bv, av, true)) } a = a.replace(aind, Data.Seq.Empty) b = b.replace(bind, Data.Seq.Empty) aind = 0 bind = 0 } else { break } } var t = new Data.Const(true) prefix.push(new Data.If(t, a, b)) var res: Data.Stmt = new Data.Seq(prefix) if (progs.length === 0) { return res } return combinePrograms([res].concat(progs)) } export class SearchResult { static Empty = new SearchResult({ iterations: 0, result: <Data.Program>null, score: -1, loopIndex: -1, executions: 0, time: 0 }) public iterations: number public result: Data.Program public loopIndex: number public score: number public executions: number public time: number constructor(o: { iterations: any; result: Data.Program; score: number; executions: number; time: number; loopIndex: number }) { this.iterations = o.iterations this.result = o.result this.score = o.score this.executions = o.executions this.time = o.time this.loopIndex = o.loopIndex } combine(o: SearchResult): SearchResult { return new SearchResult({ iterations: this.iterations + o.iterations, result: this.result, score: this.score, executions: this.executions + o.executions, time: this.time + o.time, loopIndex: this.loopIndex }) } getStats(): string { var ex = (this.executions * 1000 / this.time).toFixed(2) var it = (this.iterations * 1000 / this.time).toFixed(2) var res = ex + " executions per second\n" + it + " iterations per second\n"; if (this.loopIndex >= 0) { res += "using the loop template with index: " + (this.loopIndex+1) } else { res += "using a loop-free template" } return res } } export class SearchConfig { static DEFAULT = { iterations: 50000, cleanupIterations: 0, debug: 0, loopIndex: -1, metric: 0, alwaysAcceptEqualCost: false, neverAcceptEqualCost: false, beta: 9, gamma: 6, alpha: 0.7, alphaloop: 0.9 } constructor(o: SearchConfig = SearchConfig.DEFAULT) { this.iterations = o.iterations this.cleanupIterations = o.cleanupIterations this.debug = o.debug this.loopIndex = o.loopIndex this.metric = o.metric this.alwaysAcceptEqualCost = o.alwaysAcceptEqualCost this.neverAcceptEqualCost = o.neverAcceptEqualCost this.beta = o.beta this.gamma = o.gamma this.alpha = o.alpha this.alphaloop = o.alphaloop Util.assert(!(this.alwaysAcceptEqualCost && this.neverAcceptEqualCost)) } iterations: number cleanupIterations: number debug: number loopIndex: number metric: number alwaysAcceptEqualCost: boolean neverAcceptEqualCost: boolean beta: number gamma: number alpha: number alphaloop: number toString(): string { return this.iterations + " core iterations, and " + this.cleanupIterations + " for cleanup, using loop " + this.loopIndex + ", and metric " + this.metric + ", and alpha " + this.alpha + ", and alphaloop " + this.alphaloop + ", and beta " + this.beta + ", and gamma " + this.gamma + (this.alwaysAcceptEqualCost ? ", and always accept equal cost" : "") + (this.neverAcceptEqualCost ? ", and never accept equal cost" : "") } } interface CoreSearchConfig { metric: (p: Data.Program) => number iterations: number randomChange: (p: Data.Program) => Data.Program base: SearchConfig only_better: boolean } function core_search(p: Data.Program, config: CoreSearchConfig): SearchResult { var start = Util.start() var badness = config.metric(p) var n = config.iterations var i for (i = 0; i < n; i++) { if (badness === 0) { // stop search if we found a perfect program break; } if (p.body.numberOfStmts() === 0) break; var newp = config.randomChange(p) var newbadness = config.metric(newp) var str = null//"result = result+n1" if (str != null && newp.toString().indexOf(str) != -1) { Ansi.Red(newp.toString()) print(badness + " => " + newbadness) } var base = config.base; if (newbadness < badness) { if (base.debug > 0) { Ansi.Gray(" improvement at iteration "+Util.pad(i, 5, ' ')+": " + Util.pad(badness.toFixed(3), 7, ' ') + " -> " + Util.pad(newbadness.toFixed(3), 7, ' ')) print(newp) } Util.assert(p.toString() != newp.toString()) p = newp badness = newbadness } else if (!config.only_better) { var alpha = Math.min(1, Math.exp(-base.beta * (newbadness - badness) - base.gamma)) if (base.alwaysAcceptEqualCost || (!base.neverAcceptEqualCost && maybe(alpha))) { if (base.debug > 0) { Ansi.Gray(" ! improvement at iteration "+Util.pad(i, 5, ' ')+": " + Util.pad(badness.toFixed(3), 7, ' ') + " -> " + Util.pad(newbadness.toFixed(3), 7, ' ')) Ansi.Green(newp.toString()) } //Util.assert(p.toString() != newp.toString(), () => ".") p = newp badness = newbadness } } if (i % 1000 === 0) { if (base.debug) print("Time: " + Util.stop(start) + ", iteration: " + i) } } var time = Util.stop(start) return new SearchResult({ iterations: i, result: p, score: badness, executions: -1, time:time, loopIndex: -1, }) } function shorten(p: Data.Program, inputs: any[][], realTraces: Data.Trace[], config: SearchConfig) { var badness = Metric.evaluate(p, inputs, realTraces, config) // remove whole statements var changed = true while (changed) { changed = false if (p.body.numberOfStmts() === 0) return p for (var i = 0; i < p.body.numberOfStmts(); i++) { var newp = new Data.Program(p.body.replace(i, Data.Seq.Empty)) var newbadness = Metric.evaluate(newp, inputs, realTraces, config) if (newbadness <= badness) { p = newp badness = newbadness changed = true break } } } // remove branches for (var i = 0; i < p.body.numberOfStmts(); i++) { var s:Data.Stmt = p.body.allStmts()[i] if (s.type === Data.StmtType.If) { var ss = <Data.If>s newp = new Data.Program(p.body.replace(i, ss.thn)) var newbadness = Metric.evaluate(newp, inputs, realTraces, config) if (newbadness <= badness) { p = newp badness = newbadness } else { newp = new Data.Program(p.body.replace(i, ss.els)) var newbadness = Metric.evaluate(newp, inputs, realTraces, config) if (newbadness <= badness) { p = newp badness = newbadness } } } } // move variable declarations end: while (true) { var body = p.body var change = false for (var ii = 0; ii < body.numberOfStmts(); ii++) { var s1: any = body.allStmts()[ii] if ("isDecl" in s1 && s1.isDecl) { for (var jj = ii + 1; jj < body.numberOfStmts(); jj++) { var s2: any = body.allStmts()[jj] if ("isDecl" in s2 && !s2.isDecl) { if (s1.v.equals(s2.v)) { var t = s2.clone() t.isDecl = true newp = new Data.Program(body.replace(jj, t).replace(ii, Data.Seq.Empty)) var newbadness = Metric.evaluate(newp, inputs, realTraces, config) if (newbadness <= badness) { p = newp badness = newbadness change = true continue end } } } } } } if (change == false) { break } } return p }
mskim5383/safe-dynamicTest-generator
src/run.ts
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Main entry point. * * @author <NAME> <<EMAIL>> */ import main = require('./main') import Util = require('./util/Util') import Random = require('./util/Random') import Ansi = require('./util/Ansicolors') import Data = require('./Data') import Search = require('./Search') import Recorder = require('./Recorder') import StructureInference = require('./StructureInference') import TestGen = require('./TestGen') import Score = require('./Score') import InputGen = require('./InputGen') var fs = require('fs') var log = Util.log var print = Util.print var line = Util.line function error(message) { print(Ansi.red("Error: " + message)) Util.exit(2) } Random.resetRandomness(-1) var safe_path if (Util.argvlength() < 2) { error('SAFE_PATH is not given') } else { safe_path = Util.argv(2) if (safe_path == "") { error('SAFE_PATH is empty') } safe_path += '/' } var data var dataList try { data = fs.readFileSync('./function-list.json', 'utf8') dataList = JSON.parse(data)['function-list'] } catch (err) { if (err.code === 'ENOENT') { error('function-list.json not found') } else if (err instanceof SyntaxError) { error('Invaild json format') } else { throw err } } if (dataList == undefined) { error('funcion-list field does not exists') } else if (!(dataList instanceof Array)) { error('function-list is not list') } var functionList = dataList.map(parseFunction) var config = new Search.SearchConfig() InputGen.config = config var inputSet = functionList.reduce(generateInputSet, []) inputSet.map(Score.testInput) var jsonList = inputSet.map(generateJson) var tests_path = safe_path + 'tests/dynamicTest/' if (!fs.existsSync(tests_path)) { try { fs.mkdir(tests_path) } catch (err) { error('Could not create dynamicTest directory') } } jsonList.map(test => saveTests(tests_path, test)) Util.exit(0) function parseFunction (e) { var name = e['name'] var fstr = e['function-body'] var args = [] var thisValArr = [] // try { // thisVal = e['thisVal'] // if (thisVal == undefined) { // thisVal = null // } else { // thisVal = eval(thisVal) // } // } catch (err) { // error('Could not parse thisVal:\n' + e['thisVal']) // } for (var i = 0; i < 10; i++) { var thisVal = Random.pickN([1, true, 'def', -1], 1)[0] //if (thisVal == -1) { if (true) { var t = [] for (var j = 0; j < Random.randInt(6, 10); j++) { t.push(Random.pickN([0, 1, -1, Infinity, -Infinity, "b", "def", true, false], 1)[0]) } thisValArr.push(t) } else thisValArr.push(thisVal) } if (name == undefined) { error('Function name does not exists:\n' + e.toString()) } if (fstr == undefined) { error('Function body does not exists:\n' + e.toString()) } var f try { f = eval('(' + fstr + ')') } catch (err) { error('Could not parse function:\n' + fstr) } if (!(f instanceof Function)) { error('function-body is not Function:\n' + fstr) } // try { // var arg = [thisVal].concat(eval('[' + e['args'] + ']')) // args.push(arg) // } catch (err) { // error('args is not any[][]:\n' + arg) // } // for (var i = 0; i < 10; i++) { var arg = Util.clone(Random.pickN(thisValArr, 1)) for (var j = 0; j < f.length + Random.randInt(3); j++) { arg.push(Random.pickN([0, 1, -1, Infinity, -Infinity, "b", "def", true, false], 1)[0]) } args.push(arg) } var func = function(self) { f.apply(self, Array.prototype.slice.call(arguments, 1)) } if (!(f instanceof Function)) { error('Function body is not javascript function:\n' + fstr) } return {'name': name, 'function': func, 'args': args, 'f': f} } function generateInputSet (inputSet, e) { console.time(e.name) e['inputs'] = [] var inputs = Search.search(e['function'], e['args'], config) for (var i = 0; i < inputs.length; i++) { var input = inputs[i] e.inputs.push({'thisVal': input[0], 'args': input.slice(1)}) } inputSet.push(e) console.timeEnd(e.name) return inputSet } function generateJson (test) { for (var i = 0; i < test.inputs.length; i++) { var input = test.inputs[i] var testJsonSAFE try { testJsonSAFE = TestGen.jsonGen(test['f'], input['thisVal'], input['args'], test['name']) } catch (err) { // TODO testJsonSAFE = {'error': true} } var testJson = {'name': test.name, 'thisVal': input.thisVal, 'args': input.args} input.json = testJsonSAFE input.testJson = testJson } return test } function saveTests (tests_path, test) { var name = test.name var inputs = test.inputs var test_path = tests_path + name + '/' if (!fs.existsSync(test_path)) { try { fs.mkdir(test_path) } catch (err) { error('Could not create test directory: ' + test_path) } } var tests = [] for (var i = 0; i < inputs.length; i++) { var json_name = name + '_' + i + '.json' var input = inputs[i] if (input.json.error) { // TODO continue } tests.push(input.testJson) try { fs.writeFileSync(test_path + json_name, input.json) Ansi.Green('Created ' + json_name) } catch (err) { Ansi.Red('Could not write test json: ' + json_name) } } fs.writeFileSync('./test.json', JSON.stringify(tests, null, 4)) } // function scoreTestSet (test) { // test.name ... mapping ... (test) // } // // var mapping = { // 'Array.prototype.pop': popScore // } // // function popScore(tests) { // var check = []; // var total; // function score(thisV, args) { // var len = ToUint32(lenVal); // if (len == 0) check[0] = true; // else check[1] = true; // } // // tests.... score(..., ...) // count = check ... // return count / total; // }
mskim5383/safe-dynamicTest-generator
src/Compile.ts
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Functionality to compile a Data.Program to JavaScript, as well as Data.Trace to Data.Program. * * @author <NAME> <<EMAIL>> */ import Util = require('./util/Util') import Ansi = require('./util/Ansicolors') import Data = require('./Data') import Recorder = require('./Recorder') import StructureInference = require('./StructureInference') var log = Util.log var print = Util.print var line = Util.line /** * Given a program, compile it into a regular function. */ export function compile(prog: Data.Program): (...a: any[]) => any { return compile2(prog.toString()) } /** * Like `compile', directly takes a string as input. */ export function compile2(prog: string): (...a: any[]) => any { return function (...a: any[]): any { var recv = Recorder.getReceiver() if (a.length === 0) { return new Function('"use strict";' + prog).apply(recv, a) } else if (a.length === 1) { return new Function("arg0", '"use strict";' + prog).apply(recv, a) } else if (a.length === 2) { return new Function("arg0", "arg1", '"use strict";' + prog).apply(recv, a) } else if (a.length === 3) { return new Function("arg0", "arg1", "arg2", '"use strict";' + prog).apply(recv, a) } else if (a.length === 4) { return new Function("arg0", "arg1", "arg2", "arg3", '"use strict";' + prog).apply(recv, a) } else if (a.length === 5) { return new Function("arg0", "arg1", "arg2", "arg3", "arg4", '"use strict";' + prog).apply(recv, a) } else if (a.length === 6) { return new Function("arg0", "arg1", "arg2", "arg3", "arg4", "arg5", '"use strict";' + prog).apply(recv, a) } return new Function('"use strict";' + prog).apply(recv, a) } } /** Compile a trace expression. */ function expr(e: Data.TraceExpr) { return e.curState[e.curState.length-1] } /** * Compile a list of events */ function compileEventList(events: Data.Event[], alloc: boolean, loop: StructureInference.Proposal = null) { function compileEvent(e: Data.Event): Data.Stmt { var ev switch (e.kind) { case Data.EventKind.EGet: ev = <Data.EGet>e return new Data.Assign(e.variable, new Data.Field(expr(ev.target), expr(ev.name)), true) break case Data.EventKind.EHas: ev = <Data.EHas>e return new Data.Assign(e.variable, new Data.Has(expr(ev.target), expr(ev.name)), true) case Data.EventKind.ESet: ev = <Data.ESet>e // save old value in local variable //stmts.push(new Data.Assign(new Data.Var(), new Data.Field(expr(ev.target), expr(ev.name)), true)) return new Data.Assign(new Data.Field(expr(ev.target), expr(ev.name)), expr(ev.value)) case Data.EventKind.EApply: ev = <Data.EApply>e var recv = null if (ev.receiver !== null) { recv = expr(ev.receiver) } return new Data.FuncCall(ev.variable, expr(ev.target), ev.args.map(expr), recv, true) case Data.EventKind.EDeleteProperty: ev = <Data.EDeleteProperty>e // save old value in local variable //stmts.push(new Data.Assign(new Data.Var(), new Data.Field(expr(ev.target), expr(ev.name)), true)) return new Data.DeleteProp(expr(ev.target), expr(ev.name)) default: Util.assert(false, ((inner_e) => () => "unknown event kind: " + inner_e)(e)) return null } } function compileEvents(events: Data.Event[]): Data.Stmt[] { return events.map(compileEvent) } if (loop == null) { return compileEvents(events) } // build loop body var body: Data.Stmt { // helper statements var resvar = new Data.Var("result", true) var resAssignment: Data.Stmt if (!alloc) { resAssignment = new Data.If(new Data.Const(true), new Data.Assign(resvar, resvar), Data.Seq.Empty) } else { resAssignment = new Data.If(new Data.Const(false), new Data.Assign(new Data.Field(resvar, new Data.Const(0)), new Data.Const(0)), Data.Seq.Empty) } var breakStmt = new Data.If(new Data.Const(false), new Data.Seq([resAssignment, <Data.Stmt>new Data.Break()]), Data.Seq.Empty) var trace = loop.trace var bodyStmts: Data.Stmt[] = [] // add a fake statement to make sure we get can catch infinite loops bodyStmts.push(new Data.Marker()) // prefix bodyStmts = bodyStmts.concat(compileEvents(trace.subEvents(loop.prefixStart, loop.prefixLen))) // conditional if (loop.thenLen != 0 || loop.elseLen != 0) { var thenBranch = compileEvents(trace.subEvents(loop.thenStart, loop.thenLen)) var elseBranch = compileEvents(trace.subEvents(loop.elseStart, loop.elseLen)) if (thenBranch.length != 0) { thenBranch.push(resAssignment) thenBranch.push(breakStmt) } if (elseBranch.length != 0) { elseBranch.push(resAssignment) elseBranch.push(breakStmt) } bodyStmts.push(new Data.If(new Data.Const(true), new Data.Seq(thenBranch), new Data.Seq(elseBranch))) } else { bodyStmts.push(resAssignment) bodyStmts.push(breakStmt) } body = new Data.Seq(bodyStmts) } var stmts: Data.Stmt[] = [] stmts = stmts.concat(compileEvents(trace.subEvents(0, loop.prefixStart))) // move variable declarations out of loop body { body.allStmts().forEach((n) => { if (n.type === Data.StmtType.Assign) { var ass = <Data.Assign>n if (ass.isDecl) { // note that we can only modify the assignments because they have not been shared yet ass.isDecl = false stmts.push(new Data.Assign(<Data.Var>ass.lhs, null, true)) } } else if (n.type === Data.StmtType.FuncCall) { var fcall = <Data.FuncCall>n if (fcall.isDecl) { // note that we can only modify the assignments because they have not been shared yet fcall.isDecl = false stmts.push(new Data.Assign(<Data.Var>fcall.v, null, true)) } } }) } // add everything stmts.push(new Data.For(new Data.Const(0), new Data.Const(0), new Data.Const(1), new Data.Seq(bodyStmts))) stmts = stmts.concat(compileEvents(trace.subEvents(loop.prefixStart + loop.unrolledLen))) return stmts; } /** * Compile a trace to a program. */ export function compileTrace(trace: Data.Trace, loop?: StructureInference.Proposal): Data.Program { var resvar = new Data.Assign(new Data.Var("result", true), null, true) var alloc = trace.isNormalReturn && trace.getResult() instanceof Data.TraceAlloc var stmts: Data.Stmt[] = compileEventList(trace.events, alloc, loop) if (trace.isNormalReturn) { if (alloc) { var obj = <Data.TraceAlloc>trace.getResult() resvar.rhs = new Data.Alloc(Array.isArray(obj.val)) stmts.push(new Data.Return(resvar.lhs)) } else { var res = expr(trace.getResult()) if (res instanceof Data.Const) { resvar.rhs = res stmts.push(new Data.Return(resvar.lhs)) } else { stmts.push(new Data.Return(res)) } } } else { stmts.push(new Data.Throw(expr(trace.getException()))) } stmts = [<Data.Stmt>resvar].concat(stmts) return new Data.Program(new Data.Seq(stmts)) }
mskim5383/safe-dynamicTest-generator
src/main.ts
<reponame>mskim5383/safe-dynamicTest-generator<gh_stars>10-100 /* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Main entry point for experimentation. * * @author <NAME> <<EMAIL>> */ "use strict"; import _difflib = require('./util/difflib') var difflib = _difflib.difflib import Ansi = require('./util/Ansicolors') import Util = require('./util/Util') import Random = require('./util/Random') import Data = require('./Data') import Metric = require('./Metric') import InputGen = require('./InputGen') import Recorder = require('./Recorder') import Compile = require('./Compile') import ProgramGen = require('./ProgramGen') import Search = require('./Search') import List = require('./LinkedList') import StructureInference = require('./StructureInference') var print = Util.print var log = Util.log var line = Util.line var Gray = Ansi.Gray var proxify = Recorder.proxifyWithLogger // -------------------------- /* function push(a, b) { return a.push(b); } function pop(a) { return a.pop(); } function defineProp(o, f, v) { Object.defineProperty(o, f, {value : v}); return o[f] } function id(a, b) { return b } function f2(o) { o.f = o.g o.h = o.g return o.h } run(pop, [["a", "a"]]) run(push, [["a"], "b"]) run(defineProp, [{}, "field", 42]) run(id, ["a", "a"]) run(f2, [{g: {}}]) */ var fs:any = [ [ // 0 "random heap modifications", (obj1, obj2, str, int) => { obj1.a = obj2 obj2[str] = obj2.g obj2[str] = "b" obj1.f2 = obj2.f return int }, [{}, {g: "a", f: {}}, "a", 0] ], [ // 1 "Array.prototype.pop", (arr) => arr.pop(), [['a', 'b', 'c']] ], [ // 2 "Array.prototype.push", (arr, ...args) => Array.prototype.push.apply(arr, args), [['a', 'b', 'c'], 'd'], [['a', 'b', 'c'], 'd', 'e', 'f'], [['a', 'b', 'c'], 'd', 'e', 'f', 'h'] ], [ // 3 "array index", (arr, i) => arr[i], [['a', 'b', 'c'], 2] ], [ // 4 "array function with conditional", (arr, i) => { if (i) { return arr } else { return arr[arr.length-1] } }, [['a', 'b', 'c'], 2] ], [ // 5 "simple higher order function", (f, i) => f(i), [(x) => x, 2], [(x) => 2*x, 2] ], [ // 6 "heap modifing higher order function", (setX, o, x, v) => setX(o, x, v), [(o, x, v) => o[x] = v, {}, 0, 0], [(o, x, v) => undefined, {}, 0, 0], ], [ // 7 "empty function", () => undefined, [] ], [ // 8 "Array.prototype.shift", (a) => a.shift(), [[1,2,3,,5]] ], [ // 9 "Array.prototype.every", (a, f) => a.every(f), [[0,5,2,20,3,23], (e) => e < 10] ], [ // 10 "Array.prototype.some", (a, f) => a.some(f), [[1,2,3], (e) => e < 10], [[1,2,3], (e) => e > 10], ], [ // 11 "Array.prototype.indexOf", (a, e) => a.indexOf(e), [[1,2,3], 2], ], [ // 12 "Array.prototype.forEach", (a, f) => a.forEach(f), [[1,2,3], (e) => 0], ], [ // 13 "Array.prototype.reduce", (a, f, z) => a.reduce(f, z), [[1,2,3], (previousValue, currentValue, index, array) => previousValue + currentValue, 0], ], [ // 14 "LinkedList.itemAt", (l: List.LinkedList, i) => l.itemAt(i), [List.LinkedList.make([1,2,3,4,5]), 3], [List.LinkedList.make([1,2,3]), 3], [List.LinkedList.make([1,2]), 3], [List.LinkedList.make([]), 3], ], [ // 15 "Array.prototype.slice(0,3)", (a: any[]) => a.slice(0, 3), [[1,2,3,4,5,6]], ], [ // 16 "Array.prototype.slice", (a: any[], low, high) => a.slice(0, high), [[1,2,3], 0, 3], ], [ // 17 "Array.prototype.map", (a: any[], b) => a.map(b), [[1,2,3], (x) => x+1], ], [ // 18 "Array.prototype.filter", (a: any[], b) => a.filter(b), [[0,5,2,20,3,23], (x) => x<2], ], [ // 19 "our sum function", (a: any[]) => { var result = 0; for (var i = 0; i < a.length; i++) result += a[i]; return result; }, [[4,5,6]], [[1,2,3]], ], [ // 20 "Array.prototype.reverse", (a: any[]) => a.reverse(), [[10,11,12,13,14]], ], ] var i = Util.argv(3) var name = fs[i][0] var f = fs[i][1] var a = fs[i].slice(2) var a0 = a[0] var config = new Search.SearchConfig() //config.cleanupIterations = 700 if (Util.argvlength() > 4) { config.loopIndex = +Util.argv(4) } //howMany(f, a, 10, [8000, 0], true) //Search.runSearch(f, a, config) //InputGen.generateInputs(f, a).map((a) => log(a)) //var x = [1,2,3,,5] //Recorder.proxifyWithLogger(x).shift() //Util.assert(false) var x = [1,2,3,,5,6] var trace = Recorder.record((a, b) => a.shift(b), [x, (x) => x + 1]) print(trace) var loop = StructureInference.infer([trace]) print(loop.slice(0, 10).join("\n")) //var program = Compile.compileTrace(trace, loop[0]); //print(program) //Util.assert(false) config.metric = 0 var debugFun = true function f2(arg0, arg1, arg2) { var result = 3 var n0 = arg0.length var n1 = arg0[0] var n2 var n5 = arg0 for (var i = 0; i < (n0-1); i += 1) { if (this != null) this.budget = 1 n2 = arg0[i+1] if (n2 != undefined) { arg0[i] = n2 } else { n5 = 1 in arg0 delete arg0[2] } } delete arg0[i] arg0[arguments.length] = n0-1 return result } if (debugFun) { var k = 0 var inputs = InputGen.generateInputs(f, a).filter((i) => k++ < 1000) //var ff = (x) => x < 10 //inputs = [ // [[ 1, 1, 0, 0, 1 ], ff,], // [[ 0, 0, 0, 20, 1, 0 ], ff,], // [[ 1, 5, 1, 1, 1, 23 ], ff,], // [[ 1, 1, 0, 20, 3, 23 ], ff,], // [[ 1, 1, 2, 1, 3, 1 ], ff,], // [[ 0, 5, 1, 0, 1, 0 ], ff,], // [[], ff,], // [[], ff,], // [[ 1], ff,], // [[ 0 ], ff,], // [[ 0, 1, 1, 0, 3 ], ff,], //] //inputs = [[[undefined], (previousValue, currentValue, index, array) => previousValue + currentValue, 0]] var traces = inputs.map((i) => Recorder.record(f, i)) var traces2 = inputs.map((i) => Recorder.record(f2, i)) a0 = inputs[0] Util.log(a0) var t1 = Recorder.record(f, a0) print(t1) var t2 = Recorder.record(f2, a0) print(t2) line() var prog = Compile.compileTrace(t1); print(prog) line() var jsonstr = JSON.stringify(prog); print(JSON.parse(jsonstr)) //log(inputs) line() print(Metric.evaluate2(f2, inputs, traces, config)) line() for (var k = 0; k < inputs.length && false; k++) { var m = Metric.traceDistance(traces[k], traces2[k], config); if (m > 0) { log(inputs[k]) print(m) print(traces[k]) print("====") print(traces2[k]) Util.line() } } } /* var aa = [] aa[2] = 10 aa[3] = 2 aa[10] = 10 Recorder.proxifyWithLogger(aa).every((a) => true) */ /* var inputs = a var traces = Recorder.all(f, inputs) var loops = StructureInference.infer(traces) var categories = InputGen.categorize(inputs, traces, loops[0]) log(categories)*/ /* var inputs = InputGen.generateInputs(f, a) var traces = inputs.map((i) => Recorder.record(f, i)) var loops = StructureInference.infer(traces) var loop = loops[0] var trace: Data.Trace = traces[0] var p0 = Compile.compileTrace(trace) print(traces[0]) line() print(loops.join("\n")) line() print(Compile.compileTrace(trace, loop)) */ /* var ff = f var aa = a var gen = InputGen.generateInputs(ff, aa) Util.logall(gen) */ /* function loop(o, b) { for (var f in o) { o[f]++ if (b) break } } function loop2(o) { for (var i = 0; i < o.length; i++) { o[i]++ } } loop(proxify({a: 0, b: 2, c: 3}), false) line() loop(proxify({a: 0, b: 2, c: 3}), true) line() loop(proxify([1, 2, 3]), false) line() loop2(proxify([1, 2, 3])) */ /* var a1 = proxify([1, 2, 3], "a") var a2 = proxify([3, 4], "b") var pred = proxify((n) => n < 2, "f") print("a1.every(pred)") a1.every(pred) line() print("a1.concat(a2)") a1.concat(a2) line() print("a1.shift()") a1.shift() line() print("a1.join(.)") a1.join(".") line() */ /* proxify([1, 2, 3, 5, 6]).shift() line() proxify([1, 2, 3, 5]).shift() line() proxify([]).shift() */ // trace recording /* var gl function init() { gl = { a: Recorder.proxifyWithLogger([1,2,3,4,5,6], "a"), b: Recorder.proxifyWithLogger(['a','b','c','d'], "b"), c: Recorder.proxifyWithLogger([6,4,2,1,5,3], "a"), f: (x) => x % 2 == 0 } } line() print("Configuration:") print(" a = [1,2,3,4,5,6]") print(" b = ['a','b','c','d']") print(" c = [6,4,2,1,5,3]") print(" f = (x) => x % 2 == 0") line() print("a.shift()") init() gl.a.shift() line() print("a.unshift('a')") init() gl.a.unshift('a') line() print("a.concat(b)") init() gl.a.concat(gl.b) line() print("a.every(f)") init() gl.a.every(gl.f) line() print("a.filter(f)") init() gl.a.filter(gl.f) line() print("a.some(f)") init() gl.a.some(gl.f) line() print("a.forEach(f)") init() gl.a.forEach(gl.f) line() print("a.indexOf(4)") init() gl.a.indexOf(4) line() print("a.indexOf(7)") init() gl.a.indexOf(7) line() print("a.join(',')") init() gl.a.join(',') line() print("a.lastIndexOf(4)") init() gl.a.lastIndexOf(4) line() print("a.map(f)") init() gl.a.map(gl.f) line() print("a.reverse()") init() gl.a.reverse() line() print("c.sort()") init() //gl.c.sort() print("actually fails with an illegal access violation") line() var gl2 function init2() { gl2 = { l: Recorder.proxifyWithLogger(List.LinkedList.make([1,2,3,4,5]), "l"), } } line() print("Configuration:") print(" l = <1,2,3,4,5,6>") print("Methods ending in R are recursive, everything else is iterative") line() init2() print("l.itemAt(3)") gl2.l.itemAt(3) line() init2() print("l.getSize()") gl2.l.getSize() line() init2() print("l.getLast()") gl2.l.getLast() line() init2() print("l.addFront(0)") gl2.l.addFront(0) line() init2() print("l.addBack(0)") gl2.l.addBack(0) line() init2() print("l.removeFirst()") gl2.l.removeFirst() line() init2() print("l.itemAtR(3)") gl2.l.itemAtR(3) line() */ /* var aaa = [1,2,3,1,1,1,1,1,1,1,11,1,1,1,1,1,1,1,1,11,1,1,1,1,1,1,1] var start = Util.start() for (var j = 0; j < 1000000; j++) { Recorder.proxifyWithLogger2(aaa) if (j % 10000 === 0) { print("Time: " + Util.stop(start) + ", iteration: " + j) } } */ /* var patch = (function (global) { "use strict"; var has = Object.prototype.hasOwnProperty; return function (original, originalRef, patches) { global[originalRef] = original; // Maintain a reference to the original constructor as a new property on the global object var args = [], newRef, // This will be the new patched constructor i; patches.called = patches.called || originalRef; // If we are not patching static calls just pass them through to the original function for (i = 0; i < original.length; i++) { // Match the arity of the original constructor args[i] = "a" + i; // Give the arguments a name (native constructors don't care, but user-defined ones will break otherwise) } if (patches.constructed) { // This string is evaluated to create the patched constructor body in the case that we are patching newed calls args.push("'use strict'; return (!!this ? " + patches.constructed + " : " + patches.called + ").apply(null, arguments);"); } else { // This string is evaluated to create the patched constructor body in the case that we are only patching static calls args.push("'use strict'; return (!!this ? new (Function.prototype.bind.apply(" + originalRef + ", [{}].concat([].slice.call(arguments))))() : " + patches.called + ".apply(null, arguments));"); } //newRef = new (Function.prototype.bind.apply(Function, [{}].concat(args)))(); // Create a new function to wrap the patched constructor newRef = Function.apply(null, args); newRef.prototype = original.prototype; // Keep a reference to the original prototype to ensure instances of the patch appear as instances of the original newRef.prototype.constructor = newRef; // Ensure the constructor of patched instances is the patched constructor Object.getOwnPropertyNames(original).forEach(function (property) { // Binary any "static" properties of the original constructor to the patched one if (!has.call(Function, property)) { // Don't include static properties of Function since the patched constructor will already have them newRef[property] = original[property]; } }); return newRef; // Return the patched constructor }; })(global); print(typeof String("abc")) print(typeof String(20)) String = patch(String, "StringOriginal", { called: function (arg) { return typeof arg === "number" ? arg : StringOriginal(arg); } }); Array = patch(String, "ArrayOriginal", { called: function (arg) { console.log(2) return ArrayOriginal(arg); } }); print(typeof String("abc")) print(typeof String(20))*/ /* var oldArray = Array Array = <any>function () { print("1") return oldArray.apply(this, arguments) } for (var k in oldArray) { print(k) } for (var k in oldArray.prototype) { print(k) }*/ //print(Array(1, 2, 3)) //print(new Array(1, 2, 3)) //print([1,2,3]); /* var oldObject = Object Object = <any>function () { console.log(":") return oldObject.apply(this, arguments) } Object.create = oldObject.create Object.keys = oldObject.keys Object.getOwnPropertyDescriptor = oldObject.getOwnPropertyDescriptor Object.defineProperty = function () { //global.console.log("f") return oldObject.defineProperty.apply(this, arguments) } var oldArray = Array Array = <any>function () { console.log(".") return oldArray.apply(this, arguments) } Array.isArray = oldArray.isArray Array = proxify(Array) console.log(Array(1,2)) console.log(new Array(1,2,3)) console.log([1,2].concat([2,3])) console.log(Object()) console.log(new Object()) console.log({ a: 1 }) console.log(Object.create({ b: 2})) */
mskim5383/safe-dynamicTest-generator
src/util/difflib.ts
<reponame>mskim5383/safe-dynamicTest-generator /*** This is part of jsdifflib v1.0. <http://snowtide.com/jsdifflib> Copyright (c) 2007, Snowtide Informatics Systems, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Snowtide Informatics Systems nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***/ /* Author: <NAME> <<EMAIL>> */ var __whitespace = {" ":true, "\t":true, "\n":true, "\f":true, "\r":true}; export var difflib = { defaultJunkFunction: function (c) { return __whitespace.hasOwnProperty(c); }, stripLinebreaks: function (str) { return str.replace(/^[\n\r]*|[\n\r]*$/g, ""); }, stringAsLines: function (str) { var lfpos = str.indexOf("\n"); var crpos = str.indexOf("\r"); var linebreak = ((lfpos > -1 && crpos > -1) || crpos < 0) ? "\n" : "\r"; var lines = str.split(linebreak); for (var i = 0; i < lines.length; i++) { lines[i] = difflib.stripLinebreaks(lines[i]); } return lines; }, // iteration-based reduce implementation __reduce: function (func, list, initial) { if (initial != null) { var value = initial; var idx = 0; } else if (list) { var value = list[0]; var idx = 1; } else { return null; } for (; idx < list.length; idx++) { value = func(value, list[idx]); } return value; }, // comparison function for sorting lists of numeric tuples __ntuplecomp: function (a, b) { var mlen = Math.max(a.length, b.length); for (var i = 0; i < mlen; i++) { if (a[i] < b[i]) return -1; if (a[i] > b[i]) return 1; } return a.length == b.length ? 0 : (a.length < b.length ? -1 : 1); }, __calculate_ratio: function (matches, length) { return length ? 2.0 * matches / length : 1.0; }, // returns a function that returns true if a key passed to the returned function // is in the dict (js object) provided to this function; replaces being able to // carry around dict.has_key in python... __isindict: function (dict) { return function (key) { return dict.hasOwnProperty(key); }; }, // replacement for python's dict.get function -- need easy default values __dictget: function (dict, key, defaultValue) { return dict.hasOwnProperty(key) ? dict[key] : defaultValue; }, SequenceMatcher: function (a, b, isjunk?) { this.set_seqs = function (a, b) { this.set_seq1(a); this.set_seq2(b); } this.set_seq1 = function (a) { if (a == this.a) return; this.a = a; this.matching_blocks = this.opcodes = null; } this.set_seq2 = function (b) { if (b == this.b) return; this.b = b; this.matching_blocks = this.opcodes = this.fullbcount = null; this.__chain_b(); } this.__chain_b = function () { var b = this.b; var n = b.length; var b2j = this.b2j = {}; var populardict = {}; for (var i = 0; i < b.length; i++) { var elt = b[i]; if (b2j.hasOwnProperty(elt)) { var indices = b2j[elt]; if (n >= 200 && indices.length * 100 > n) { populardict[elt] = 1; delete b2j[elt]; } else { indices.push(i); } } else { b2j[elt] = [i]; } } for (var elt in populardict) { if (populardict.hasOwnProperty(elt)) { delete b2j[elt]; } } var isjunk = this.isjunk; var junkdict = {}; if (isjunk) { for (var elt in populardict) { if (populardict.hasOwnProperty(elt) && isjunk(elt)) { junkdict[elt] = 1; delete populardict[elt]; } } for (var elt in b2j) { if (b2j.hasOwnProperty(elt) && isjunk(elt)) { junkdict[elt] = 1; delete b2j[elt]; } } } this.isbjunk = difflib.__isindict(junkdict); this.isbpopular = difflib.__isindict(populardict); } this.find_longest_match = function (alo, ahi, blo, bhi) { var a = this.a; var b = this.b; var b2j = this.b2j; var isbjunk = this.isbjunk; var besti = alo; var bestj = blo; var bestsize = 0; var j = null; var k; var j2len = {}; var nothing = []; for (var i = alo; i < ahi; i++) { var newj2len = {}; var jdict = difflib.__dictget(b2j, a[i], nothing); for (var jkey in jdict) { if (jdict.hasOwnProperty(jkey)) { j = jdict[jkey]; if (j < blo) continue; if (j >= bhi) break; newj2len[j] = k = difflib.__dictget(j2len, j - 1, 0) + 1; if (k > bestsize) { besti = i - k + 1; bestj = j - k + 1; bestsize = k; } } } j2len = newj2len; } while (besti > alo && bestj > blo && !isbjunk(b[bestj - 1]) && a[besti - 1] == b[bestj - 1]) { besti--; bestj--; bestsize++; } while (besti + bestsize < ahi && bestj + bestsize < bhi && !isbjunk(b[bestj + bestsize]) && a[besti + bestsize] == b[bestj + bestsize]) { bestsize++; } while (besti > alo && bestj > blo && isbjunk(b[bestj - 1]) && a[besti - 1] == b[bestj - 1]) { besti--; bestj--; bestsize++; } while (besti + bestsize < ahi && bestj + bestsize < bhi && isbjunk(b[bestj + bestsize]) && a[besti + bestsize] == b[bestj + bestsize]) { bestsize++; } return [besti, bestj, bestsize]; } this.get_matching_blocks = function () { if (this.matching_blocks != null) return this.matching_blocks; var la = this.a.length; var lb = this.b.length; var queue = [[0, la, 0, lb]]; var matching_blocks = []; var alo, ahi, blo, bhi, qi, i, j, k, x; while (queue.length) { qi = queue.pop(); alo = qi[0]; ahi = qi[1]; blo = qi[2]; bhi = qi[3]; x = this.find_longest_match(alo, ahi, blo, bhi); i = x[0]; j = x[1]; k = x[2]; if (k) { matching_blocks.push(x); if (alo < i && blo < j) queue.push([alo, i, blo, j]); if (i+k < ahi && j+k < bhi) queue.push([i + k, ahi, j + k, bhi]); } } matching_blocks.sort(difflib.__ntuplecomp); var i1 = 0, j1 = 0, k1 = 0, block = 0; var i2, j2, k2; var non_adjacent = []; for (var idx in matching_blocks) { if (matching_blocks.hasOwnProperty(idx)) { block = matching_blocks[idx]; i2 = block[0]; j2 = block[1]; k2 = block[2]; if (i1 + k1 == i2 && j1 + k1 == j2) { k1 += k2; } else { if (k1) non_adjacent.push([i1, j1, k1]); i1 = i2; j1 = j2; k1 = k2; } } } if (k1) non_adjacent.push([i1, j1, k1]); non_adjacent.push([la, lb, 0]); this.matching_blocks = non_adjacent; return this.matching_blocks; } this.get_opcodes = function () { if (this.opcodes != null) return this.opcodes; var i = 0; var j = 0; var answer = []; this.opcodes = answer; var block, ai, bj, size, tag; var blocks = this.get_matching_blocks(); for (var idx in blocks) { if (blocks.hasOwnProperty(idx)) { block = blocks[idx]; ai = block[0]; bj = block[1]; size = block[2]; tag = ''; if (i < ai && j < bj) { tag = 'replace'; } else if (i < ai) { tag = 'delete'; } else if (j < bj) { tag = 'insert'; } if (tag) answer.push([tag, i, ai, j, bj]); i = ai + size; j = bj + size; if (size) answer.push(['equal', ai, i, bj, j]); } } return answer; } // this is a generator function in the python lib, which of course is not supported in javascript // the reimplementation builds up the grouped opcodes into a list in their entirety and returns that. this.get_grouped_opcodes = function (n) { if (!n) n = 3; var codes = this.get_opcodes(); if (!codes) codes = [["equal", 0, 1, 0, 1]]; var code, tag, i1, i2, j1, j2; if (codes[0][0] == 'equal') { code = codes[0]; tag = code[0]; i1 = code[1]; i2 = code[2]; j1 = code[3]; j2 = code[4]; codes[0] = [tag, Math.max(i1, i2 - n), i2, Math.max(j1, j2 - n), j2]; } if (codes[codes.length - 1][0] == 'equal') { code = codes[codes.length - 1]; tag = code[0]; i1 = code[1]; i2 = code[2]; j1 = code[3]; j2 = code[4]; codes[codes.length - 1] = [tag, i1, Math.min(i2, i1 + n), j1, Math.min(j2, j1 + n)]; } var nn = n + n; var group = []; var groups = []; for (var idx in codes) { if (codes.hasOwnProperty(idx)) { code = codes[idx]; tag = code[0]; i1 = code[1]; i2 = code[2]; j1 = code[3]; j2 = code[4]; if (tag == 'equal' && i2 - i1 > nn) { group.push([tag, i1, Math.min(i2, i1 + n), j1, Math.min(j2, j1 + n)]); groups.push(group); group = []; i1 = Math.max(i1, i2-n); j1 = Math.max(j1, j2-n); } group.push([tag, i1, i2, j1, j2]); } } if (group && !(group.length == 1 && group[0][0] == 'equal')) groups.push(group) return groups; } this.ratio = function () { var matches = difflib.__reduce( function (sum, triple) { return sum + triple[triple.length - 1]; }, this.get_matching_blocks(), 0); return difflib.__calculate_ratio(matches, this.a.length + this.b.length); } this.quick_ratio = function () { var fullbcount, elt; if (this.fullbcount == null) { this.fullbcount = fullbcount = {}; for (var i = 0; i < this.b.length; i++) { elt = this.b[i]; fullbcount[elt] = difflib.__dictget(fullbcount, elt, 0) + 1; } } fullbcount = this.fullbcount; var avail = {}; var availhas = difflib.__isindict(avail); var numb var matches = numb = 0; for (var i = 0; i < this.a.length; i++) { elt = this.a[i]; if (availhas(elt)) { numb = avail[elt]; } else { numb = difflib.__dictget(fullbcount, elt, 0); } avail[elt] = numb - 1; if (numb > 0) matches++; } return difflib.__calculate_ratio(matches, this.a.length + this.b.length); } this.real_quick_ratio = function () { var la = this.a.length; var lb = this.b.length; return difflib.__calculate_ratio(Math.min(la, lb), la + lb); } this.isjunk = isjunk ? isjunk : difflib.defaultJunkFunction; this.a = this.b = null; this.set_seqs(a, b); } };
mskim5383/safe-dynamicTest-generator
src/Data.ts
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Data structures for programs, statements, expressions and traces. * * @author <NAME> <<EMAIL>> */ import Util = require('./util/Util') var print = Util.print var log = Util.log var line = Util.line /** * Serialization code (stupid, but works well enough) */ export class Serialize { } /** * Common ancestor for expressions and statements. */ export class Node { type: any /* Returns all direct child nodes (of type Node) */ children(): Node[] { Util.assert(false) return [] } transitiveChildren(): Node[] { var res = this.children() var l = res.length; for (var i = 0; i < l; i++) { res = res.concat(res[i].transitiveChildren()) } return res } transitiveAnychildren(): Node[] { var res = this.anychildren() var l = res.length; for (var i = 0; i < l; i++) { var cur = res[i]; if (typeof cur === "object" && cur != null && "transitiveAnychildren" in cur) { res = res.concat(cur.transitiveAnychildren()) } } return res } /* Returns all direct children (that are somehow relevant for equality) */ anychildren(): any[] { Util.assert(false) return [] } toSkeleton(): string { Util.assert(false, () => "getSkeleton not implemented for " + this) return null } } function clone(config) { var res = {} for (var k in config) { if (config.hasOwnProperty(k)) { res[k] = config[k] } } return res } var __noparen_config = { noparen: true } function noparen(config = undefined) { if (config === undefined) { return __noparen_config } if ("noparen" in config) { return config } config = clone(config) config.noparen = true return config } function reset(config) { if ("noparen" in config) { config = clone(config) delete config.noparen } return config } /** * An enum for expressions. */ export enum ExprType { Field = 1000, // make sure these don't collide with other types Arg, Var, Const, Binary, Unary, Alloc, Has, } /** * Common ancestor for all expressions. */ export class Expr extends Node { constructor(public type: ExprType, public depth: number) { super() } /** * Evaluate this expression over args. Assumes this.isSafe(args) === true. */ eval(args: any[]): any { Util.assert(false) } /** * Update the value of this expression in args to `val'. Assumes that this.canBeUpdate(args) === true. */ update(args: any[], val: any): any { Util.assert(false) } equals(o): boolean { Util.assert(false) return false } /** * Returns true if the expression (interpreted over args) can be updated. * * For instance, a constant cannot be updated, or a field of something that isn't an object or array. */ canBeUpdated(args: any[]): boolean { Util.assert(false) return false } /** * Returns true if the expression (interpreted over arg) already has the value `val'. * Assumes that this.canBeUpdate(args) === true. */ isUpdateNop(args: any[], val: any): boolean { Util.assert(false) return false } /** * Returns true if the expression interpreted over args makes sense and can safely be accessed. */ isSafe(args: any[]): boolean { Util.assert(false) return false } toString(config = {}): string { Util.assert(false) return "" } /** * Return the type of this expression (best effort, might not be known). */ getType(): string { return undefined } } /** * A marker class for Field and Argument */ export class Prestate extends Expr { getBase(): Prestate { return this } } /** * A field access. */ export class Field extends Prestate { constructor(public o: Expr, public f: Expr) { super(ExprType.Field, 1+Math.max(o.depth, f.depth)) } toString(config = {}) { config = reset(config) if (this.f.type === ExprType.Const) { var c = <Const>this.f if (typeof c.val === "string") { if (/^[a-zA-Z_][_a-zA-Z0-9]*$/.test(c.val)) { return this.o.toString(noparen(config)) + "." + c.val } if (/^[1-9][0-9]*$/.test(c.val) || c.val === "0") { return this.o.toString(noparen(config)) + "[" + c.val + "]" } } } return this.o.toString(noparen(config)) + "[" + this.f.toString(noparen(config)) + "]" } eval(args: any[]): any { return this.o.eval(args)[this.f.eval(args)] } update(args: any[], val: any): any { this.o.eval(args)[this.f.eval(args)] = val } equals(o) { return o instanceof Field && o.f.equals(this.f) && o.o.equals(this.o) } children(): Node[] { return [this.o, this.f] } anychildren(): any[] { return this.children() } toSkeleton(): string { return this.o.toSkeleton() + "[" + this.f.toSkeleton() + "]" } canBeUpdated(args: any[]): boolean { if (!this.isSafe(args)) { return false } var o = this.o.eval(args) var i = this.f.eval(args) return !(Array.isArray(o) && (i < 0 || i >= o.length)); } isUpdateNop(args: any[], val: any): boolean { return this.eval(args) === val } isSafe(args: any[]): boolean { return this.o.isSafe(args) && this.canHaveFields(this.o.eval(args)) } private canHaveFields(oVal: any) { var type = typeof oVal; return oVal !== null && (type === 'object' || type === 'function') } getBase() { Util.assert(this.o instanceof Prestate) return (<Prestate>this.o).getBase() } getType() { if (this.f instanceof Const && (<Const>this.f).val === "length" && this.o instanceof Var && ((<Var>this.o).name === "arguments" || (<Var>this.o).name === "result")) { return "number" } return undefined } isTraceableFieldRead(): boolean { if (this.o.type === ExprType.Var) { var o = <Var>this.o if (o.name === "arguments" || o.name === "result") { return false } } return true } } /** * A 'has' expression */ export class Has extends Expr { constructor(public o: Expr, public f: Expr) { super(ExprType.Has, 1+Math.max(o.depth, f.depth)) } toString(config = {}) { config = reset(config) if (this.f.type === ExprType.Const) { var c = <Const>this.f if (typeof c.val === "string") { if (/^[0-9]+$/.test(c.val)) { return c.val + " in " + this.o.toString(config) } } } return this.f.toString(config) + " in " + this.o.toString(config) + "" } eval(args: any[]): any { return this.f.eval(args) in this.o.eval(args) } update(args: any[], val: any): any { Util.assert(false) } equals(o) { return o instanceof Has && o.f.equals(this.f) && o.o.equals(this.o) } children(): Node[] { return [this.o, this.f] } anychildren(): any[] { return this.children() } toSkeleton(): string { return this.f.toSkeleton() + " in " + this.o.toSkeleton() } canBeUpdated(args: any[]): boolean { return false } isUpdateNop(args: any[], val: any): boolean { Util.assert(false) return false } isSafe(args: any[]): boolean { return true } getType() { return "boolean" } } /** * A binary expression. */ export class Binary extends Expr { constructor(public a: Expr, public op: string, public b: Expr) { super(ExprType.Binary, 1+Math.max(a.depth, b.depth)) Util.assert(op === "+" || op === "-" || op === "==" || op === "<" || op === "/") } toString(config = {}) { var pre = "(" var post = ")" if ("noparen" in config) { pre = "" post = "" } config = reset(config) if (this.b.type === ExprType.Const && this.op === "+") { var c = <Const>this.b if (c.val < 0) { return pre + this.a.toString(config) + "-" + (new Const(-c.val)).toString(config) + post } } return pre + this.a.toString(config) + this.op + this.b.toString(config) + post } eval(args: any[]): any { switch (this.op) { case "+": return this.a.eval(args)+this.b.eval(args) case "-": return this.a.eval(args)-this.b.eval(args) case "/": return this.a.eval(args)/this.b.eval(args) case "==": return this.a.eval(args) == this.b.eval(args) default: Util.assert(false) return false } } equals(o) { return o instanceof Binary && o.a.equals(this.a) && o.b.equals(this.b) && o.op === this.op } children(): Node[] { return [this.a, this.b] } anychildren(): any[] { var res: any[] = this.children() res.push(this.op) return res } toSkeleton(): string { return this.a.toSkeleton() + this.op + this.b.toSkeleton() } canBeUpdated(args: any[]): boolean { return false } isSafe(args: any[]): boolean { return this.a.isSafe(args) && this.b.isSafe(args) } getType(): string { if (this.op === "+" || this.op === "-" || this.op === "/") { return "number" } if (this.op === "==") { return "boolean" } if (this.op === "<") { return "boolean" } Util.assert(false) return undefined } } /** * Unary operation. */ export class Unary extends Expr { constructor(public op: string, public e: Expr) { super(ExprType.Unary, 1+e.depth) Util.assert(op === "!") } toString(config = {}) { config = reset(config) return this.op + this.e.toString(config) } eval(args: any[]): any { return !this.e.eval(args) } equals(o) { return o instanceof Unary && o.e.equals(this.e) && o.op === this.op } children(): Node[] { return [this.e] } anychildren(): any[] { var res: any[] = this.children() res.push(this.op) return res } toSkeleton(): string { return this.op + this.e.toSkeleton() } canBeUpdated(args: any[]): boolean { return false } isSafe(args: any[]): boolean { return this.e.isSafe(args) } getType(): string { if (this.op === "!") { return "boolean" } Util.assert(false) return undefined } } /** * The i-th argument of a function. */ export class Argument extends Prestate { constructor(public i: Expr) { super(ExprType.Arg, 0) if (!(i instanceof Expr)) { Util.assert(false); } } toString(config = {}) { config = reset(config) if (this.i instanceof Const && (<Const>this.i).val < 6) { return "arg" + (<Const>this.i).val } return "arguments[" + this.i.toString(noparen(config)) + "]" } eval(args: any[]): any { return args[this.i.eval(args)] } update(args: any[], val: any): any { args[this.i.eval(args)] = val; } equals(o): boolean { return o instanceof Argument && o.i.equals(this.i) } children(): Node[] { return [this.i] } anychildren(): any[] { return this.children() } toSkeleton(): string { return "arg(" + this.i.toSkeleton() + ")" } canBeUpdated(args: any[]): boolean { return this.isSafe(args) } isUpdateNop(args: any[], val: any): boolean { return args[this.i.eval(args)] === val } isSafe(args: any[]): boolean { return this.i.eval(args) < args.length } } /** * A local variable. */ export class Var extends Expr { static _count: Object = {} name: string constructor(prefix: string = "n", fixedName: boolean = false) { super(ExprType.Var, 0) if (fixedName) { this.name = prefix } else { if (!(prefix in Var._count)) { Var._count[prefix] = 0 } this.name = prefix + Var._count[prefix] if (Var._count[prefix] == 0 && prefix == "i") { this.name = prefix } Var._count[prefix]++ } } toString(config = {}) { if ("novar" in config) { return "*" } return this.name } equals(o): boolean { return o instanceof Var && o.name === this.name } children(): Node[] { return [] } anychildren(): any[] { var res: any[] = this.children() res = res.concat([this.name]) return res } toSkeleton(): string { return "var" } canBeUpdated(args: any[]): boolean { return false } isSafe(args: any[]): boolean { return false } getType(): string { if (this.name[0] === "i") { return "number" } return undefined } } /** A small helper class that holds a variable, as well as an index where it was defined (which statement). */ export class VarDef { constructor(public v: Var, public definedAt: number) { } } /** * A constant (of a primitive type). */ export class Const extends Expr { constructor(public val: any) { super(ExprType.Const, 0) Util.assert(Util.isPrimitive(this.val)) } toString(config = {}) { if (typeof this.val === "string") { return "\"" + this.val + "\"" } return this.val } eval(args: any[]): any { return this.val } update(args: any[], val: any): any { Util.assert(false, () => "cannot update constant") } equals(o): boolean { return o instanceof Const && o.val === this.val } children(): Node[] { return [] } anychildren(): any[] { var res: any[] = this.children() res = res.concat([this.val]) return res } toSkeleton(): string { return "const" } canBeUpdated(args: any[]): boolean { return false } isSafe(args: any[]): boolean { return true } getType(): string { return typeof this.val } } /** * An newly allocated object or array. */ export class Alloc extends Expr { constructor(public isArray: boolean) { super(ExprType.Alloc, 0) } toString(config = {}) { if (this.isArray) { return "[]"; } return "{}" } eval(args: any[]): any { if (this.isArray) { return []; } return {}; } update(args: any[], val: any): any { Util.assert(false, () => "cannot update allocation") } equals(o): boolean { return o instanceof Alloc && o.isArray === this.isArray } children(): Node[] { return [] } anychildren(): any[] { var res: any[] = this.children() return res } toSkeleton(): string { return this.toString() } canBeUpdated(args: any[]): boolean { return false } isSafe(args: any[]): boolean { return true } getType(): string { return typeof this.eval([]) } } /** * An enum for all statements. */ export enum StmtType { Assign = 2000, Return, Throw, DeleteProp, DefineProp, VarDecl, If, For, Seq, FuncCall, Break, Marker, } /** * Common ancestor of all statements. */ export class Stmt extends Node { constructor(public type: StmtType) { super() } equals(o): boolean { Util.assert(false) return false } /*visit(f: (s: Stmt) => any) { if (f(this) !== false) { var cs = this.children() for (var i = 0; i < cs.length; i++) { cs[i].visit(f) } } }*/ /** Returns a shallow clone (i.e., *this* object is not shared yet, but anything referenced might still be shared) */ clone(): Stmt { Util.assert(false) return null } allStmts(): Stmt[] { return [this] } numberOfStmts(): number { return 1 } replace(i: number, news: Stmt): Stmt { Util.assert(i === 0, () => "out of bounds repl") return news } /** Returns a list of all variables declared, as well as the statement index where they are declared */ getVariables(startIdx: number = 0): VarDef[] { return [] } } /** * Conditional statement. */ export class If extends Stmt { constructor(public c: Expr, public thn: Stmt, public els: Stmt) { super(StmtType.If) } toString() { if (this.thn.numberOfStmts() === 0) { return "if (" + this.c.toString(noparen()) + ") {} else {\n" + Util.indent(this.els.toString()) + "\n}" } if (this.els.numberOfStmts() === 0) { return "if (" + this.c.toString(noparen()) + ") {\n" + Util.indent(this.thn.toString()) + "\n}" } return "if (" + this.c.toString(noparen()) + ") {\n" + Util.indent(this.thn.toString()) + "\n} else {\n" + Util.indent(this.els.toString()) + "\n}" } children(): Node[] { return [this.c, this.thn, this.els] } anychildren(): any[] { return this.children() } numberOfStmts(): number { return 1 + this.thn.numberOfStmts() + this.els.numberOfStmts() } clone(): Stmt { return new If(this.c, this.thn, this.els) } replace(i: number, news: Stmt): Stmt { Util.assert(i >= 0 && i < this.numberOfStmts(), () => "out of bound replacement") if (i === 0) { return news } i -= 1 if (i < this.thn.numberOfStmts()) { // recurse for thn return new If(this.c, this.thn.replace(i, news), this.els) } i -= this.thn.numberOfStmts() // recurse for els return new If(this.c, this.thn, this.els.replace(i, news)) } allStmts(): Stmt[] { return [<Stmt>this].concat(this.thn.allStmts()).concat(this.els.allStmts()) } getVariables(startIdx: number = 0): VarDef[] { return this.thn.getVariables(startIdx + 1).concat(this.els.getVariables(startIdx + 1 + this.thn.numberOfStmts())) } } /** * For loop statement. */ export class For extends Stmt { constructor(public start: Expr, public end: Expr, public inc: Expr, public body: Stmt, public variable: Var = new Var("i")) { super(StmtType.For) } toString() { var res = "" res += "for (var " res += this.variable.toString() res += " = " res += this.start.toString(noparen()) res += "; " res += this.variable.toString() res += " < " res += this.end.toString() res += "; " res += this.variable.toString() res += " += " res += this.inc.toString() res += ") {\n" res += Util.indent(this.body.toString()) res += "\n}" return res } children(): Node[] { return [this.variable, this.start, this.end, this.inc, this.body] } anychildren(): any[] { return this.children() } numberOfStmts(): number { return 1 + this.body.numberOfStmts() } clone(): Stmt { return new For(this.start, this.end, this.inc, this.body, this.variable) } replace(i: number, news: Stmt): Stmt { Util.assert(i >= 0 && i < this.numberOfStmts(), () => "out of bound replacement") if (i === 0) { return news } return new For(this.start, this.end, this.inc, this.body.replace(i-1, news), this.variable) } allStmts(): Stmt[] { return [<Stmt>this].concat(this.body.allStmts()) } getVariables(startIdx: number = 0): VarDef[] { return [new VarDef(this.variable, startIdx)].concat(this.body.getVariables(startIdx + 1)) } } /** * A sequence of statements (has no behavior other that that of it's children). */ export class Seq extends Stmt { static Empty = new Seq([]) constructor(public stmts: Stmt[]) { super(StmtType.Seq) } toString() { if (this.numberOfStmts() === 0) { return "/* nop */" } return this.stmts.join("\n") } children(): Node[] { return this.stmts } anychildren(): any[] { var res: any[] = this.children() return res } numberOfStmts(): number { return Util.sum(this.stmts.map((x) => x.numberOfStmts())) } clone(): Stmt { return new Seq(this.stmts) } replace(i: number, news: Stmt): Stmt { Util.assert(i >= 0 && i < this.numberOfStmts(), () => "out of bound replacement") var stmts = this.stmts var cur = 0 function repl(ths, idx, ss) { var newss = ths.stmts.slice(0) if (ss === Seq.Empty) { newss.splice(idx, 1) } else { newss.splice(idx, 1, ss) } return new Seq(newss) } while (true) { if (i === 0) { // replace directly return repl(this, cur, news) } else { if (i < stmts[cur].numberOfStmts()) { // recurse return repl(this, cur, stmts[cur].replace(i, news)) } else { i -= stmts[cur].numberOfStmts() cur += 1 } } } } allStmts(): Stmt[] { var res = [] this.stmts.forEach((s) => res = res.concat(s.allStmts())) return res } getVariables(startIdx: number = 0): VarDef[] { var res = [] for (var i = 0; i < this.stmts.length; i++) { res = res.concat(this.stmts[i].getVariables(startIdx)) startIdx += this.stmts[i].numberOfStmts() } return res } } /** * An marker statement (has no effect, just used for internal purposes) */ export class Marker extends Stmt { constructor() { super(StmtType.Marker) } toString() { return "if (this != null) this.budget = 1" } equals(o) { return o instanceof Marker } children(): Node[] { return [] } clone(): Stmt { return new Marker() } anychildren(): any[] { var res: any[] = this.children() return res } toSkeleton(): string { return "marker" } getVariables(startIdx: number = 0): VarDef[] { return [] } } /** * An assignment statement. */ export class Assign extends Stmt { v: Var constructor(public lhs: Expr, public rhs: Expr, public isDecl: boolean = false) { super(StmtType.Assign) if (lhs.type === ExprType.Var) { this.v = <Var>lhs } } toString() { var prefix = "" if (this.isDecl) { prefix = "var " } if (this.rhs === null) { return prefix + this.lhs.toString(noparen()) } return prefix + this.lhs.toString(noparen()) + " = " + this.rhs.toString(noparen()) } equals(o) { return o instanceof Assign && o.lhs.equals(this.lhs) && ((o.rhs === null) === (this.rhs === null)) && (o.rhs === null || o.rhs.equals(this.rhs)) } clone(): Stmt { return new Assign(this.lhs, this.rhs, this.isDecl) } children(): Node[] { if (this.rhs === null) { return [this.lhs] } return [this.lhs, this.rhs] } anychildren(): any[] { return this.children() } toSkeleton(): string { if (this.rhs === null) { return this.lhs.toSkeleton() } return this.lhs.toSkeleton() + "=" + this.rhs.toSkeleton() } getVariables(startIdx: number = 0): VarDef[] { var res = [] if (this.isDecl) { res.push(new VarDef(<Var>this.lhs, startIdx)) } return res } } /** * A function call. */ export class FuncCall extends Stmt { constructor(public v: Var, public f: Expr, public args: Expr[], public recv: Expr, public isDecl: boolean) { super(StmtType.FuncCall) } toString() { var s = "" if (this.isDecl) { s += "var " } s += this.v.toString() + " = " var rcvArg = this.recv === null ? "global" : this.recv.toString(); var args = this.args.map((a) => a.toString(noparen())) s += this.f.toString() + ".call(" + rcvArg + ", " + Util.join(args, ", ") + ")" return s } equals(o) { if (!(o instanceof FuncCall)) { return false } if (!(o.v.equals(this.v) && o.f.equals(this.f))) { return false } if (!(this.args.length === o.args.length)) { return false } for (var i = 0; i < this.args.length; i++) { if (!this.args[i].equals(o.args[i])) { return false } } return true } clone(): Stmt { return new FuncCall(this.v, this.f, this.args.slice(0), this.recv, this.isDecl) } children(): Node[] { var res = [this.v, this.f].concat(this.args); if (this.recv !== null) { res.push(this.recv) } return res } anychildren(): any[] { return this.children() } toSkeleton(): string { var s = "" if (this.isDecl) { s += "var " } s += this.v.toSkeleton() + " = " var rcvArg = this.recv === null ? "null" : this.recv.toSkeleton(); var args = this.args.map((a) => a.toSkeleton()) s += this.f.toSkeleton() + ".apply(" + rcvArg + ", [ " + Util.join(args, ", ") + " ])" return s } getVariables(startIdx: number = 0): VarDef[] { var res = [] if (this.isDecl) { res.push(new VarDef(this.v, startIdx)) } return res } } /** * A return statement. */ export class Return extends Stmt { constructor(public rhs: Expr) { super(StmtType.Return) } toString() { return "return " + this.rhs.toString(noparen()) } equals(o) { return o instanceof Return && o.rhs.equals(this.rhs) } clone(): Stmt { return new Return(this.rhs) } children(): Node[] { return [this.rhs] } anychildren(): any[] { return this.children() } toSkeleton(): string { return "ret " + this.rhs.toSkeleton() } getVariables(startIdx: number = 0): VarDef[] { return [] } } export class Throw extends Stmt { constructor(public rhs: Expr) { super(StmtType.Throw) } toString() { return "throw " + this.rhs.toString(noparen()) } equals(o) { return o instanceof Throw && o.rhs.equals(this.rhs) } clone(): Stmt { return new Throw(this.rhs) } children(): Node[] { return [this.rhs] } anychildren(): any[] { return this.children() } toSkeleton(): string { return "throw " + this.rhs.toSkeleton() } getVariables(startIdx: number = 0): VarDef[] { return [] } } /** * A break statement */ export class Break extends Stmt { constructor() { super(StmtType.Break) } toString() { return "break" } equals(o) { return o instanceof Break } clone(): Stmt { return new Break() } children(): Node[] { return [] } anychildren(): any[] { var res: any[] = this.children() return res } toSkeleton(): string { return "break" } getVariables(startIdx: number = 0): VarDef[] { return [] } } /** * A property deletion statement. */ export class DeleteProp extends Stmt { constructor(public o: Expr, public f: Expr) { super(StmtType.DeleteProp) } toString() { if (this.f.type === ExprType.Const) { var c = <Const>this.f if (typeof c.val === "string") { if (/[a-zA-Z_][_a-zA-Z0-9]*/.test(c.val)) { return "delete " + this.o.toString() + "." + c.val } if (/[0-9]+/.test(c.val)) { return "delete " + this.o.toString() + "[" + c.val + "]" } } } return "delete " + this.o.toString() + "[" + this.f.toString(noparen()) + "]" } equals(o) { return o instanceof DeleteProp && o.o.equals(this.o) && o.f.equals(this.f) } clone(): Stmt { return new DeleteProp(this.o, this.f) } children(): Node[] { return [this.o, this.f] } anychildren(): any[] { return this.children() } toSkeleton(): string { return "del " + this.f.toSkeleton() + " of " + this.o.toSkeleton() } getVariables(startIdx: number = 0): VarDef[] { return [] } } /** * A property definition statement. */ export class DefineProp extends Stmt { constructor(public o: Expr, public f: Expr, public v: Expr) { super(StmtType.DefineProp) } toString() { return "Object.defineProperty(" + this.o.toString(noparen()) + ", " + this.f.toString(noparen()) + ", {value: " + this.v.toString() + "})" } equals(o) { return o instanceof DefineProp && o.o.equals(this.o) && o.f.equals(this.f) && o.v.equals(this.v) } clone(): Stmt { return new DefineProp(this.o, this.f, this.v) } children(): Node[] { return [this.o, this.f, this.v] } anychildren(): any[] { return this.children() } toSkeleton(): string { return "def " + this.f.toSkeleton() + " of " + this.o.toSkeleton() + " as " + this.v.toSkeleton() } getVariables(startIdx: number = 0): VarDef[] { return [] } } /** * A program (just a way to group statements). */ export class Program { static Empty = new Program(Seq.Empty) constructor(public body: Stmt) { Util.assert(this.body != undefined) } toString() { if (this.body.numberOfStmts() === 0) { return " // <empty program>" } return Util.indent(this.body.toString()) } toFullProgram(name: string) { var body = this.toString() var n = 100 var res = "function " + name + "(" while (body.indexOf("arg" + n) == -1 && n > 0) { n -= 1 } n += 1 var i = 0 while (i < n) { if (i != 0) { res += ", " } res += "arg" + i i += 1 } res += ") {\n" res += body res += "\n}" return res } getVariables(): VarDef[] { return this.body.getVariables() } } /** * A program trace. Note that some statements like conditionals will never occur in traces. */ export class Trace { public events: Event[] = [] public isNormalReturn: boolean = false public isExceptionReturn: boolean = false public isExhaustedBudget: boolean = false private result: TraceExpr = null private exception: TraceExpr = null public prestates: Prestate[] = null public constants: Const[] = null constructor() { } getLength(): number { return this.events.length } subEvents(start: number, length: number = undefined): Event[] { if (length === undefined) { return this.events.slice(start) } return this.events.slice(start, start+length) } extend(e: Event) { this.events.push(e) } setException(ex: TraceExpr) { this.isExceptionReturn = true this.exception = ex this.result = null } setResult(val: TraceExpr) { this.isNormalReturn = true this.exception = null this.result = val } setExhaustedBudget() { this.isExhaustedBudget = true } getResult() { Util.assert(this.isNormalReturn) return this.result } getException() { Util.assert(this.isExceptionReturn) return this.exception } setPrestates(ps: Prestate[]) { this.prestates = ps } getPrestates() { return this.prestates } setConstants(ps: Const[]) { this.constants = ps } getConstants() { return this.constants } eventsOfKind(kind: EventKind): Event[] { return this.events.filter((s) => s.kind === kind) } toString(config = {}) { var res if (this.isExhaustedBudget) { return "// exhausted computational budget" } if (this.isNormalReturn) { res = this.result.toString(config) } else { res = "Exception: " + this.exception.toString(config) } return "Trace:\n " + this.events.map((e) => e.toString(config)).join("\n ") + "\n Result: " + res } getSkeleton(): string { return this.events.map((s) => s.getSkeleton()).join("") } getSkeletonShort(): string { return this.events.map((s) => s.getSkeletonShort()).join("") } getSubSkeleton(start: number, length?: number): string { if (length === undefined) { length = this.events.length - start } var res = "" for (var i = 0; i < length; i++) { res += this.events[start+i].getSkeleton() } return res } } /** * An enum for all events. */ export enum EventKind { EGet = 2000, ESet, EApply, EDeleteProperty, EHas, } /** * An event that occurred when recording a trace. */ export class Event { public variable: Var = null constructor(public kind: EventKind, public target: TraceExpr, public otherArgs: TraceExpr[]) { this.otherArgs = otherArgs.filter((i) => i != null) if (kind === EventKind.EApply || kind === EventKind.EGet || kind === EventKind.EHas) { this.variable = new Var() } } getSkeleton(): string { Util.assert(false) return "" } getSkeletonShort(): string { Util.assert(false) return "" } toString(config = {}): string { var s = "" s += this.variable.toString(config) s += " := " return s } getParts(): TraceExpr[] { return [this.target].concat(this.otherArgs) } } export class EGet extends Event { constructor(public target: TraceExpr, public name: TraceExpr) { super(EventKind.EGet, target, [name]) } getSkeleton(): string { return "get;" } getSkeletonShort(): string { return "g" } toString(config = {}): string { var s = "" s += super.toString(config) s += "get property " s += this.name.toString(config) s += " of " s += this.target.toString(config) return s } } export class EHas extends Event { constructor(public target: TraceExpr, public name: TraceExpr) { super(EventKind.EHas, target, [name]) } getSkeleton(): string { return "has;" } getSkeletonShort(): string { return "h" } toString(config = {}): string { var s = "" s += super.toString(config) s += "has property " s += this.name.toString(config) s += " of " s += this.target.toString(config) return s } } export class ESet extends Event { constructor(public target: TraceExpr, public name: TraceExpr, public value: TraceExpr) { super(EventKind.ESet, target, [name, value]) } getSkeleton(): string { return "set;" } getSkeletonShort(): string { return "s" } toString(config = {}): string { var s = "" //s += super.toString(config) s += "set property " s += this.name.toString(config) s += " of " s += this.target.toString(config) s += " to " s += this.value.toString(config) return s } } export class EApply extends Event { constructor(public target: TraceExpr, public receiver: TraceExpr, public args: TraceExpr[]) { super(EventKind.EApply, target, [receiver].concat(args)) } getSkeleton(): string { return "apply;" } getSkeletonShort(): string { return "a" } toString(config = {}): string { var s = "" s += super.toString(config) s += "apply " s += this.target.toString(config) if (this.receiver != null) { s += " with receiver " s += this.receiver.toString(config) s += " and arguments ( " } else { s += " with arguments ( " } s += Util.join(this.args.map((a) => a.toString(config)), ", ") s += " )" return s } } export class EDeleteProperty extends Event { constructor(public target: TraceExpr, public name: TraceExpr) { super(EventKind.EDeleteProperty, target, [name]) } getSkeleton(): string { return "deleteProperty;" } getSkeletonShort(): string { return "d" } toString(config = {}): string { var s = "" //s += super.toString(config) s += "delete property " s += this.name.toString(config) s += " of " s += this.target.toString(config) return s } } /** * An enum for trace expressions. */ export enum TraceExprType { General = 3000, Const, Alloc, } /** * An expression used when recording a trace. Because there are often many possible expression * when recording a trace (e.g., because there were aliases in the input), a list of expressions * is used. Furthermore, both expressions that are valid (only) in the pre-state are recorded * (used for equality checking of traces), as well as expressions that may only be valid at * that particular point in the trace (used for program generation from a trace). */ export class TraceExpr { type: TraceExprType = TraceExprType.General constructor(public preState: Expr[], public curState: Expr[]) { var isConst = false Util.assert(preState.length > 0 && curState.length > 0) if (preState.length === 1 && curState.length === 1) { // only allow constants if both are constants if (preState[0].type === ExprType.Const) { Util.assert(curState[0].type === ExprType.Const) isConst = true } } Util.assert(isConst || preState.every((e) => e.type !== ExprType.Const)) Util.assert(isConst || curState.every((e) => e.type !== ExprType.Const)) } private pss_cache: string[] = null preStateStrings(): string[] { if (this.pss_cache === null) { this.pss_cache = this.preState.map((s) => s.toString()) } return this.pss_cache } toString(config = {}): string { var f = (exprs: Expr[]) => { if (exprs.length === 1) { return exprs[0].toString(config) } else { return "[" + Util.join(exprs.map((e) => e.toString(config)), ",") + "]" } } if (this.preState.join("|") === this.curState.join("|")) { return f(this.preState) } var s = "" s += "<" s += f(this.preState) s += ", " s += f(this.curState) s += ">" return s } } export class TraceConst extends TraceExpr { constructor(public val: any) { super([<Expr>new Const(val)], [<Expr>new Const(val)]) this.type = TraceExprType.Const } toString(config = {}): string { var s = "" //s += "<" s += this.val //s += ">" return s } } export class TraceAlloc extends TraceExpr { constructor(public val: any) { super([<Expr>new Const(undefined)], [<Expr>new Const(undefined)]) this.type = TraceExprType.Alloc } toString(config = {}): string { var s = "Allocated" s += "(" s += Util.inspect(this.val, false) s += ")" return s } }
mskim5383/safe-dynamicTest-generator
src/LinkedList.ts
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Simple linked list library. * * @author <NAME> <<EMAIL>> */ import Data = require('./Data') import Util = require('./util/Util') import Recorder = require('./Recorder') import Compile = require('./Compile') var print = Util.print var log = Util.log var line = Util.line export class LinkedList { static make(arr: number[]) { var res = null for (var i = arr.length-1; i >= 0; i--) { res = new LinkedList(res, arr[i]) } return res } constructor(public next: LinkedList = null, public value: number = -1) { } itemAt(idx: number) { var elem = this while (idx > 0) { elem = elem.next idx -= 1 } return elem.value } getLast() { var elem = this while (elem.next != null) { elem = elem.next } return elem.value } addFront(val: number) { return new LinkedList(this, this.value) } addBack(val: number) { var elem = this while (elem.next != null) { elem = elem.next } elem.next = new LinkedList(this, this.value) return this } getSize() { var elem = this var i = 0 while (elem.next != null) { elem = elem.next i += 1 } return i } removeFirst(val: number) { if (this.value === val) { return this.next } var elem = this var prev = null while (elem != null) { if (elem.value === val) { prev.next = elem.next return this } prev = elem elem = elem.next } return this } elements(): number[] { var res = [] var elem = this res.push(elem.value) while (elem.next != null) { elem = elem.next res.push(elem.value) } return res } itemAtR(idx: number) { if (idx === 0) { return this.value } else { return this.next.itemAtR(idx-1) } } toString() { return "<" + this.elements().join(",") + ">" } }
mskim5383/safe-dynamicTest-generator
src/TestGen.ts
// generate a JSON for dynamic tests // TODO extend it for functions. // TODO extend it for non-pure function. // TODO handling exception case. export function jsonGen(func, thisVal, args, name="") { // type checks if (typeof func !== "function") err("'func' should have a function type."); if (!Array.isArray(args)) err("'args' should have an array type."); // initial record var record = {}; var addr_count = 0; // built-in locations // TODO fill out var predefLocs = { "#Object": Object, "#Object.prototype": Object.prototype, "#Function": Function, "#Function.prototype": Function.prototype, "#Array": Array, "#Array.prototype": Array.prototype, "#Array.prototype.push": Array.prototype.push }; // generate input var input = { "thisVal": convert(thisVal), "arguments": convert(getArg(args)), "heap": getHeap() }; // generate output var result = func.apply(thisVal, args); var output = { "value": convert(result, true, name), "heap": getHeap() }; // final json var json = { "input": input, "output": output }; // display or download the final JSON var data = JSON.stringify(json, null, 4); return data; // covert to possible formats function convert(value, isOutput = false, name = "") { var type = typeof value; if (type === 'undefined') { return '@undef'; } else if (type === 'boolean') { return value; } else if (type === 'number') { if (value === NaN) return '@NaN'; else if (value === Infinity) return '@PosInf'; else if (value === -Infinity) return '@NegInf'; return value; } else if (type === 'string') { return value; } else if (type === 'object' || type === 'function') { if (value === null) { return null; } else { var loc = find(value, predefLocs); if (loc === null) loc = find(value, record); if (loc === null) { if (isOutput) { if (value instanceof Array) { type = "array" } loc = '#' + name + "<" + type + ">" } else { loc = '#' + (++addr_count); } record[loc] = value; var props = Object.getOwnPropertyNames(value); for (var i = 0; i < props.length; i++){ convert(getDesc(value, props[i]).value); } convert(getProto(value)); } return loc; } // TODO handling function } else { notSupport('to convert host object: ' + value); } } // find location in a given table function find(obj, table) { for (var loc in table) { if (table[loc] === obj) return loc; } return null; } // get heap from record function getHeap() { // check for (var loc in record) { convert(record[loc]); } // convert var heap = {}; for (var loc in record) { var obj = {}; var given = record[loc]; var props = Object.getOwnPropertyNames(given); for (var i = 0; i < props.length; i++) { var prop = props[i]; var desc = getDesc(given, prop); if (desc.hasOwnProperty('value')) desc.value = convert(desc.value); obj[prop] = desc; } obj["[[Class]]"] = getClass(given); obj["[[Prototype]]"] = convert(getProto(given)); obj["[[Extensible]]"] = getIsExt(given); var primVal = getPrimVal(given); if (primVal) obj["[[PrimitiveValue"] = primVal; heap[loc] = obj; } return heap; } // get [[Class]] function getClass(obj) { var str = Object.prototype.toString.call(obj); return str.substring(8, str.length-1); } // get [[Prototype]] function getProto(obj) { return Object.getPrototypeOf(obj); } // get [[Extensible]] function getIsExt(obj) { return Object.isExtensible(obj); } // get [[PrimitiveValue]] function getPrimVal(obj) { if (obj instanceof Number || obj instanceof String || obj instanceof Boolean || obj instanceof Date) return obj.valueOf(); if (obj === Date.prototype) return NaN; } // get arguments function getArg(args) { var argObj; function f() { argObj = arguments; } f.apply(undefined, args); argObj.callee = func; return argObj; } // get descriptor function getDesc(obj, prop) { return Object.getOwnPropertyDescriptor(obj, prop); } // errors function err(msg) { throw Error(msg); } function notSupport(msg) { console.error('Not supported yet: ' + msg); } }
mskim5383/safe-dynamicTest-generator
src/ProgramGen.ts
<filename>src/ProgramGen.ts /* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Random program generation. * * @author <NAME> <<EMAIL>> */ import Data = require('./Data') import Util = require('./util/Util') import Random = require('./util/Random') import Recorder = require('./Recorder') var randInt = Random.randInt var WeightedPair = Random.WeightedPair var maybe = Random.maybe var pick = Random.pick var randArr = Random.randArr var print = Util.print var log = Util.log var line = Util.line export class RandomMutationInfo { types: string[][] nArgs: number constructor(public constants: Data.Expr[], public variables: Data.VarDef[], public inputs: any[][], public useAlloc: boolean) { this.types = [] this.nArgs = Util.max(inputs.map((i) => i.length)) for (var i = 0; i < this.nArgs; i++) { this.types[i] = Util.dedup(inputs.map((inp) => typeof inp[i])) } } } /** * A factory for ast creation, where creation can sometimes fail, and failure is propagated correctly. * Failure is indicated with `null', and if any of the child nodes failed, then so does the overall creation. */ class MaybeAstFactory { static makeField(a: Data.Expr, b: Data.Expr): Data.Field { if (a === null || b === null) { return null } return new Data.Field(a, b) } static makeBinary(a: Data.Expr, op: string, b: Data.Expr): Data.Binary { if (a === null || b === null) { return null } return new Data.Binary(a, op, b) } static makeDeleteProp(a: Data.Expr, b: Data.Expr): Data.DeleteProp { if (a === null || b === null) { return null } return new Data.DeleteProp(a, b) } static makeAssign(a: Data.Expr, b: Data.Expr, isDecl: boolean = false): Data.Assign { if (a === null || b === null) { return null } return new Data.Assign(a, b, isDecl) } static makeFuncCall(v: Data.Var, f: Data.Expr, r: Data.Expr, args: Data.Expr[], isDecl: boolean): Data.FuncCall { if (v === null || f === null || args.some((a) => a === null)) { return null } return new Data.FuncCall(v, f, args, r, isDecl) } static makeReturn(a: Data.Expr): Data.Return { if (a === null) { return null } return new Data.Return(a) } static makeArgument(a: Data.Expr): Data.Argument { if (a === null) { return null } return new Data.Argument(a) } static makeThrow(a: Data.Expr): Data.Throw { if (a === null) { return null } return new Data.Throw(a) } static makeIf(a: Data.Expr, b: Data.Stmt, c: Data.Stmt): Data.If { if (a === null || b === null || c === null) { return null } return new Data.If(a, b, c) } static makeFor(v: Data.Var, a: Data.Expr, b: Data.Expr, c: Data.Expr, body: Data.Stmt): Data.For { if (a === null || b === null || c === null || v === null || body === null) { return null } return new Data.For(a, b, c, body, v) } } var Ast = MaybeAstFactory /** * Randomly mutate the given program. */ export function randomChange(info: RandomMutationInfo, p: Data.Program): Data.Program { var stmts = p.body.allStmts() // all possible transformations (they return false if they cannot be applied) var options = [ new WeightedPair(0, () => { // remove this statement if (stmts.length < 1) return null var si = randInt(stmts.length) p.body.replace(si, Data.Seq.Empty) return null }), new WeightedPair(0, () => { // insert a new statement /*stmts.splice(si, 0, randomStmt(state)) return true*/ return null }), new WeightedPair(0, () => { // swap with another statement /*if (stmts.length < 2) return undefined var si2 while ((si2 = randInt(stmts.length)) === si) {} var t = stmts[si] stmts[si] = stmts[si2] stmts[si2] = t return true*/ return null }), new WeightedPair(7, () => { // modify an existing statement if (stmts.length < 1) return null var si = randInt(stmts.length) var randExp = (args = {}) => randomExpr(info, si, args) var ss = stmts[si] var s var news switch (ss.type) { case Data.StmtType.Assign: s = <Data.Assign>ss if (s.lhs.type === Data.ExprType.Field) { if (maybe(0.3334)) { news = Ast.makeAssign(s.lhs, randExp()) } else if (maybe(0.5)) { var field = Ast.makeField((<Data.Field>s.lhs).o, randExp({field: true})) news = Ast.makeAssign(field, s.rhs) } else { var field = Ast.makeField(randExp({obj: true}), (<Data.Field>s.lhs).f) news = Ast.makeAssign(field, s.rhs) } } else { if (s.rhs === null) { // only a variable declaration -> add an initializer news = Ast.makeAssign(s.lhs, randExp(), s.isDecl) } else if (s.rhs.type === Data.ExprType.Has) { var has = <Data.Has>s.rhs var newhas if (maybe()) { newhas = new Data.Has(has.o, randExp({field: true})) } else { newhas = new Data.Has(randExp({obj: true}), has.f) } news = Ast.makeAssign(s.lhs, newhas) } else if (s.rhs.type === Data.ExprType.Alloc) { // leave allocations return null } else if (s.rhs.type === Data.ExprType.Var && s.lhs.type === Data.ExprType.Var && s.lhs.name == "result") { // result variable assignment news = Ast.makeAssign(s.lhs, randExp(), s.isDecl) } else if (s.rhs.type === Data.ExprType.Var && s.lhs.type === Data.ExprType.Var) { // from code merging return null } else { if (s.lhs.type === Data.ExprType.Var && s.rhs.type === Data.ExprType.Field) { var f = <Data.Field>s.rhs if (maybe()) { var exp = randExp({field: true}) news = Ast.makeAssign(s.lhs, Ast.makeField(f.o, exp), s.isDecl) } else { news = Ast.makeAssign(s.lhs, Ast.makeField(randExp({lhs: true}), f.f), s.isDecl) } } else { if (s.isDecl) { if (maybe(0.9)) { news = Ast.makeAssign(s.lhs, randExp(), s.isDecl) } else { news = new Data.Assign(s.lhs, null, s.isDecl) } } else { news = Ast.makeAssign(s.lhs, randExp(), s.isDecl) } } } } break case Data.StmtType.Return: s = <Data.Return>ss news = Ast.makeReturn(randExp()) break case Data.StmtType.DeleteProp: s = <Data.DeleteProp>ss if (maybe()) { news = Ast.makeDeleteProp(randExp({arr: true, obj: true}), s.f) } else { news = Ast.makeDeleteProp(s.o, randExp()) } break case Data.StmtType.If: s = <Data.If>ss news = Ast.makeIf(randExp({num: true, bool: true}), s.thn, s.els) break case Data.StmtType.For: s = <Data.For>ss var newEnd = randExp({num: true}) news = Ast.makeFor(s.variable, s.start, newEnd, s.inc, s.body) break case Data.StmtType.FuncCall: s = <Data.FuncCall>ss if (s.args.length === 0) return null var idx = randInt(s.args.length) var newExpr = randExp(); var newargs = s.args.slice(0) newargs.splice(idx, 1, newExpr) news = Ast.makeFuncCall(s.v, s.f, s.recv, newargs, s.isDecl) break case Data.StmtType.Break: return null // cannot modify breaks case Data.StmtType.Marker: return null default: Util.assert(false, () => "unhandled statement modification: " + ss) break } if (news === null) { // not successful at finding a new statement return null } if (softEquals(news, s)) { // new statement happens to be the same as the old one return null } return new Data.Program(p.body.replace(si, news)) }), ] // randomly choose an action (and execute it) var res var i = 0 while ((res = pick(options)()) === null && i < 25) { i += 1 } Util.assert(res != null) return res } /** * Equals function for statements that only considers the part of a statement which * can actually be modified by program generation. */ function softEquals(a: Data.Stmt, b: Data.Stmt): boolean { if (a.type !== b.type) return false switch (a.type) { case Data.StmtType.Assign: case Data.StmtType.Return: case Data.StmtType.DeleteProp: case Data.StmtType.FuncCall: return a.equals(b) case Data.StmtType.If: var aif = <Data.If>a var bif = <Data.If>b return aif.c.equals(bif.c) case Data.StmtType.For: var afor = <Data.For>a var bfor = <Data.For>b return afor.end.equals(bfor.end) default: Util.assert(false, () => "unhandled statement soft equals: " + a) break } } //function randomStmt(info: RandomMutationInfo): Data.Stmt { // var options = [ // () => { // return Ast.makeReturn(randomExpr(info)) // }, // () => { // return Ast.makeAssign(randomExpr(info, {lhs: true}), randomExpr(info)) // }, // ] // return randArr(options)() //} function randomExpr(info: RandomMutationInfo, stmtIdx: number, args: any = {}, depth: number = 2): Data.Expr { var lhs = "lhs" in args && args.lhs === true var obj = "obj" in args && args.obj === true var arr = "arr" in args && args.arr === true var num = "num" in args && args.num === true var bool = "bool" in args && args.bool === true var str = "str" in args && args.str === true var noconst = "noconst" in args && args.noconst === true var field = "field" in args && args.field === true if (field) { num = true str = true } var nonPrimitive = lhs || obj || arr var hasRequirement = nonPrimitive || num || bool || str var zeroD = depth === 0 var recurse = (a: any = {}) => { if (depth <= 0) return null return randomExpr(info, stmtIdx, a, depth - 1) } var randomVar = () => { var varDef: Data.VarDef = randArr(info.variables) if (varDef.definedAt >= stmtIdx) { return null } return <Data.Expr>varDef.v } var options: Random.WeightedPair<() => Data.Expr>[] = [ new WeightedPair(info.nArgs > 0 ? 6 : 0, () => { // random argument return <Data.Expr>new Data.Argument(new Data.Const(Random.randInt(info.nArgs))) }), new WeightedPair(info.nArgs > 0 ? 2 : 0, () => { // random argument return <Data.Expr>Ast.makeArgument(recurse({num: true, noconst: true})) }), new WeightedPair(info.nArgs > 0 ? 2 : 0, () => { // random argument return <Data.Expr>Ast.makeField(new Data.Var("arguments", true), new Data.Const("length")) }), new WeightedPair(info.constants.length > 0 && !noconst ? 1 : 0, () => { // random new constant from the program return <Data.Expr>randArr(info.constants) }), new WeightedPair(info.variables.length > 0 ? 4 : 0, () => { // random variable from the program return randomVar() }), new WeightedPair(zeroD || !info.useAlloc ? 0 : 1/*3*/, () => { // length field read of result return <Data.Expr>Ast.makeField(new Data.Var("result", true), new Data.Const("length")) }), new WeightedPair(zeroD || !info.useAlloc ? 0 : 0/*3*/, () => { // random field read of result return <Data.Expr>Ast.makeField(new Data.Var("result", true), recurse({field: true})) }), new WeightedPair(zeroD ? 0 : 0/*3*/, () => { // random new field return <Data.Expr>Ast.makeField(recurse({obj: true}), recurse({field: true})) }), new WeightedPair(nonPrimitive || zeroD ? 0 : 2, () => { // random new addition return <Data.Expr>Ast.makeBinary(recurse({num: true, noconst: true}), "+", new Data.Const(maybe() ? 1 : -1)) }), new WeightedPair(nonPrimitive || zeroD ? 0 : 0, () => { // random new division return <Data.Expr>Ast.makeBinary(recurse({num: true, noconst: true}), "/", recurse({num: true})) }), new WeightedPair(nonPrimitive || zeroD || info.variables.length == 0 ? 0 : 1, () => { // random new addition of two variables return <Data.Expr>Ast.makeBinary(randomVar(), "+", randomVar()) }), new WeightedPair(nonPrimitive || zeroD || info.variables.length == 0 ? 0 : 1, () => { // random new subtraction of two variables return <Data.Expr>Ast.makeBinary(Ast.makeBinary(randomVar(), "-", randomVar()), "-", new Data.Const(1)) }), new WeightedPair(bool && !zeroD ? 1 : 0, () => { // random new equality comparison var e1 = recurse() var conf = {} if (e1.type === Data.ExprType.Const) { conf = { noconst: true } } var e2 = recurse(conf) return <Data.Expr>Ast.makeBinary(e1, "==", e2) }), new WeightedPair(bool && !zeroD ? 1 : 0, () => { // random new arithmetic comparison var e1 = recurse({ num: true }) var conf = { num: true } if (e1.type === Data.ExprType.Const) { conf = { noconst: true, num: true } } var e2 = recurse(conf) return <Data.Expr>Ast.makeBinary(e1, "<", e2) }), new WeightedPair(nonPrimitive || zeroD ? 0 : 1, () => { // random boolean not return <Data.Expr>new Data.Unary("!", recurse({noconst: true})) }), new WeightedPair(nonPrimitive || noconst ? 0 : 1, () => { // random new integer return <Data.Expr>new Data.Const(randInt(10)-5) }), ] // filter out bad expressions var filter: (e: Data.Expr) => Data.Expr = (e: Data.Expr) => { if (e === null) return e // filter by depth if (e.depth > depth) return null // filter by requirement var type = e.getType() if (hasRequirement && type !== undefined) { var isConst = e.type === Data.ExprType.Const; var constVal = (<Data.Const>e).val; if (lhs && isConst && constVal === null) { // dereference of null return null } if (field && isConst && type === "number" && (constVal < 0 || constVal % 1 !== 0)) { // only allow whole positive numbers as fields return null } if (type === "number" && num) { return e } if (type === "object" && (obj || arr || lhs)) { return e } if (type === "boolean" && bool) { return e } if (type === "string" && str) { return e } return null // no match } if (hasRequirement && e.type === Data.ExprType.Arg) { var arg = <Data.Argument>e var types: string[] = [] if (arg.i.type === Data.ExprType.Const) { types = info.types[(<Data.Const>arg.i).val] } else { for (var i = 0; i < info.types.length; i++) { types = types.concat(info.types[i]) } types = Util.dedup(types) } var required: string[] = [] if (str || field) { required.push("string") } if (lhs || arr || obj) { required.push("object") } if (bool) { required.push("boolean") } if (num || field) { required.push("number") } if (required.length > 0) { // make sure there is at least the possibility to have the correct type for (var i = 0; i < required.length; i++) { if (types.indexOf(required[i]) != -1) { return e } } return null } } return e } var res var i = 0 while ((res = filter(pick(options)())) === null && i < 25) { i += 1 } return res }
mskim5383/safe-dynamicTest-generator
ts-decl/harmony-reflect.d.ts
<reponame>mskim5383/safe-dynamicTest-generator declare module "harmony-reflect" { //var Proxy: (target: any, handler: any) => any; interface Harmony { get: any; } export = Harmony; }
mskim5383/safe-dynamicTest-generator
src/StructureInference.ts
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Inferring the structure of a program from traces. * * @author <NAME> <<EMAIL>> */ import Data = require('./Data') import Util = require('./util/Util') import Recorder = require('./Recorder') import Compile = require('./Compile') import Random = require('./util/Random') var print = Util.print var log = Util.log var line = Util.line export class Proposal { worksFor: number[] long: string numStmts: number constructor(public regex: string, public trace: Data.Trace, public unrolledLen: number, public prefixStart: number, public prefixLen: number, public thenStart: number, public thenLen: number, public elseStart: number, public elseLen: number) { this.numStmts = 0 this.long = "" for (var i = 0; i < regex.length; i++) { this.numStmts += 1 switch (regex[i]) { case 'g': this.long += "get;" break case 's': this.long += "set;" break case 'h': this.long += "has;" break case 'd': this.long += "delete;" break case 'a': this.long += "apply;" break; default: this.long += regex[i] if (regex[i] != "|") { this.numStmts -= 1 } } } } equals(o) { if (!(o instanceof Proposal)) { return false } return this.regex === o.regex } toString(): string { return this.long } matches(trace: Data.Trace): boolean { return new RegExp("^" + this.regex + "$").test(trace.getSkeletonShort()) } hasConditional(): boolean { return this.regex.indexOf("|") != -1 } } /** * Tries to infer a loop structure of the given traces. Returns a set of proposals, ordered by * confidence in them (best proposal first). */ export function infer(traces: Data.Trace[]) { function find_candidates(trace0: Data.Trace) { var trace = trace0.getSkeletonShort() var candidates: Proposal[] = [] var tlen = trace.length var minIterations = 4 var minBodyLength = 1 var maxBranchLength = 1000000 var minBranchLengh = 1 for (var start = 0; start < tlen - 1; start++) { // not enough space for minIterations if (start + minIterations > tlen) break; for (var unrolledLen = minBodyLength; unrolledLen < tlen - start + 1; unrolledLen++) { // not enough space for minIterations if (minBodyLength * minIterations > unrolledLen) continue; var regexStart = trace.substr(0, start) var regexEnd = trace.substr(start + unrolledLen) for (var thenLen = minBranchLengh; thenLen < maxBranchLength; thenLen++) { // not enough space for minIterations if (thenLen+minBranchLengh > unrolledLen) break; // try to match as many then branches as possible var thenBranch = trace.substr(start, thenLen) Util.assert(thenBranch.length == thenLen, () => "invalid then branch") var thenLeadingIters = 1 while (trace.substr(start + thenLeadingIters*thenLen, thenLen) == thenBranch && (thenLeadingIters+1)*thenLen <= unrolledLen) { thenLeadingIters += 1 } // special case for no conditional in loop var regex if (unrolledLen == thenLeadingIters*thenLen) { regex = regexStart + "(" + thenBranch + ")*" + regexEnd; candidates.push(new Proposal(regex, trace0, unrolledLen, start, thenLen, 0, 0, 0, 0)) } for (var elseLen = minBranchLengh; elseLen < maxBranchLength; elseLen++) { if (elseLen == 1 && thenLen == 1) break; // need at least one of each if (thenLen+elseLen > unrolledLen) break; // not enough space for minIterations if (Math.min(thenLen, elseLen) * (minIterations-1) + Math.max(thenLen, elseLen) > unrolledLen) break; // TODO: special case: else branch is subset of then branch // not enough room for else branch if (thenLeadingIters*thenLen + elseLen > unrolledLen) break; var elseFirstStart = start + thenLeadingIters * thenLen; var elseBranch = trace.substr(elseFirstStart, elseLen); Util.assert(elseBranch.length == elseLen, () => "invalid else branch") regex = regexStart + "(" + thenBranch + "|" + elseBranch + ")*" + regexEnd; var res = new RegExp("^" + regex + "$").test(trace) if (!res) { continue } candidates.push(new Proposal(regex, trace0, unrolledLen, 0, 0, start, thenLen, elseFirstStart, elseLen)) // find common prefix for then and else branch var prefixLen = 1 while (true) { if (prefixLen > thenBranch.length || prefixLen > elseBranch.length) break; if (prefixLen == thenBranch.length && prefixLen == elseBranch.length) break; var prefix = thenBranch.substr(0, prefixLen); if (prefix != elseBranch.substr(0, prefixLen)) break; regex = regexStart + "(" + prefix + "(" + thenBranch.substr(prefixLen) + "|" + elseBranch.substr(prefixLen) + "))*" + regexEnd; candidates.push(new Proposal(regex, trace0, unrolledLen, start, prefixLen, start+prefixLen, thenLen-prefixLen, elseFirstStart+prefixLen, elseLen-prefixLen)) prefixLen += 1 } } } } } return candidates; } var candidates: Proposal[] = [] var inferFrom = Random.pickN(traces, 100) for (var k = 0; k < inferFrom.length; k++) { candidates = candidates.concat(find_candidates(inferFrom[k])) } candidates = Util.dedup2(candidates) var howMany = (a: Proposal) => { if (a.worksFor !== undefined) { return a.worksFor.length } var i = 0 a.worksFor = [] var res = traces.filter((t) => { if (a.matches(t)) { a.worksFor.push(i) } i++ return res }).length return res } candidates.map((c) => howMany(c)) // initialize c.worksFor Util.sortBy(candidates, [ // sort by number of traces it matches (a: Proposal) => -howMany(a), // then by the length of the regular expression (a: Proposal) => a.numStmts, // then by not having a conditional in the loop (a: Proposal) => a.hasConditional() ? 1 : 0, // then by having the loop as late as possible (a: Proposal) => -a.regex.indexOf("(")]) return candidates }
mskim5383/safe-dynamicTest-generator
src/Builtin.ts
export function getFunction(fName) { return map[fName] } var map = {} export function ToObject(v) { if (v === null || v === undefined) throw TypeError return Object(v) } export function DefineOwnProperty(O, P, Desc, Throw) { try { return Object.defineProperty(O, P, Desc) } catch (e) { if (Throw) throw e else return false } } export function ToInteger(v) { // 1. Let number be the result of calling ToNumber on the input argument. var number = ToNumber(v) // 2. If number is NaN, return +0. if (isNaN(number)) return +0 // 3. If number is +0, -0, +Infinity, or -Infinity, return number. if (Math.abs(number) === 0 || Math.abs(number) == Infinity) return number // 4. Return the result of computing sign(number) * floor(abs(number)). return Math.sign(number) * Math.floor(Math.abs(number)) } export function ToString(v) { return String(v) } export function ToNumber(v) { return Number(v) } export function ToInt32(v) { return v << 0 } export function ToUint32(v) { return v >>> 0 } export function HasProperty(o, p) { return p in o } export function IsCallable(f) { return f instanceof Function } // 15.4.4.6 Array.prototype.pop ( ) // The last element of the array is removed from the array and returned. map["Array.prototype.pop"] = function() { // 1. Let O be the result of calling ToObject passing the this value as the argument. var O = ToObject(this) // 2. Let lenVal be the result of calling the [[Get]] internal method of O with argument "length". var lenVal = O["length"] // 3. Let len be ToUint32(lenVal). var len = ToUint32(lenVal) // 4. If len is zero, if (len === 0) { // a. Call the [[Put]] internal method of O with arguments "length", 0, and true. O.length = 0 // b. Return undefined. return undefined // 5. Else, len > 0 } else { // a. Let indx be ToString(len–1). var indx = ToString(len - 1) // b. Let element be the result of calling the [[Get]] internal method of O with argument indx. var element = O[indx] // c. Call the [[Delete]] internal method of O with arguments indx and true. delete O[indx] // d. Call the [[Put]] internal method of O with arguments "length", indx, and true. O["length"] = indx // e. Return element. return element } } // 15.4.4.7 Array.prototype.push ( [ item1 [ , item2 [ , ... ] ] ] ) map["Array.prototype.push"] = function() { // 1. Let O be the result of calling ToObject passing the this value as the argument. var O = ToObject(this) // 2. Let lenVal be the result of calling the [[Get]] internal method of O with argument "length". var lenVal = O["length"] // 3. Let n be ToUint32(lenVal). var n = ToUint32(lenVal) // 4. Let items be an internal List whose elements are, // in left to right order, the arguments that were passed to this // function invocation. var items = arguments // 5. Repeat, while items is not empty for (var i = 0; i < items.length; i++) { // a. Remove the first element from items and let E be the value of the element. var E = items[i] // b. Call the [[Put]] internal method of O with arguments ToString(n), E, and true. O[ToString(n)] = E // c. Increase n by 1. n++ } // 6. Call the [[Put]] internal method of O with arguments "length", n, and true. O.length = n // 7. Return n. return n } // 15.4.4.8 Array.prototype.reverse ( ) // The elements of the array are rearranged so as to reverse their order. The object is returned as the result of the call. map["Array.prototype.reverse"] = function() { // 1. Let O be the result of calling ToObject passing the this value as the argument. var O = ToObject(this) // 2. Let lenVal be the result of calling the [[Get]] internal method of O with argument "length". var lenVal = O["length"] // 3. Let len be ToUint32(lenVal). var len = ToUint32(lenVal) // 4. Let middle be floor(len/2). var middle = Math.floor(len/2) // 5. Let lower be 0. var lower = 0 // 6. Repeat, while lower  middle while (lower != middle) { // a. Let upper be len lower 1. var upper = len - lower - 1 // b. Let upperP be ToString(upper). var upperP = ToString(upper) // c. Let lowerP be ToString(lower). var lowerP = ToString(lower) // d. Let lowerValue be the result of calling the [[Get]] internal method of O with argument lowerP. var lowerValue = O[lowerP] // e. Let upperValue be the result of calling the [[Get]] internal method of O with argument upperP . var upperValue = O[upperP] // f. Let lowerExists be the result of calling the [[HasProperty]] internal method of O with argument lowerP. var lowerExists = HasProperty(O, lowerP) // g. Let upperExists be the result of calling the [[HasProperty]] internal method of O with argument upperP. var upperExists = HasProperty(O, upperP) // h. If lowerExists is true and upperExists is true, then if (lowerExists && upperExists) { // i. Call the [[Put]] internal method of O with arguments lowerP, upperValue, and true . O[lowerP] = upperValue // ii. Call the [[Put]] internal method of O with arguments upperP, lowerValue, and true . O[upperP] = lowerValue } // i. Else if lowerExists is false and upperExists is true, then else if (!lowerExists && upperExists) { // i. Call the [[Put]] internal method of O with arguments lowerP, upperValue, and true . O[lowerP] = upperValue // ii. Call the [[Delete]] internal method of O, with arguments upperP and true. delete O[upperP] } // j. Else if lowerExists is true and upperExists is false, then else if (lowerExists && !upperExists) { // i. Call the [[Delete]] internal method of O, with arguments lowerP and true . delete O[lowerP] // ii. Call the [[Put]] internal method of O with arguments upperP, lowerValue, and true . k. O[upperP] = lowerValue } // k. Else, both lowerExists and upperExists are false // i. No action is required. // l. Increase lower by 1. lower += 1 } // 7. Return O return O } // 15.4.4.9 rray.prototype.shift ( ) // The first element of the array is removed from the array and returned. map["Array.prototype.shift"] = function() { // 1. Let O be the result of calling ToObject passing the this value as the argument. var O = ToObject(this) // 2. Let lenVal be the result of calling the [[Get]] internal method of O with argument "length". var lenVal = O["length"] // 3. Let len be ToUint32(lenVal). var len = ToUint32(lenVal) // 4. If len is zero, then if (len == 0) { // a. Call the [[Put]] internal method of O with arguments "length", 0, and true. O["length"] = 0 // b. Return undefined. return undefined } // 5. Let first be the result of calling the [[Get]] internal method of O with argument "0". var first = O["0"] // 6. Let k be 1. var k = 1 // 7. Repeat, while k < len while (k < len) { // a. Let from be ToString(k). var from_ = ToString(k) // b. Let to be ToString(k–1). var to_ = ToString(k - 1) // c. Let fromPresent be the result of calling the [[HasProperty]] internal method of O with argument from. var fromPresent = HasProperty(O, from_) // d. If fromPresent is true, then if (fromPresent) { // i. Let fromVal be the result of calling the [[Get]] internal method of O with argument from. var fromVal = O[from_] // ii. Call the [[Put]] internal method of O with arguments to, fromVal, and true. O[to_] = fromVal } // e. Else, fromPresent is false else { // i. Call the [[Delete]] internal method of O with arguments to and true. delete O[to_] } // f. Increase k by 1. k += 1 } // 8. [[Delete]] internal method of O with arguments ToString(len–1) and true. delete O[ToString(len - 1)] // 9. [[Put]] internal method of O with arguments "length", (len–1) , and true. O["length"] = len - 1 // 10. Return first. return first } // 192.168.127.12 Array.prototype.slice (start, end) map["Array.prototype.slice"] = function(start, end) { // 1. Let O be the result of calling ToObject passing the this value as the argument. var O = ToObject(this) // 2. Let A be a new array created as if by the expression new Array() where Array is the standard built-in // constructor with that name. var A = new Array() // 3. Let lenVal be the result of calling the [[Get]] internal method of O with argument "length". var lenVal = O.length // 4. Let len be ToUint32(lenVal). var len = ToUint32(lenVal) // 5. Let relativeStart be ToInteger(start). var relativeStart = ToInteger(start) // 6. If relativeStart is negative, var k if (relativeStart < 0) { // let k be max((len + relativeStart),0) k = Math.max((len + relativeStart), 0) } else { // else let k be min(relativeStart, len). k = Math.min(relativeStart, len) } // 7. If end is undefined, var relativeEnd if (end === undefined) { // let relativeEnd be len relativeEnd = len } else { // else let relativeEnd be ToInteger(end). relativeEnd = ToInteger(end) } // 8. If relativeEnd is negative, var final if (relativeEnd < 0) { // let final be max((len + relativeEnd),0) final = Math.max((len + relativeEnd), 0) } else { // else let final be min(relativeEnd, len). final = Math.min(relativeEnd, len) } // 9. Let n be 0. var n = 0 // 10. Repeat, while k < final while (k < final) { // a. Let Pk be ToString(k). var Pk = ToString(k) // b. Let kPresent be the result of calling the [[HasProperty]] internal method of O with argument Pk. var kPresent = HasProperty(O, Pk) // c. If kPresent is true, then var kValue if (kPresent) { // i. Let kValue be the result of calling the [[Get]] internal method of O with argument Pk. kValue = O[Pk] // ii. Call the [[DefineOwnProperty]] internal method of A with arguments ToString(n), Property Descriptor {[[Value]]: kValue, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true}, and false. DefineOwnProperty(A, ToString(n), { value: kValue, writable: true, enumerable: true, configurable: true }, false) } // d. Increase k by 1. k++ // e. Increase n by 1. n++ } // 11. Return A. return A } // 15.4.4.12 Array.prototype.splice (start, deleteCount [ , item1 [ , item2 [ , ... ] ] ] ) map["Array.prototype.splice"] = function(start, deleteCount) { // 1. Let O be the result of calling ToObject passing the this value as the argument. var O = ToObject(this) // 2. Let A be a new array created as if by the expression new Array()where Array is the standard built-in // constructor with that name. var A = new Array() // 3. Let lenVal be the result of calling the [[Get]] internal method of O with argument "length". var lenVal = O.length // 4. Let len be ToUint32(lenVal). var len = ToUint32(lenVal) // 5. Let relativeStart be ToInteger(start). var relativeStart = ToInteger(start) // 6. If relativeStart is negative, let actualStart be max((len + relativeStart),0); else let actualStart be // min(relativeStart, len). var actualStart = 0 if (relativeStart < 0) { actualStart = Math.max((len + relativeStart), 0) } else { actualStart = Math.min(relativeStart, len) } // 7. Let actualDeleteCount be min(max(ToInteger(deleteCount),0), len – actualStart). var actualDeleteCount = Math.min(Math.max(ToInteger(deleteCount), 0), len - actualStart) // 8. Let k be 0. var k = 0 // 9. Repeat, while k < actualDeleteCount while (k < actualDeleteCount) { // a. Let from be ToString(actualStart+k). var from = ToString(actualStart + k) // b. Let fromPresent be the result of calling the [[HasProperty]] internal method of O with argument from. var fromPresent = HasProperty(O, from) // c. If fromPresent is true, then if (fromPresent) { // i. Let fromValue be the result of calling the [[Get]] internal method of O with argument from. var fromValue = O[from] // ii. Call the [[DefineOwnProperty]] internal method of A with arguments ToString(k), Property // Descriptor {[[Value]]: fromValue, [[Writable]]: true, [[Enumerable]]: true, // [[Configurable]]: true}, and false. DefineOwnProperty(A, ToString(k), { value: fromValue, writable: true, enumerable: true, configurable: true }, false) } // d. Increment k by 1. k++ } // 10. Let items be an internal List whose elements are, in left to right order, the portion of the actual argument list starting with item1. The list will be empty if no such items are present. var items = [] for (var i = 2; i < arguments.length; i++) items[i-2] = arguments[i] // 11. Let itemCount be the number of elements in items. var itemCount = items.length // 12. If itemCount < actualDeleteCount, then if (itemCount < actualDeleteCount) { // a. Let k be actualStart. k = actualStart // b. Repeat, while k < (len – actualDeleteCount) while (k < (len - actualDeleteCount)) { // i. Let from be ToString(k+actualDeleteCount). var from = ToString(k + actualDeleteCount) // ii. Let to be ToString(k+itemCount). var to = ToString(k + itemCount) // iii. Let fromPresent be the result of calling the [[HasProperty]] internal method of O with argument from. var fromPresent = HasProperty(O, from) // iv. If fromPresent is true, then if (fromPresent) { // 1. Let fromValue be the result of calling the [[Get]] internal method of O with // argument from. var fromValue = O[from] // 2. Call the [[Put]] internal method of O with arguments to, fromValue, and true. O[to] = fromValue } // v. Else, fromPresent is false else { // 1. Call the [[Delete]] internal method of O with arguments to and true. delete O[to] } // vi. Increase k by 1. k++ } // c. Let k be len. k = len // d. Repeat, while k > (len – actualDeleteCount + itemCount) while (k > (len - actualDeleteCount + itemCount)) { // i. Call the [[Delete]] internal method of O with arguments ToString(k–1) and true. delete O[ToString(k-1)] // ii. Decrease k by 1. k-- } } // 13. Else if itemCount > actualDeleteCount, then else { // a. Let k be (len – actualDeleteCount). var k = (len - actualDeleteCount) // b. Repeat, while k > actualStart while (k > actualStart) { // i. Let from be ToString(k + actualDeleteCount – 1). var from = ToString(k + actualDeleteCount - 1) // ii. Let to be ToString(k + itemCount – 1) var to = ToString(k + itemCount - 1) // iii. Let fromPresent be the result of calling the [[HasProperty]] internal method of O with argument from. var fromPresent = HasProperty(O, from) // iv. If fromPresent is true, then if (fromPresent) { // 1. Let fromValue be the result of calling the [[Get]] internal method of O with // argument from. var fromValue = O[from] // 2. Call the [[Put]] internal method of O with arguments to, fromValue, and true. O[to] = fromValue } // v. Else, fromPresent is false else { // 1. Call the [[Delete]] internal method of O with argument to and true. delete O[to] } // vi. Decrease k by 1. k-- } } // 14. Let k be actualStart. var k = actualStart // 15. Repeat, while items is not empty for (var i = 0; i < items.length; i++) { // a. Remove the first element from items and let E be the value of that element. var E = items[i] // b. Call the [[Put]] internal method of O with arguments ToString(k), E, and true. O[ToString(k)] = E // c. Increase k by 1. k++ } // 16. Call the [[Put]] internal method of O with arguments "length", (len – actualDeleteCount + itemCount), and true. O.length = (len - actualDeleteCount + itemCount) // 17. Return A. return A } // 192.168.3.11 Array.prototype.indexOf ( searchElement [ , fromIndex ] ) map["Array.prototype.indexOf"] = function(searchElement, fromIndex) { // 1. Let O be the result of calling ToObject passing the this value as the argument. var O = ToObject(this) // 2. Let lenValue be the result of calling the [[Get]] internal method of O with the argument "length". var lenValue = O.length // 3. Let len be ToUint32(lenValue). var len = ToUint32(lenValue) // 4. If len is 0, return -1. if (len === 0) { return -1 } // 5. If argument fromIndex was passed let n be ToInteger(fromIndex); else let n be 0. var n = 0 if (fromIndex !== undefined) { n = ToInteger(fromIndex) } // 6. If n ≥ len, return -1. if (n >= len) { return -1 } // 7. If n ≥ 0,then var k = 0 if (n >= 0) { // a. Let k be n. k = n } // 8. Else, n < 0 else { // a. Let k be len - abs(n). k = len - Math.abs(n) // b. If k is less than 0, then let k be 0. if (k < 0) k = 0 } // 9. Repeat, while k < len while (k < len) { // a. Let kPresent be the result of calling the [[HasProperty]] internal method of O with argument ToString(k). var kPresent = HasProperty(O, ToString(k)) // b. If kPresent is true, then if (kPresent) { // i. Let elementK be the result of calling the [[Get]] internal method of O with the argument // ToString(k). var elementK = O[ToString(k)] // ii. Let same be the result of applying the Strict Equality Comparison Algorithm to // searchElement and elementK. var same = searchElement === elementK // iii. If same is true, return k. if (same) { return k } } // c. Increase k by 1. k++ } // 10. Return -1. return -1 } // 172.16.17.32 Array.prototype.lastIndexOf ( searchElement [ , fromIndex ] ) map["Array.prototype.lastIndexOf"] = function(searchElement, fromIndex) { // 1. Let O be the result of calling ToObject passing the this value as the argument. var O = ToObject(this) // 2. Let lenValue be the result of calling the [[Get]] internal method of O with the argument "length". var lenValue = O.length // 3. Let len be ToUint32(lenValue). var len = ToUint32(lenValue) // 4. If len is 0, return -1. if (len === 0) { return -1 } // 5. If argument fromIndex was passed let n be ToInteger(fromIndex); else let n be len-1. var n = len - 1 if (fromIndex !== undefined) { n = ToInteger(fromIndex) } // 6. If n ≥ 0, then let k be min(n,len–1). var k = 0 if (n >= 0) { k = Math.min(n, len - 1) } // 7. Else,n<0 // a. Let k be len - abs(n). else { k = len - Math.abs(n) } // 8. Repeat, while k≥ 0 while (k >= 0) { // a. Let kPresent be the result of calling the [[HasProperty]] internal method of O with argument ToString(k). var kPresent = HasProperty(O, ToString(k)) // b. If kPresent is true, then if (kPresent) { // i. Let elementK be the result of calling the [[Get]] internal method of O with the argument // ToString(k). var elementK = O[ToString(k)] // ii. Let same be the result of applying the Strict Equality Comparison Algorithm to // searchElement and elementK. var same = searchElement === elementK // iii. If same is true, return k. if (same) { return k } } // c. Decrease k by 1. k-- } // 9. Return -1. return -1 }
mskim5383/safe-dynamicTest-generator
src/Recorder.ts
<gh_stars>10-100 /* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Functionality to record the execution of a javascript function by using proxies. * * @author <NAME> <<EMAIL>> */ "use strict"; import Util = require('./util/Util') import Ansi = require('./util/Ansicolors') import Data = require('./Data') import Random = require('./util/Random') // enable proxies var harmonyrefl = require('harmony-reflect'); harmonyrefl; declare var Reflect: any declare var global: any var log = Util.log var print = Util.print /** * Record a trace for the given function and arguments. In the `extended' mode, we additionally * store various intermediate results (e.g. those from all field reads, or the old value of field * writes) in local variables. This is used to make program generation easier. */ export function record(f: (..._: any[]) => any, args: any[], budget: number = 100): Data.Trace { state = new State(budget) var trace = state.trace Data.Var._count = {} args = Util.clone(args) // instrument args var iargs = [] for (var i = 0; i < args.length; i++) { iargs[i] = proxify(args[i]) var ai = new Data.Argument(new Data.Const(i)) state.addCurState(iargs[i], ai) state.addPreState(iargs[i], [ai]) } try { var res = f.apply(null, iargs) trace.setResult(state.texpr(res)) } catch (e) { if (e instanceof Util.AssertionError) { throw e // don't catch our own errors } else if (e instanceof BudgetExhausted) { trace.setExhaustedBudget() } else if (e instanceof ReferenceError) { var ee = <ReferenceError>e trace.setException(state.texpr(ee.message.toString())) } else if (e instanceof TypeError) { var ee = <TypeError>e trace.setException(state.texpr(ee.message.toString())) } else if (e instanceof RangeError) { var ee = <RangeError>e trace.setException(state.texpr(ee.message.toString())) } else if (e instanceof SyntaxError) { var ee = <SyntaxError>e Util.assert(false, () => "syntax error: " + ee.toString() + "\n\nfor program: " + f.toString()) } else { trace.setException(state.texpr(e)) } } trace.setPrestates(state.preStates) trace.setConstants(state.constants) state = null //state = new State(100000) //state.doRecord = false return trace } class BudgetExhausted { } class State { /** Are we currently recording? */ public doRecord: boolean = true /** map objects to their proxified object */ public proxy2object: Map<Object, Object> = new Map<Object, Object>() /** map proxified objects to their target */ public object2proxy: Map<Object, Object> = new Map<Object, Object>() /** the current trace */ public trace: Data.Trace = new Data.Trace() public preState = new Map<Object, Data.Prestate[]>() public curState = new Map<Object, Data.Expr[]>() public preStates: Data.Prestate[] = [] public constants: Data.Const[] = [] private budgetUsed = 0 constructor(public budget: number) { } /** record an event */ record(ev: Data.Event) { if (this.budgetUsed > this.budget) { throw new BudgetExhausted() } this.trace.extend(ev) } /** add a step in the execution (for budget calculations) */ addStep() { this.budgetUsed += 1 } /** get the trace expression for an (unproxied) value */ texpr(v: any): Data.TraceExpr { if (Util.isPrimitive(v)) { this.constants.push(new Data.Const(v)) return new Data.TraceConst(v) } if (!this.proxy2object.has(v)) { // newly allocated object return new Data.TraceAlloc(v) } Util.assert(this.proxy2object.has(v), () => "texpr only accepts proxied inputs") return new Data.TraceExpr(this.preState.get(v), this.curState.get(v)) } /** add an expression as the current state expression of a value */ addCurState(v: any, e: Data.Expr) { if (Util.isPrimitive(v)) return Util.assert(this.proxy2object.has(v), () => "addCurState only accepts proxied inputs") var state = this.curState.get(v) || [] state.push(e) this.curState.set(v, state) } /** add a list of expressions as the pre-state expression of a value */ addPreState(v: any, es: Data.Prestate[]) { this.preStates = this.preStates.concat(es) if (Util.isPrimitive(v)) return Util.assert(this.proxy2object.has(v), () => "addPreState only accepts proxied inputs") var state = this.preState.get(v) || [] state = state.concat(es) this.preState.set(v, state) } } var state: State = null var common = function (target: Object): Data.TraceExpr { //if (!state.object2proxy.has(target)) { // return; //} state.addStep() Util.assert(state.object2proxy.has(target), () => "target not proxied: " + Util.inspect(target)) var res = state.texpr(state.object2proxy.get(target)) Util.assert(res !== undefined, () => "target TraceExpr undefined") return res } var ignorec = (a: any) => print(Ansi.lightgrey(a)) ignorec = (a: any) => a function makeFieldName(target: any, name: string) { if (Array.isArray(target) && Util.isInt(name)) { return new Data.Const(parseInt(name, 10)) } return new Data.Const(name) } var Handler = { get: function(target, name: string, receiver) { if (name === "inspect") { // TODO: why is this happening? improve/fix return undefined } var ttarget = common(target) if (state.doRecord) { if (!(name in target) || target.hasOwnProperty(name)) { var val = target[name]; var pval = proxify(val) if (state.doRecord) { var event = new Data.EGet(ttarget, state.texpr(name)) state.record(event) state.addCurState(pval, event.variable) var fieldId = new Data.Const(name) state.addPreState(pval, ttarget.preState.map((t) => new Data.Field(t, fieldId))) } return pval } else { // TODO handle properties that are somewhere else ignorec("ignoring access to '" + name + "'.") } } return Reflect.get(target, name, receiver); }, set: function(target, name: string, value, receiver) { var ttarget = common(target) var res if (state.doRecord) { var tval = state.texpr(value) var event = new Data.ESet(ttarget, state.texpr(name), tval) state.record(event) res = Reflect.set(target, name, value, receiver) state.addCurState(res, event.variable) } else { res = Reflect.set(target, name, value, receiver) } return res }, has: function(target, name: string) { var ttarget = common(target) if (state.doRecord) { var val = name in target; var pval = proxify(val) if (state.doRecord) { var event = new Data.EHas(ttarget, state.texpr(name)) state.record(event) } return pval } return Reflect.has(target, name); }, apply: function(target, receiver, args) { var ttarget = common(target) var result if (state.doRecord) { var targs = args.map((a) => state.texpr(a)) var recv = null if (receiver !== global) { recv = state.texpr(receiver) } var event = new Data.EApply(ttarget, recv, targs) state.record(event) var prevDoRecord = state.doRecord state.doRecord = false result = Reflect.apply(target, receiver, args) state.doRecord = prevDoRecord state.addCurState(result, event.variable) } else { result = Reflect.apply(target, receiver, args) } return result }, construct: function(target, args) { ignorec(".. unhandled call to construct") var ttarget = common(target) return Reflect.construct(target, args); }, getOwnPropertyDescriptor: function(target, name: string) { ignorec(".. unhandled call to getOwnPropertyDescriptor for " + name + " on " + Util.inspect(target)) var ttarget = common(target) return Reflect.getOwnPropertyDescriptor(target, name); }, defineProperty: function(target, name: string, desc) { var ttarget = common(target) if (state.doRecord) { if ("value" in desc) { // TODO ignorec(".. unhandled call to defineProperty (ignore for now)") } else { ignorec(".. unhandled call to defineProperty (unhandled type of descriptor)") } } return Reflect.defineProperty(target, name, desc); }, getOwnPropertyNames: function(target) { ignorec(".. unhandled call to getOwnPropertyNames") var ttarget = common(target) return Reflect.getOwnPropertyNames(target); }, getPrototypeOf: function(target) { ignorec(".. unhandled call to getPrototypeOf") var ttarget = common(target) return Reflect.getPrototypeOf(target); }, setPrototypeOf: function(target, newProto) { ignorec(".. unhandled call to setPrototypeOf") var ttarget = common(target) return Reflect.setPrototypeOf(target, newProto); }, deleteProperty: function(target, name: string) { var ttarget = common(target) if (state.doRecord) { state.record(new Data.EDeleteProperty(ttarget, state.texpr(name))) } return Reflect.deleteProperty(target, name); }, enumerate: function(target) { ignorec(".. unhandled call to enumerate") var ttarget = common(target) return Reflect.enumerate(target); }, preventExtensions: function(target) { ignorec(".. unhandled call to preventExtensions") var ttarget = common(target) return Reflect.preventExtensions(target); }, isExtensible: function(target) { ignorec(".. unhandled call to isExtensible on "+Util.inspect(target)) var ttarget = common(target) return Reflect.isExtensible(target); }, ownKeys: function(target) { ignorec(".. unhandled call to ownKeys") var ttarget = common(target) return Reflect.ownKeys(target); } } function proxify<T>(o: T): T { if (Util.isPrimitive(o)) return o if (state.object2proxy.has(o)) return <T>state.object2proxy.get(o) if (state.proxy2object.has(o)) return o var p = new Proxy(o, Handler) state.proxy2object.set(p, o) state.object2proxy.set(o, p) return p } var recv = new Proxy({}, { set: function(target, name: string, value, receiver) { if (state != null) { state.addStep() } return Reflect.set(target, name, value, receiver) } }) /** Returns a receiver that is used for function calls to prevent infinite loops. */ export function getReceiver() { return recv } /** * Proxify the object `o', and log all behavior (in addition to actually performing the actions). */ export function proxifyWithLogger<T>(o: T, tag: string = " ", level: number = 0, cache: WeakMap<any, any> = new WeakMap<any, any>()): T { var debug = true if (Util.isPrimitive(o)) return o if (cache.has(o)) { return cache.get(o) } var common = function (target): string { var s = tag + " " if (level === 0) { } else { s += "" + level + " " } return s } var recurse = (o) => proxifyWithLogger(o, tag, level+1, cache) var logaccess = (a: any) => { if (debug) print(Ansi.lightgrey(a)) } var Handler = { get: function(target, name: string, receiver) { var value = Reflect.get(target, name, receiver); var s = common(target) + "get of " + name; if (Util.isPrimitive(value)) { s += " (yields " + value + ")" } else { value = recurse(value) } logaccess(s) return value; }, set: function(target, name: string, value, receiver) { var s = common(target) s += "set of " + name; if (Util.isPrimitive(value)) { s += " (with value " + value + ")" } logaccess(s) return Reflect.set(target, name, value, receiver); }, has: function(target, name: string) { var s = common(target) logaccess(s + "has of " + name) return Reflect.has(target, name); }, apply: function(target, receiver, args) { var s = common(target) var id = "0x" + Util.pad(Random.randInt(Math.pow(16, 4)).toString(16), 4, "0") logaccess(s + "apply start "+id) var v = Reflect.apply(target, receiver, args); if (Util.isPrimitive(v)) { logaccess(s + "apply end " + id + " (result: " + v + ")") } else { logaccess(s + "apply end " + id) v = recurse(v) } return v; }, construct: function(target, args) { var s = common(target) logaccess(s + "construct") return Reflect.construct(target, args); }, getOwnPropertyDescriptor: function(target, name: string) { var s = common(target) logaccess(s + "getOwnPropertyDescriptor for " + name) return Reflect.getOwnPropertyDescriptor(target, name); }, defineProperty: function(target, name: string, desc) { var s = common(target) logaccess(s + "defineProperty for " + name) return Reflect.defineProperty(target, name, desc); }, getOwnPropertyNames: function(target) { var s = common(target) logaccess(s + "getOwnPropertyNames") return Reflect.getOwnPropertyNames(target); }, getPrototypeOf: function(target) { var s = common(target) logaccess(s + "getPrototypeOf") return Reflect.getPrototypeOf(target); }, setPrototypeOf: function(target, newProto) { var s = common(target) logaccess(s + "setPrototypeOf") return Reflect.setPrototypeOf(target, newProto); }, deleteProperty: function(target, name: string) { var s = common(target) logaccess(s + "deleteProperty for " + name) return Reflect.deleteProperty(target, name); }, enumerate: function(target) { var s = common(target) logaccess(s + "enumerate") return recurse(Reflect.enumerate(target)) }, preventExtensions: function(target) { var s = common(target) logaccess(s + "preventExtensions") return Reflect.preventExtensions(target); }, isExtensible: function(target) { var s = common(target) logaccess(s + "isExtensible") return Reflect.isExtensible(target); }, ownKeys: function(target) { var s = common(target) logaccess(s + "ownKeys") return Reflect.ownKeys(target); } } var p = new Proxy(o, Handler) cache.set(o, p) return <T>p } /* var Handler = { get: function(target, name: string, receiver) { }, set: function(target, name: string, value, receiver) { }, has: function(target, name: string) { }, apply: function(target, receiver, args) { }, construct: function(target, args) { }, getOwnPropertyDescriptor: function(target, name: string) { }, defineProperty: function(target, name: string, desc) { }, getOwnPropertyNames: function(target) { }, getPrototypeOf: function(target) { }, setPrototypeOf: function(target, newProto) { }, deleteProperty: function(target, name: string) { }, enumerate: function(target) { }, preventExtensions: function(target) { }, isExtensible: function(target) { }, ownKeys: function(target) { } } export function proxifyWithLogger2<T>(o: T): T { var p = Proxy(o, Handler) return <T>p }*/ export function all(f, inputs): Data.Trace[] { return inputs.map((i) => record(f, i)) }
MaxKlaxxMiner/factorio_belt_simulator
FactorioTransportBeltSimulator/ts/sprites.ts
/* tslint:disable:one-line max-line-length interface-name comment-format no-bitwise */ class Sprites { tutorialGrid: HTMLImageElement; transportBelt: HTMLImageElement; splitterNorth: HTMLImageElement; splitterSouth: HTMLImageElement; splitterWestTop: HTMLImageElement; splitterWest: HTMLImageElement; splitterEastTop: HTMLImageElement; splitterEast: HTMLImageElement; undergroundBelt: HTMLImageElement; static showError = false; static loadImg(url: string, callback: (img: HTMLImageElement) => void): void { const img = new Image(); img.onload = () => callback(img); img.onerror = () => { console.error("load error: " + url); if (this.showError) return; alert("load error: " + url); this.showError = true; } img.src = url; } constructor() { Sprites.loadImg("/factorio/data/base/graphics/terrain/tutorial-grid/hr-tutorial-grid1.png", img => { this.tutorialGrid = img; }); const path = "/factorio/data/base/graphics/entity/"; Sprites.loadImg(path + "transport-belt/hr-transport-belt.png", img => { this.transportBelt = img; }); Sprites.loadImg(path + "splitter/hr-splitter-north.png", img => { this.splitterNorth = img; }); Sprites.loadImg(path + "splitter/hr-splitter-south.png", img => { this.splitterSouth = img; }); Sprites.loadImg(path + "splitter/hr-splitter-east-top_patch.png", img => { this.splitterEastTop = img; }); Sprites.loadImg(path + "splitter/hr-splitter-east.png", img => { this.splitterEast = img; }); Sprites.loadImg(path + "splitter/hr-splitter-west-top_patch.png", img => { this.splitterWestTop = img; }); Sprites.loadImg(path + "splitter/hr-splitter-west.png", img => { this.splitterWest = img; }); Sprites.loadImg(path + "underground-belt/underground-belt-structure.png", img => { this.undergroundBelt = img; }); } loadChecked = false; hasLoaded(): boolean { if (this.loadChecked) return true; const check = this.tutorialGrid && this.transportBelt && this.splitterNorth && this.splitterSouth && this.splitterWestTop && this.splitterWest && this.splitterEastTop && this.splitterEast && this.undergroundBelt && true; if (check) this.loadChecked = true; return check; } }
MaxKlaxxMiner/factorio_belt_simulator
FactorioTransportBeltSimulator/ts/display.ts
<reponame>MaxKlaxxMiner/factorio_belt_simulator /* tslint:disable:one-line max-line-length interface-name comment-format no-bitwise */ class Display { gameDiv: HTMLElement; canvasElement: HTMLCanvasElement; canvasContext: CanvasRenderingContext2D; title = document.title; sprites: Sprites; map: Map; entityTransportBelt: DisplayEntityTransportBelt; entitySplitter: DisplayEntitySplitter; constructor(gameDiv: HTMLElement, canvasWidth: number, canvasHeight: number, map: Map) { this.gameDiv = gameDiv; gameDiv.style.width = canvasWidth + "px"; gameDiv.style.height = canvasHeight + "px"; gameDiv.style.backgroundColor = "#036"; this.canvasElement = document.createElement("canvas"); this.canvasElement.width = canvasWidth; this.canvasElement.height = canvasHeight; this.canvasContext = this.canvasElement.getContext("2d"); gameDiv.appendChild(this.canvasElement); this.sprites = new Sprites(); this.setScale(18); this.entityTransportBelt = new DisplayEntityTransportBelt(); this.entitySplitter = new DisplayEntitySplitter(); this.map = map; // add ultra-zoom for (let z = this.zoomLevels[this.zoomLevels.length - 1]; z < 20000; z *= Math.pow((Math.sqrt(5) + 1) / 2, 1 / 3)) this.zoomLevels.push((z + 0.5) >> 0); } countFrame = 0; countCalc = 0; nextFrameLog = 0; lastFrameLog = 0; animate = 0; scaleLevel: number; scale: number; offsetX = 0; offsetY = 0; zoomLevels = [2, 3, 4, 5, 6, 8, 10, 12, 14, 16, 19, 22, 26, 30, 36, 42, 49, 57, 67, 79, 93, 109, 128]; setScale(scaleLevel: number): void { scaleLevel = scaleLevel >> 0; if (scaleLevel >= this.zoomLevels.length) scaleLevel = this.zoomLevels.length - 1; if (scaleLevel < 0) scaleLevel = 0; if (scaleLevel !== this.scaleLevel) { this.scaleLevel = scaleLevel; const newScale = this.zoomLevels[scaleLevel]; if (this.scale) { this.offsetX = (this.offsetX - mouseX) / this.scale * newScale + mouseX; this.offsetY = (this.offsetY - mouseY) / this.scale * newScale + mouseY; } this.scale = newScale; } } calc(): void { this.animate++; this.countCalc++; } getMouseFieldPos(): { x: number, y: number } { const x = ((mouseX - this.offsetX + this.scale * 1000000) / this.scale >> 0) - 1000000; const y = ((mouseY - this.offsetY + this.scale * 1000000) / this.scale >> 0) - 1000000; return { x, y }; } drawEntities(entities: Array<{ x: number, y: number, e: MapEntity }>): void { const belt = this.entityTransportBelt.draw; const splitter = this.entitySplitter.draw; // --- pipeline step 1: draw transport belts --- const beltAdds: { x: number, y: number, t: BeltType }[] = []; const entityAdds: { x: number, y: number, t: number, animate?: number, draw: (x: number, y: number, type: number, animate?: number) => void }[] = []; entities.forEach(entity => { const x = entity.x; const y = entity.y; const e = entity.e; switch (e.t) { case EntityType.transportBelt: { switch (e.d) // direction { case Direction.top: { if (e.isCurve()) { if (e.fromLeft()) belt(x, y, BeltType.leftToTop); if (e.fromRight()) belt(x, y, BeltType.rightToTop); } else { belt(x, y, BeltType.bottomToTop); if (!e.fromBottom(true)) beltAdds.push({ x: x, y: y + 1, t: BeltType.voidToTop }); } if (e.tn === undefined || !e.tn.isCurve() && !e.fromTop(true)) beltAdds.push({ x: x, y: y - 1, t: BeltType.bottomToVoid }); } break; case Direction.right: { if (e.isCurve()) { if (e.fromTop()) belt(x, y, BeltType.topToRight); if (e.fromBottom()) belt(x, y, BeltType.bottomToRight); } else { belt(x, y, BeltType.leftToRight); if (!e.fromLeft(true)) beltAdds.push({ x: x - 1, y: y, t: BeltType.voidToRight }); } if (e.rn === undefined || !e.rn.isCurve() && !e.fromRight(true)) beltAdds.push({ x: x + 1, y: y, t: BeltType.leftToVoid }); } break; case Direction.bottom: { if (e.isCurve()) { if (e.fromLeft()) belt(x, y, BeltType.leftToBottom); if (e.fromRight()) belt(x, y, BeltType.rightToBottom); } else { belt(x, y, BeltType.topToBottom); if (!e.fromTop(true)) beltAdds.push({ x: x, y: y - 1, t: BeltType.voidToBottom }); } if (e.bn === undefined || !e.bn.isCurve() && !e.fromBottom(true)) beltAdds.push({ x: x, y: y + 1, t: BeltType.topToVoid }); } break; case Direction.left: { if (e.isCurve()) { if (e.fromTop()) belt(x, y, BeltType.topToLeft); if (e.fromBottom()) belt(x, y, BeltType.bottomToLeft); } else { belt(x, y, BeltType.rightToLeft); if (!e.fromRight(true)) beltAdds.push({ x: x + 1, y: y, t: BeltType.voidToLeft }); } if (e.ln === undefined || !e.ln.isCurve() && !e.fromLeft(true)) beltAdds.push({ x: x - 1, y: y, t: BeltType.rightToVoid }); } break; } } break; case EntityType._splitterLeft: { switch (e.d) // direction { case Direction.top: { belt(x, y, BeltType.bottomToTop); belt(x + 1, y, BeltType.bottomToTop); if (!e.fromBottom(true)) beltAdds.push({ x: x, y: y + 1, t: BeltType.voidToTop }); if (!e.rn.fromBottom(true)) beltAdds.push({ x: x + 1, y: y + 1, t: BeltType.voidToTop }); if (e.tn === undefined || !e.tn.isCurve() && !e.fromTop(true)) beltAdds.push({ x: x, y: y - 1, t: BeltType.bottomToVoid }); if (e.rn.tn === undefined || !e.rn.tn.isCurve() && !e.rn.fromTop(true)) beltAdds.push({ x: x + 1, y: y - 1, t: BeltType.bottomToVoid }); entityAdds.push({ x: x, y: y, t: 0, draw: splitter }); } break; case Direction.right: { belt(x, y, BeltType.leftToRight); belt(x, y + 1, BeltType.leftToRight); if (!e.fromLeft(true)) beltAdds.push({ x: x - 1, y: y, t: BeltType.voidToRight }); if (!e.bn.fromLeft(true)) beltAdds.push({ x: x - 1, y: y + 1, t: BeltType.voidToRight }); if (e.rn === undefined || !e.rn.isCurve() && !e.fromRight(true)) beltAdds.push({ x: x + 1, y: y, t: BeltType.leftToVoid }); if (e.bn.rn === undefined || !e.bn.rn.isCurve() && !e.bn.fromRight(true)) beltAdds.push({ x: x + 1, y: y + 1, t: BeltType.leftToVoid }); entityAdds.push({ x: x, y: y, t: 3, draw: splitter }); } break; case Direction.bottom: { belt(x - 1, y, BeltType.topToBottom); belt(x, y, BeltType.topToBottom); if (!e.fromTop(true)) beltAdds.push({ x: x, y: y - 1, t: BeltType.voidToBottom }); if (!e.ln.fromTop(true)) beltAdds.push({ x: x - 1, y: y - 1, t: BeltType.voidToBottom }); if (e.bn === undefined || !e.bn.isCurve() && !e.fromBottom(true)) beltAdds.push({ x: x, y: y + 1, t: BeltType.topToVoid }); if (e.ln.bn === undefined || !e.ln.bn.isCurve() && !e.ln.fromBottom(true)) beltAdds.push({ x: x - 1, y: y + 1, t: BeltType.topToVoid }); entityAdds.push({ x: x - 1, y: y, t: 1, draw: splitter }); } break; case Direction.left: { belt(x, y - 1, BeltType.rightToLeft); belt(x, y, BeltType.rightToLeft); if (!e.fromRight(true)) beltAdds.push({ x: x + 1, y: y, t: BeltType.voidToLeft }); if (!e.tn.fromRight(true)) beltAdds.push({ x: x + 1, y: y - 1, t: BeltType.voidToLeft }); if (e.ln === undefined || !e.ln.isCurve() && !e.fromLeft(true)) beltAdds.push({ x: x - 1, y: y, t: BeltType.rightToVoid }); if (e.tn.ln === undefined || !e.tn.ln.isCurve() && !e.tn.fromLeft(true)) beltAdds.push({ x: x - 1, y: y - 1, t: BeltType.rightToVoid }); entityAdds.push({ x: x, y: y - 1, t: 2, draw: splitter }); } break; } } break; } }); // --- pipeline step 2: draw belt additives --- beltAdds.forEach(add => { belt(add.x, add.y, add.t); }); // --- pipeline step 3: draw entities --- entityAdds.forEach(add => { add.draw(add.x, add.y, add.t, add.animate); }); } previewEntity: EntityType = EntityType.transportBelt; previewDirection: Direction = Direction.right; drawPreviewEntity(ctx: CanvasRenderingContext2D): void { const m = this.getMouseFieldPos(); ctx.globalAlpha = 0.7; const e = new MapEntity(m.x, m.y, this.previewEntity, this.previewDirection); e.tn = this.map.getEntity(e.x, e.y - 1); e.rn = this.map.getEntity(e.x + 1, e.y); e.bn = this.map.getEntity(e.x, e.y + 1); e.ln = this.map.getEntity(e.x - 1, e.y); this.drawEntities([{ x: m.x, y: m.y, e: e }]); ctx.globalAlpha = 1; } draw(time: number): boolean { // --- pipeline step 0: prepare --- if (!this.sprites || !this.sprites.hasLoaded()) return false; // missing sprites? this.entityTransportBelt.prepareForDisplay(this); this.entitySplitter.prepareForDisplay(this); const c = this.canvasContext; const w = this.canvasElement.width; const h = this.canvasElement.height; c.imageSmoothingEnabled = false; c.imageSmoothingQuality = "high"; // --- pipeline step 1: background (tutorial-grid) --- if (this.scaleLevel >= 8) { c.clearRect(0, 0, w, h); const picWidth = this.sprites.tutorialGrid.width; const picHeight = this.sprites.tutorialGrid.height; const gridWidth = picWidth * this.scale / 64 >> 0; const gridHeight = picHeight * this.scale / 64 >> 0; const startY = -((this.offsetY / gridHeight >> 0) + 1) * gridHeight; const endY = h - this.offsetY; const endX = w - this.offsetX; for (let y = startY; y <= endY; y += gridHeight) { const startX = ((y + gridHeight * 1000000) * -6) % gridWidth - ((this.offsetX / gridWidth >> 0) + 1) * gridWidth; for (let x = startX; x <= endX; x += gridWidth) { c.drawImage(this.sprites.tutorialGrid, x + this.offsetX, y + this.offsetY, gridWidth, gridHeight); } } } else // fill gray = faster { c.fillStyle = "#848484"; c.fillRect(0, 0, w, w); } if (this.scaleLevel < 2) c.imageSmoothingEnabled = true; //todo: optimize viewport const entityList: Array<{ x: number, y: number, e: MapEntity }> = []; this.map.callEntities(-100, -100, 100, 100, (x, y, e) => entityList.push({ x, y, e })); this.drawEntities(entityList); // --- draw preview --- if (mouseX + mouseY > 0 && this.scale < 500) { this.drawPreviewEntity(c); } // --- Helper lines --- const helpLines = (x: number, y: number, width: number, height: number) => { c.beginPath(); c.strokeStyle = "#0f0"; c.lineWidth = 1; const s = this.scale; for (let cy = 0; cy <= height; cy++) { c.moveTo(x * s + 0.5, (y + cy) * s + 0.5); c.lineTo((x + width) * s + 0.5, (y + cy) * s + 0.5); } for (let cx = 0; cx <= width; cx++) { c.moveTo((x + cx) * s + 0.5, y * s + 0.5); c.lineTo((x + cx) * s + 0.5, (y + height) * s + 0.5); } c.stroke(); c.closePath(); }; //helpLines(mx, my, 1, 1); // --- Final --- if (this.animate < 120) { c.globalAlpha = Easing.easeInQuad((120 - this.animate) / 120); c.fillStyle = "#000"; c.fillRect(0, 0, w, h); c.globalAlpha = 1.0; } this.countFrame++; if (time > this.nextFrameLog) { if (this.countFrame > 0) document.title = this.title + " - FPS " + (this.countFrame / (time - this.lastFrameLog) * 1000).toFixed(1) + ", UPS " + (this.countCalc / (time - this.lastFrameLog) * 1000).toFixed(1); this.countFrame = 0; this.countCalc = 0; this.nextFrameLog += 1000; this.lastFrameLog = time; if (this.nextFrameLog < time) this.nextFrameLog = time; } return true; } }
MaxKlaxxMiner/factorio_belt_simulator
FactorioTransportBeltSimulator/ts/displayEntities.ts
/* tslint:disable:one-line max-line-length interface-name comment-format no-bitwise */ enum BeltType { leftToRight = 0, rightToLeft = 1, bottomToTop = 2, topToBottom = 3, rightToTop = 4, topToRight = 5, leftToTop = 6, topToLeft = 7, bottomToRight = 8, rightToBottom = 9, bottomToLeft = 10, leftToBottom = 11, voidToTop = 12, topToVoid = 13, voidToRight = 14, rightToVoid = 15, voidToBottom = 16, bottomToVoid = 17, voidToLeft = 18, leftToVoid = 19 } class DisplayEntity { ctx: CanvasRenderingContext2D; ofsX: number; ofsY: number; scale: number; scaleX: number; scaleY: number; spriteW: number; spriteH: number; animate: number; sprite: HTMLImageElement; constructor() { this.draw = this.draw.bind(this); } prepareForDisplay(display: Display): void { this.ctx = display.canvasContext; this.ofsX = display.offsetX; this.ofsY = display.offsetY; this.scale = display.scale; this.scaleX = display.scale; this.scaleY = display.scale; this.spriteW = 32; this.spriteH = 32; this.animate = display.animate; } draw(x: number, y: number, type: number, animate?: number) { } } class DisplayEntityTransportBelt extends DisplayEntity { prepareForDisplay(display: Display) { super.prepareForDisplay(display); this.sprite = display.sprites.transportBelt; this.ofsX -= this.scale * 0.5; this.ofsY -= this.scale * 0.5; this.scaleX *= 2; this.scaleY *= 2; this.spriteW = this.sprite.width / 16 >> 0; this.spriteH = this.sprite.height / 20 >> 0; this.animate &= 15; } draw(x: number, y: number, type: BeltType) { this.ctx.drawImage(this.sprite, this.animate * this.spriteW, type * this.spriteH, this.spriteW, this.spriteH, x * this.scale + this.ofsX, y * this.scale + this.ofsY, this.scaleX, this.scaleY); } } class DisplayEntitySplitterSouth extends DisplayEntity { prepareForDisplay(display: Display) { super.prepareForDisplay(display); this.sprite = display.sprites.splitterSouth; this.ofsX -= this.scale * 0.155; this.scaleX *= 2.56; this.spriteW = this.sprite.width / 8 >> 0; this.spriteH = this.sprite.height / 4 >> 0; this.animate = this.animate * 0.70 & 31; } draw(x: number, y: number, type: number, animate?: number) { if (animate === undefined) animate = this.animate; this.ctx.drawImage(this.sprite, (animate & 7) * this.spriteW, (animate >> 3) * this.spriteH, this.spriteW, this.spriteH, x * this.scale + this.ofsX, y * this.scale + this.ofsY, this.scaleX, this.scaleY); } } class DisplayEntitySplitterNorth extends DisplayEntity { prepareForDisplay(display: Display) { super.prepareForDisplay(display); this.sprite = display.sprites.splitterNorth; this.ofsX -= this.scale * 0.03; this.ofsY -= this.scale * 0.05; this.scaleX *= 2.5; this.scaleY *= 1.1; this.spriteW = this.sprite.width / 8 >> 0; this.spriteH = this.sprite.height / 4 >> 0; this.animate = this.animate * 0.70 & 31; } draw(x: number, y: number, type: number, animate?: number) { if (animate === undefined) animate = this.animate; this.ctx.drawImage(this.sprite, (animate & 7) * this.spriteW, (animate >> 3) * this.spriteH, this.spriteW, this.spriteH, x * this.scale + this.ofsX, y * this.scale + this.ofsY, this.scaleX, this.scaleY); } } class DisplayEntitySplitterWestTop extends DisplayEntity { prepareForDisplay(display: Display) { super.prepareForDisplay(display); this.sprite = display.sprites.splitterWestTop; this.spriteW = this.sprite.width / 8 >> 0; this.spriteH = this.sprite.height / 4 >> 0; this.ofsX -= this.scale * 0.015; this.ofsY -= this.scale * 0.3134; this.scaleX *= 1.40; this.scaleY *= 1.50; this.animate = this.animate * 0.70 & 31; } draw(x: number, y: number, type: number, animate?: number) { if (animate === undefined) animate = this.animate; this.ctx.drawImage(this.sprite, (animate & 7) * this.spriteW, (animate >> 3) * this.spriteH, this.spriteW, this.spriteH, x * this.scale + this.ofsX, y * this.scale + this.ofsY, this.scaleX, this.scaleY); } } class DisplayEntitySplitterWest extends DisplayEntity { top: DisplayEntitySplitterWestTop; constructor() { super(); this.top = new DisplayEntitySplitterWestTop(); } prepareForDisplay(display: Display) { super.prepareForDisplay(display); this.top.prepareForDisplay(display); this.sprite = display.sprites.splitterWest; this.spriteW = this.sprite.width / 8 >> 0; this.spriteH = this.sprite.height / 4 >> 0; this.ofsX -= this.scale * 0.015; this.ofsY -= this.scale * 0.30; this.scaleX *= 1.40; this.scaleY *= 1.35; this.animate = this.animate * 0.70 & 31; } draw(x: number, y: number, type: number, animate?: number) { this.top.draw(x, y, type, animate); if (animate === undefined) animate = this.animate; this.ctx.drawImage(this.sprite, (animate & 7) * this.spriteW, (animate >> 3) * this.spriteH, this.spriteW, this.spriteH, x * this.scale + this.ofsX, (y + 1) * this.scale + this.ofsY, this.scaleX, this.scaleY); } } class DisplayEntitySplitterEastTop extends DisplayEntity { prepareForDisplay(display: Display) { super.prepareForDisplay(display); this.sprite = display.sprites.splitterEastTop; this.spriteW = this.sprite.width / 8 >> 0; this.spriteH = this.sprite.height / 4 >> 0; this.ofsX -= this.scale * 0.075; this.ofsY -= this.scale * 0.434; this.scaleX *= 1.40; this.scaleY *= 1.62; this.animate = this.animate * 0.70 & 31; } draw(x: number, y: number, type: number, animate?: number) { if (animate === undefined) animate = this.animate; this.ctx.drawImage(this.sprite, (animate & 7) * this.spriteW, (animate >> 3) * this.spriteH, this.spriteW, this.spriteH, x * this.scale + this.ofsX, y * this.scale + this.ofsY, this.scaleX, this.scaleY); } } class DisplayEntitySplitterEast extends DisplayEntity { top: DisplayEntitySplitterEastTop; constructor() { super(); this.top = new DisplayEntitySplitterEastTop(); } prepareForDisplay(display: Display) { super.prepareForDisplay(display); this.top.prepareForDisplay(display); this.sprite = display.sprites.splitterEast; this.spriteW = this.sprite.width / 8 >> 0; this.spriteH = this.sprite.height / 4 >> 0; this.ofsX -= this.scale * 0.075; this.ofsY -= this.scale * 0.25; this.scaleX *= 1.40; this.scaleY *= 1.303; this.animate = this.animate * 0.70 & 31; } draw(x: number, y: number, type: number, animate?: number) { this.top.draw(x, y, type, animate); if (animate === undefined) animate = this.animate; this.ctx.drawImage(this.sprite, (animate & 7) * this.spriteW, (animate >> 3) * this.spriteH, this.spriteW, this.spriteH, x * this.scale + this.ofsX, (y + 1) * this.scale + this.ofsY, this.scaleX, this.scaleY); } } class DisplayEntitySplitter extends DisplayEntity { splitterNorth: DisplayEntitySplitterNorth; splitterSouth: DisplayEntitySplitterSouth; splitterWest: DisplayEntitySplitterWest; splitterEast: DisplayEntitySplitterEast; constructor() { super(); this.splitterNorth = new DisplayEntitySplitterNorth(); this.splitterSouth = new DisplayEntitySplitterSouth(); this.splitterWest = new DisplayEntitySplitterWest(); this.splitterEast = new DisplayEntitySplitterEast(); } prepareForDisplay(display: Display) { super.prepareForDisplay(display); this.splitterNorth.prepareForDisplay(display); this.splitterSouth.prepareForDisplay(display); this.splitterWest.prepareForDisplay(display); this.splitterEast.prepareForDisplay(display); } draw(x: number, y: number, type: number, animate?: number) { switch (type) { case 0: this.splitterNorth.draw(x, y, 0, animate); break; case 1: this.splitterSouth.draw(x, y, 0, animate); break; case 2: this.splitterWest.draw(x, y, 0, animate); break; case 3: this.splitterEast.draw(x, y, 0, animate); break; } } }
MaxKlaxxMiner/factorio_belt_simulator
FactorioTransportBeltSimulator/ts/tools.ts
<filename>FactorioTransportBeltSimulator/ts/tools.ts /* tslint:disable:one-line max-line-length interface-name comment-format no-bitwise */ const requestAnimFrame = (() => (window.requestAnimationFrame || (<any>window).webkitRequestAnimationFrame || (<any>window).mozRequestAnimationFrame || ((cb: TimerHandler) => window.setTimeout(cb, 1000 / 60))))(); interface DocumentSize { width: number; height: number; } function getDocumentSize(): DocumentSize { const body = document.body; const html = document.documentElement; return { width: Math.max(body.scrollWidth, body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth), height: Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight) }; } const Easing = { /** no easing, no acceleration */ linear: (t: number) => t, /** accelerating from zero velocity */ easeInQuad: (t: number) => t * t, /** decelerating to zero velocity */ easeOutQuad: (t: number) => t * (2 - t), /** acceleration until halfway, then deceleration */ easeInOutQuad: (t: number) => t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t, /** accelerating from zero velocity */ easeInCubic: (t: number) => t * t * t, /** decelerating to zero velocity */ easeOutCubic: (t: number) => (--t) * t * t + 1, /** acceleration until halfway, then deceleration */ easeInOutCubic: (t: number) => t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1, /** accelerating from zero velocity */ easeInQuart: (t: number) => t * t * t * t, /** decelerating to zero velocity */ easeOutQuart: (t: number) => 1 - (--t) * t * t * t, /** acceleration until halfway, then deceleration */ easeInOutQuart: (t: number) => t < .5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t, /** accelerating from zero velocity */ easeInQuint: (t: number) => t * t * t * t * t, /** decelerating to zero velocity */ easeOutQuint: (t: number) => 1 + (--t) * t * t * t * t, /** acceleration until halfway, then deceleration */ easeInOutQuint: (t: number) => t < .5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t };
MaxKlaxxMiner/factorio_belt_simulator
FactorioTransportBeltSimulator/ts/map.ts
<gh_stars>0 /* tslint:disable:one-line max-line-length interface-name comment-format no-bitwise */ enum EntityType { transportBelt = 0, splitter = 1, _splitterLeft = 2, _splitterRight = 3 } enum Direction { top = 0, right = 1, bottom = 2, left = 3 } class MapEntity { /** X-Position */ x: number; /** Y-Position */ y: number; /** Entity-Type */ t: EntityType; /** Direction (0 = top, 1 = right, 2 = bottom, 3 = left) */ d: Direction; constructor(x: number, y: number, t: EntityType, d: Direction) { this.x = x; this.y = y; this.t = t; this.d = d; } /** Top-Neighbor (if exists) */ tn?: MapEntity; /** Right-Neighbor (if exists) */ rn?: MapEntity; /** Bottom-Neighbor (if exists) */ bn?: MapEntity; /** Left-Neighbor (if exists) */ ln?: MapEntity; toTop(): boolean { return this.d === Direction.top; } toRight(): boolean { return this.d === Direction.right; } toBottom(): boolean { return this.d === Direction.bottom; } toLeft(): boolean { return this.d === Direction.left; } fromTop(backCheck?: boolean): boolean { return this.tn !== undefined && (this.tn.toBottom() || backCheck === true && this.tn.toTop() && !this.tn.isCurve()); } fromRight(backCheck?: boolean): boolean { return this.rn !== undefined && (this.rn.toLeft() || backCheck === true && this.rn.toRight() && !this.rn.isCurve()); } fromBottom(backCheck?: boolean): boolean { return this.bn !== undefined && (this.bn.toTop() || backCheck === true && this.bn.toBottom() && !this.bn.isCurve()); } fromLeft(backCheck?: boolean): boolean { return this.ln !== undefined && (this.ln.toRight() || backCheck === true && this.ln.toLeft() && !this.ln.isCurve()); } isCurve(): boolean { if (this.t === EntityType.transportBelt) { switch (this.d) { case Direction.top: return !this.fromBottom() && this.fromLeft() !== this.fromRight(); case Direction.right: return !this.fromLeft() && this.fromTop() !== this.fromBottom(); case Direction.bottom: return !this.fromTop() && this.fromLeft() !== this.fromRight(); case Direction.left: return !this.fromRight() && this.fromTop() !== this.fromBottom(); } } return false; } } interface MapEntityLine extends Array<MapEntity> { /** total count of entities in this line */ count: number; /** X-Position from first entity */ firstX: number; /** X-Position from last enitiy */ lastX: number; } class Map { entityLines: MapEntityLine[] = []; /** line-update: firstX and lastX * @param x X-Position * @param y Y-Position */ private updatFirstLast(x: number, y: number) { const line = this.entityLines[y]; if (!line) return; // line does not exist if (line.firstX === undefined) line.firstX = x; if (line.lastX === undefined) line.lastX = x; if (line[x]) { if (x < line.firstX) line.firstX = x; if (x > line.lastX) line.lastX = x; } else { while (!line[line.firstX]) line.firstX++; while (!line[line.lastX]) line.lastX--; while (line.length > 0 && !line[line.length - 1]) line.length--; } while (this.entityLines.length > 0 && !this.entityLines[this.entityLines.length - 1]) this.entityLines.length--; } /** remove an entity * @param x X-Position * @param y Y-Position */ removeEntity(x: number, y: number): boolean { const line = this.entityLines[y]; if (!line) return false; // line does not exist const entity = line[x]; if (!entity) return false; // entity not found const extraRemoves: { x: number, y: number }[] = []; switch (entity.t) { case EntityType._splitterLeft: { switch (entity.d) { case Direction.top: extraRemoves.push({ x: x + 1, y: y }); break; case Direction.right: extraRemoves.push({ x: x, y: y + 1 }); break; case Direction.bottom: extraRemoves.push({ x: x - 1, y: y }); break; case Direction.left: extraRemoves.push({ x: x, y: y - 1 }); break; } } break; case EntityType._splitterRight: { switch (entity.d) { case Direction.top: extraRemoves.push({ x: x - 1, y: y }); break; case Direction.right: extraRemoves.push({ x: x, y: y - 1 }); break; case Direction.bottom: extraRemoves.push({ x: x + 1, y: y }); break; case Direction.left: extraRemoves.push({ x: x, y: y + 1 }); break; } } break; } if (entity.ln) { delete line[x - 1].rn; delete entity.ln; } // disconnect left if (entity.rn) { delete line[x + 1].ln; delete entity.rn; } // disconnect right if (entity.tn) { delete this.entityLines[y - 1][x].bn; delete entity.tn; } // disconnect top if (entity.bn) { delete this.entityLines[y + 1][x].tn; delete entity.bn; } // disconnect bottom delete line[x]; // remove entity line.count--; if (line.count === 0) delete this.entityLines[y]; // delete entire line if last entity removed this.updatFirstLast(x, y); if (extraRemoves.length > 0) { extraRemoves.forEach(e => { this.removeEntity(e.x, e.y); }); } return true; } /** add or overwrite an entity * @param x X-Position * @param y Y-Position * @param e Entity-Type * @param d Direction */ addEntity(x: number, y: number, e: EntityType, d: Direction) { if (e === EntityType.splitter) { switch (d) { case Direction.top: { this.addEntity(x, y, EntityType._splitterLeft, d); this.addEntity(x + 1, y, EntityType._splitterRight, d); } break; case Direction.right: { this.addEntity(x, y, EntityType._splitterLeft, d); this.addEntity(x, y + 1, EntityType._splitterRight, d); } break; case Direction.bottom: { this.addEntity(x, y, EntityType._splitterRight, d); this.addEntity(x + 1, y, EntityType._splitterLeft, d); } break; case Direction.left: { this.addEntity(x, y, EntityType._splitterRight, d); this.addEntity(x, y + 1, EntityType._splitterLeft, d); } break; } return; } const newEntity = new MapEntity(x, y, e, d); this.removeEntity(x, y); // remove old entity (if exsist) const lineT = this.entityLines[y - 1]; const lineB = this.entityLines[y + 1]; let line = this.entityLines[y]; if (!line) { this.entityLines[y] = line = [] as MapEntityLine; line.count = 0; } line[x] = newEntity; line.count++; if (line[x - 1]) { newEntity.ln = line[x - 1]; line[x - 1].rn = newEntity; } // connect left if (line[x + 1]) { newEntity.rn = line[x + 1]; line[x + 1].ln = newEntity; } // connect right if (lineT && lineT[x]) { newEntity.tn = lineT[x]; lineT[x].bn = newEntity; } // connect top if (lineB && lineB[x]) { newEntity.bn = lineB[x]; lineB[x].tn = newEntity; } // connect bottom this.updatFirstLast(x, y); } /** load a factorio blueprint * @param startX Start-Position X * @param startY Start-Position Y * @param base64 Blueprint-Code */ addBlueprint(startX: number, startY: number, base64: string): boolean { const r = Blueprint.decodeBlueprint(base64); if (r.length === 0) return false; r.forEach(e => { this.addEntity(e.x + startX, e.y + startY, e.t, e.d); }); return true; } /** save a factorio blueprint and return a base64 string * @param label optional Label of the blueprint */ getBlueprint(label = "blueprint"): string { const entities: MapEntity[] = []; for (let y = 0; y < this.entityLines.length; y++) { const line = this.entityLines[y]; if (!line || line.count === 0) continue; for (let x = line.firstX; x <= line.lastX; x++) { const e = line[x]; if (e) { entities.push(new MapEntity(e.x, e.y, e.t, e.d)); // create a new instance of MapEntity } } } return Blueprint.encodeBlueprint(label, entities); } /** get entity * @param x X-Position * @param y Y-Position */ getEntity(x: number, y: number): MapEntity { const line = this.entityLines[y]; if (!line) return undefined; return line[x]; } callEntities(firstX: number, firstY: number, lastX: number, lastY: number, call: (x: number, y: number, e: MapEntity) => void): void { const lines = this.entityLines; if (lastY >= lines.length) lastY = lines.length - 1; for (let y = firstY; y <= lastY; y++) { const line = lines[y]; if (!line) continue; const lx = lastX <= line.lastX ? lastX : line.lastX; for (let x = firstX >= line.firstX ? firstX : line.firstX; x <= lx; x++) { const e = line[x]; if (e) call(x, y, e); } } } }
MaxKlaxxMiner/factorio_belt_simulator
FactorioTransportBeltSimulator/ts/game.ts
<filename>FactorioTransportBeltSimulator/ts/game.ts /* tslint:disable:one-line max-line-length interface-name comment-format no-bitwise */ // --- globals --- const keys: { [key: number]: boolean } = {}; let mouseX = 0; let mouseY = 0; let mouseButtons = 0; let mouseWheel = 0; let game: Game; class Game { map: Map; display: Display; constructor(gameDiv: HTMLElement, canvasWidth: number, canvasHeight: number) { this.map = new Map(); this.display = new Display(gameDiv, canvasWidth, canvasHeight, this.map); const m = this.map; const test = "<KEY>="; m.addBlueprint(1, 1, test); //for (let y = 2; y < 12; y++) //{ // for (let x = 2; x < 22; x++) // { // m.add(x, y, EntityType.transportBelt, Math.random() * 4 >> 0); // //m.add(x, y, EntityType.transportBelt, y & 3); // } //} //m.add(3, 3, EntityType.splitter, Direction.top); } lastWheel = 0; entityDirection: Direction = Direction.right; uiUpdate(): void { if (keys[107]) // numpad + { keys[107] = false; this.display.setScale(this.display.scaleLevel + 1); } if (keys[109]) // numpad - { keys[109] = false; this.display.setScale(this.display.scaleLevel - 1); } if (keys[82]) // R { keys[82] = false; this.display.previewDirection++; if (this.display.previewDirection === 4) this.display.previewDirection = 0; } if (mouseButtons === 1) { const m = this.display.getMouseFieldPos(); this.map.addEntity(m.x, m.y, this.display.previewEntity, this.display.previewDirection); } if (mouseButtons === 2) { const m = this.display.getMouseFieldPos(); this.map.removeEntity(m.x, m.y); } if (this.lastWheel !== mouseWheel) { if (mouseWheel < this.lastWheel) { this.display.setScale(this.display.scaleLevel + 1); } else { this.display.setScale(this.display.scaleLevel - 1); } this.lastWheel = mouseWheel; } } calcTime = 0; calc(): void { let moveDirX = 0; let moveDirY = 0; if (keys[87]) moveDirY++; // W if (keys[65]) moveDirX++; // A if (keys[83]) moveDirY--; // S if (keys[68]) moveDirX--; // D if (moveDirX !== 0 || moveDirY !== 0) { if (moveDirX !== 0 && moveDirY !== 0) // diagonal move? -> reduce speed { moveDirX /= Math.sqrt(2); moveDirY /= Math.sqrt(2); } this.display.offsetX += moveDirX * Math.min(50, Math.max(5, this.display.scale * 0.2)); this.display.offsetY += moveDirY * Math.min(50, Math.max(5, this.display.scale * 0.2)); } this.display.calc(); this.calcTime += 16.6666666; } draw(): void { const time = performance.now(); if (!this.display.draw(time)) return; this.uiUpdate(); if (this.calcTime === 0) this.calcTime = time; if (this.calcTime < time + 30 && this.calcTime > time - 30) this.calc(); // inner sync? else while (this.calcTime < time - 20) this.calc(); // resync } static run(): void { // --- init --- const docSize = getDocumentSize(); const div = document.getElementById("game"); game = new Game(div, docSize.width, docSize.height); // --- key events --- document.body.onkeydown = (e: KeyboardEvent) => { console.log("key pressed: " + e.keyCode); keys[e.keyCode] = true; }; document.body.onkeyup = (e: KeyboardEvent) => { keys[e.keyCode] = false; }; // --- mouse events --- document.addEventListener("contextmenu", event => event.preventDefault()); // disable context menu (right mouse click) function mouseWheelEvent(m: MouseWheelEvent) { console.log(m); if ((<any>m).wheelDelta !== undefined) // IE workaround { if ((<any>m).wheelDelta < 0) mouseWheel++; else mouseWheel--; return; } if (typeof m.deltaY === "number") { if (m.deltaY > 0) mouseWheel++; else mouseWheel--; // generic } else { if (m.detail > 0) mouseWheel++; else mouseWheel--; // firefox workaround } } if ("onmousewheel" in window) { window.onmousewheel = mouseWheelEvent; } else // Firefox fallback { document.addEventListener("DOMMouseScroll", mouseWheelEvent, false); } const mouseEvent = (m: MouseEvent) => { mouseX = m.x; mouseY = m.y; mouseButtons = m.buttons; }; div.onmousedown = mouseEvent; div.onmousemove = mouseEvent; div.onmouseup = mouseEvent; // --- run game-loop -- //window.setInterval(() => game.draw(), 8); // 125 FPS test const run = () => { requestAnimFrame(run); game.draw(); }; run(); // vsync } }
MaxKlaxxMiner/factorio_belt_simulator
FactorioTransportBeltSimulator/ts/blueprint.ts
/* tslint:disable:one-line max-line-length interface-name comment-format no-bitwise */ interface BluePrintIcon { signal: { type: string, name: string }, index: number; } interface BluePrintEntity { entity_number: number, name: string, position: { x: number, y: number }, /** values: undefined = top, 2 = right, 4 = bottom, 6 = left */ direction?: 2 | 4 | 6; } interface BluePrint { blueprint: { icons: BluePrintIcon[], entities: BluePrintEntity[], item: "blueprint", label: string, version: 281474976710656; }; } class Blueprint { static decodeBlueprint(base64: string): MapEntity[] { const result: MapEntity[] = []; try { if (base64[0] !== "0") return result; const blueprint = JSON.parse(pako.inflate(atob(base64.substr(1)), { to: "string" }).toString()) as BluePrint; console.log(blueprint); const entities = blueprint.blueprint.entities; let minX = 1000000; let minY = 1000000; entities.forEach(e => { if (e.position.x < minX) minX = e.position.x; if (e.position.y < minY) minY = e.position.y; }); entities.forEach(e => { const x = (e.position.x - minX + .01) >> 0; const y = (e.position.y - minY + .01) >> 0; const d = e.direction === 2 ? Direction.right : e.direction === 6 ? Direction.left : e.direction === 4 ? Direction.bottom : Direction.top; switch (e.name) { case "transport-belt": result.push(new MapEntity(x, y, EntityType.transportBelt, d)); break; case "splitter": result.push(new MapEntity(x, y, EntityType.splitter, d)); break; } }); } catch (exc) { } return result; } static encodeBlueprint(label: string, entities: MapEntity[]): string { const result: BluePrint = { blueprint: { icons: [], entities: [], label: label, item: "blueprint", version: 281474976710656 } }; let count = 0; entities.forEach(e => { let next: BluePrintEntity; const dir = e.d === Direction.right ? 2 : e.d === Direction.bottom ? 4 : e.d === Direction.left ? 6 : 0; switch (e.t) { case EntityType.transportBelt: { next = { entity_number: ++count, name: "transport-belt", position: { x: e.x + 0.5, y: e.y + 0.5 } }; if (dir === 2 || dir === 4 || dir === 6) next.direction = dir; } break; case EntityType._splitterLeft: { next = { entity_number: ++count, name: "splitter", position: { x: e.x, y: e.y } }; switch (e.d) { case Direction.top: next.position.x += 0.5; break; case Direction.right: next.position.y += 0.5; next.direction = 2; break; case Direction.bottom: next.position.x -= 0.5; next.direction = 4; break; case Direction.left: next.position.y -= 0.5; next.direction = 6; break; } } break; } if (next) result.blueprint.entities.push(next); }); return "0" + btoa(pako.deflate(JSON.stringify(result), { to: "string" }).toString()); } }
ksurendra/jaqstack
core/ui.resources/src/app/hello/hello.component.ts
import { Component, OnInit } from '@angular/core'; import {HelloService} from "./hello.service"; @Component({ selector: 'app-hello', templateUrl: './hello.component.html', styleUrls: ['./hello.component.css'], providers: [HelloService] }) export class HelloComponent implements OnInit { helloFromJava : any; public jsonObject: any; constructor(private helloService : HelloService) { } ngOnInit() { this.getHelloFromJava(); } getHelloFromJava() : void { console.log("....getHelloFromJava!"); this.helloFromJava = this.helloService.getHelloWorldFromJava() .subscribe(resp => { console.log(resp); this.helloFromJava = JSON.stringify(resp); }); } }
ksurendra/jaqstack
examples/azureblobviewer/ui.resources/src/app/azureblobviewer/azureblobviewer.component.ts
<reponame>ksurendra/jaqstack import { Component, ElementRef, ViewChild, OnInit } from '@angular/core'; import {AzureblobService} from "../services/azureblob.service"; import { DomSanitizer, SafeUrl } from "@angular/platform-browser"; @Component({ selector: 'app-azureblobviewer', templateUrl: './azureblobviewer.component.html', styleUrls: ['./azureblobviewer.component.css'], providers: [ AzureblobService] }) export class AzureBlobViewerComponent implements OnInit { blobsList : any; imageBlobUrl: string | null = null; sanitizedImageBlobUrl: SafeUrl | null = null; constructor(private azureblobService : AzureblobService, private sanitizer: DomSanitizer) { } ngOnInit() { this.getAllBlobs(); this. getThumbnail(); } getAllBlobs() : void { this.azureblobService.getAllBlobs() .subscribe( (val) => { this.blobsList = val; //<====== Set value here }, response => { console.log("POST - getAllBlobs in error", response); }, () => { console.log("POST - getAllBlobs is now completed."); }); } getThumbnail() : void { this.azureblobService.getBlobThumbnail() .subscribe( (val) => { console.log("POST - getThumbnail- successful value returned in body", val); //this.turl = val; //<====== Set value here this.createImageFromBlob(val); }, response => { console.log("POST - getThumbnail - in error", response); }, () => { console.log("POST - getThumbnail - observable is now completed."); }); } createImageFromBlob(image: Blob) { console.log("Call createImageFromBlob()", image); let reader = new FileReader(); reader.addEventListener("load", () => { this.imageBlobUrl = reader.result; }, false); if (image) { reader.readAsDataURL(image); } } }
ksurendra/jaqstack
examples/azureblobviewer/ui.resources/src/app/services/azureblob.service.ts
import { Injectable } from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import { Azureblob } from '../models/azureblob'; import {environment} from "../../environments/environment"; import {Observable} from 'rxjs/Observable'; @Injectable() export class AzureblobService { constructor(private httpClient: HttpClient) { } serverUrl : string = environment.BACKEND_URL + "/service/blobservice/azure/fetch"; thumbnailFetchUrl : string = "https://southcentralus.api.cognitive.microsoft.com/vision/v2.0/generateThumbnail?width=100&height=100&smartCropp"; value: any; getAllBlobs() { console.log("....AzureblobService.getAllBlobs()"); const headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Accept' : 'application/json' }); return this.httpClient.post<Azureblob[]>(this.serverUrl, JSON.stringify({ "azureAcountName": "acsazurestore", "azureAcountKey": "<KEY> "azureContainer":"acsazurecontainer" }),{headers: headers}); } getBlobThumbnail(): Observable<Blob> { console.log("....AzureblobService.getBlobThumbnail()"); const headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json', 'Ocp-Apim-Subscription-Key': 'f78fdd51de304d99862c4a50c9a0ec0c' }); return this.httpClient.post<Blob>(this.thumbnailFetchUrl, { "url": "http://acsazurestore.blob.core.windows.net/acsazurecontainer/Git-Logo-1788C.png" }, {headers: headers, responseType: 'blob' as 'json' }); } }
ksurendra/jaqstack
examples/azureblobviewer/ui.resources/src/environments/environment.prod.ts
export const environment = { production: true, BACKEND_URL : window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + "/jaqstack-azure-blobviewer" };
ksurendra/jaqstack
core/ui.resources/src/app/hello/hello.service.ts
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import 'rxjs/add/operator/map'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import {environment} from '../../environments/environment'; @Injectable() export class HelloService { serverUrl : string = environment.BACKEND_URL + "/service/dbservice/product"; constructor(private http: HttpClient) { } getHelloWorldFromService() : string { return "hello world from the service"; } getHelloWorldFromJava() { return this.http.get(this.serverUrl); } }
ksurendra/jaqstack
core/ui.resources/src/app/app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; import { RouterModule } from '@angular/router'; import { HelloComponent } from './hello/hello.component'; import { Component2Component } from './component2/component2.component'; @NgModule({ imports: [ HttpClientModule, BrowserModule ], declarations: [ AppComponent, HelloComponent, Component2Component ], bootstrap: [ AppComponent ] }) export class AppModule { }
ksurendra/jaqstack
examples/azureblobviewer/ui.resources/src/app/app.component.ts
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html' //template: `<h1>Hello Test Angular - {{name}}</h1>` }) /*export class AppComponent implements OnInit { name = 'This Message is from Test Angular index.html calling app.component.ts '; title = 'Angular App Title'; //public title : String = 'Loading title...'; //public content : String = 'Loading content...'; constructor(private httpClient: HttpClient) { } ngOnInit() { } }*/ export class AppComponent { //title = 'Azure BlobViewer Application - Sample Title'; }
ksurendra/jaqstack
examples/azureblobviewer/ui.resources/src/app/models/azureblob.ts
export class Azureblob { blobName: string; blobURL: string; blboMimeType: string; }
ksurendra/jaqstack
examples/azureblobviewer/ui.resources/src/app/models/azurethumbnail.ts
<reponame>ksurendra/jaqstack<filename>examples/azureblobviewer/ui.resources/src/app/models/azurethumbnail.ts export class Azurethumbnail { thumbnailurl: Blob; }
ksurendra/jaqstack
examples/azureblobviewer/ui.resources/src/app/app.module.ts
<filename>examples/azureblobviewer/ui.resources/src/app/app.module.ts<gh_stars>0 import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; import { RouterModule } from '@angular/router'; import { AzureBlobViewerComponent } from './azureblobviewer/azureblobviewer.component'; import {KeysPipe} from './helpers/azureblob.pipe'; @NgModule({ imports: [ HttpClientModule, BrowserModule ], declarations: [ AppComponent, AzureBlobViewerComponent, KeysPipe ], bootstrap: [ AppComponent ] }) export class AppModule { }
sudhakarbhra/bm
src/app/shared/services/vendors.service.ts
<filename>src/app/shared/services/vendors.service.ts import { Injectable } from '@angular/core'; import { HelperService } from './helper.service'; @Injectable({ providedIn: 'root' }) export class VendorsService { constructor(private hs: HelperService) {} findAllVendors(){ return this.hs.get('/bm/v1/admin/find/vendors'); } findAllVendorsWithStatus(){ return this.hs.get('/bm/v1/admin/find/vendors/'+ status); } }
sudhakarbhra/bm
src/app/shared/services/auth.service.ts
<filename>src/app/shared/services/auth.service.ts<gh_stars>0 import { Injectable } from '@angular/core'; import { HelperService } from './helper.service'; @Injectable({ providedIn: 'root' }) export class AuthService { constructor(private hs: HelperService) { } authenticateUser(payload){ return this.hs.post('role', payload); } }
sudhakarbhra/bm
src/app/shared/models/helper.ts
<filename>src/app/shared/models/helper.ts export interface Helper { name: String }
sudhakarbhra/bm
src/app/layout/layout.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { MatButtonModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatSidenavModule, MatToolbarModule } from '@angular/material'; import { MatTableModule } from '@angular/material/table'; import { TranslateModule } from '@ngx-translate/core'; import { SidebarComponent } from './components/sidebar/sidebar.component'; import { TopnavComponent } from './components/topnav/topnav.component'; import { LayoutRoutingModule } from './layout-routing.module'; import { LayoutComponent } from './layout.component'; import { NavComponent } from './nav/nav.component'; import { Screen2Component } from './screen2/screen2.component'; import { UsersComponent } from './users/users.component'; import { ProductsComponent } from './products/products.component'; import { VendorsComponent } from './vendors/vendors.component'; import { ReportsComponent } from './reports/reports.component'; import { ProfileComponent } from './profile/profile.component'; @NgModule({ imports: [ CommonModule, LayoutRoutingModule, MatToolbarModule, MatButtonModule, MatSidenavModule, MatIconModule, MatInputModule, MatMenuModule, MatListModule, TranslateModule, MatTableModule ], declarations: [Screen2Component, LayoutComponent, NavComponent, TopnavComponent, SidebarComponent, UsersComponent, ProductsComponent, VendorsComponent, ReportsComponent, ProfileComponent, ] }) export class LayoutModule { }
sudhakarbhra/bm
src/app/shared/services/products.service.ts
import { Injectable } from '@angular/core'; import { HelperService } from './helper.service'; @Injectable({ providedIn: 'root' }) export class ProductsService { constructor(private hs: HelperService) { } productUpload(payload){ return this.hs.post('/bm/v1/product/upload', payload); } }
sudhakarbhra/bm
src/app/shared/services/users.service.ts
import { Injectable } from '@angular/core'; import { HelperService } from './helper.service'; @Injectable({ providedIn: 'root' }) export class UsersService { constructor(private hs: HelperService) { } findAllRoles(){ return this.hs.get('/bm/v1/role/findall'); } findAllCustomers(){ return this.hs.get('/bm/v1/admin/find/customers'); } findAllUsers(){ return this.hs.get('/bm/v1/admin/find/all'); } findAllAdminUsersWithStatus(status){ return this.hs.get('/bm/v1/admin/find/admins/' + status); } findAllAdminUsers(){ return this.hs.get('/bm/v1/admin/find/admins'); } findUserByMobile(mobile){ return this.hs.get('/bm/v1/admin/user/'+ mobile); } getUserDetailsUnderAdminUser(mobile){ return this.hs.get('/bm/v1/admin/users/referral/'+ mobile); } createCustomer(payload){ return this.hs.post('/bm/v1/customer/s1', payload); } updateCustomer(r_id, payload){ return this.hs.put('/bm/v1/customer/s1/'+ r_id, payload); } createExecutive(payload){ return this.hs.post('/bm/v1/executive/s1', payload); } updateExecutive(r_id, payload){ return this.hs.put('/bm/v1/executive/s1/'+ r_id, payload); } createVendor(payload){ return this.hs.post('/bm/v1/vendor/s1', payload); } updateVendor(r_id, payload){ return this.hs.put('/bm/v1/vendor/s1'+ r_id, payload); } }
sudhakarbhra/bm
src/app/shared/services/helper.service.ts
<reponame>sudhakarbhra/bm import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class HelperService { BASE_URI = "http://172.16.31.10:8089/"; constructor(private http: HttpClient) { } get(endpoint: string): Observable<any> { return this.http.get(this.BASE_URI + endpoint); } post(endpoint: string, body): Observable<any> { return this.http.post(this.BASE_URI + endpoint, body); } put(endpoint: string, body): Observable<any> { return this.http.put(this.BASE_URI + endpoint, body); } delete(endpoint: string): Observable<any> { return this.http.delete(this.BASE_URI + endpoint); } generateOTP(mobile){ // return this.http.post('/bm/v1/otp/'+mobile, '**'); } findAllVendorsService(){ return this.http.get(this.BASE_URI + '/bm/v1/admin/find/vendors'); } }
sudhakarbhra/bm
src/app/shared/services/index.ts
import { Injectable } from '@angular/core'; import {HttpClient} from '@angular/common/http'; @Injectable({providedIn: 'root'}) export class HelperService { url = "http://dummy.restapiexample.com/api/v1"; constructor(private http: HttpClient) { } getEmployee() { return this.http.get(this.url+'/employees') } }
sudhakarbhra/bm
src/app/shared/services/role.service.ts
<reponame>sudhakarbhra/bm import { Injectable } from '@angular/core'; import { HelperService } from './helper.service'; @Injectable({ providedIn: 'root' }) export class RoleService { constructor() { } }
sudhakarbhra/bm
src/app/layout/products/products.component.ts
<gh_stars>0 import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { HelperService } from '../../shared/services/helper.service'; import { Helper } from '../../shared/models/helper'; import { MatTableDataSource } from '@angular/material'; const ELEMENT_DATA: Helper[] = [ { name: 'Hydrogen', }, { name: 'Helium', }, { name: 'Lithium', }, { name: 'Beryllium', }, { name: 'Boron', }, { name: 'Carbon', }, { name: 'Nitrogen', } ]; @Component({ selector: 'app-products', templateUrl: './products.component.html', styleUrls: ['./products.component.scss'] }) export class ProductsComponent implements OnInit { displayedColumns: string[] = ['name']; dataSource = new MatTableDataSource(ELEMENT_DATA); constructor(public http: HttpClient, private helperService: HelperService) { } findAllVendors() { this.helperService.findAllVendorsService().subscribe((data : Helper[]) => { console.log(data); }) } ngOnInit() { this.findAllVendors(); } }
adinvadim/vuex-orm-next
test/feature/relations/has_many_save.spec.ts
<reponame>adinvadim/vuex-orm-next import { createStore, fillState, assertState } from 'test/Helpers' import { Model, Num, Str, HasMany } from '@/index' describe('feature/relations/has_many_save', () => { class User extends Model { static entity = 'users' @Num(0) id!: number @Str('') name!: string @HasMany(() => Post, 'userId') posts!: Post[] } class Post extends Model { static entity = 'posts' @Num(0) id!: number @Num(0) userId!: number @Str('') title!: string } it('saves a model to the store with "has many" relation', () => { const store = createStore() fillState(store, { users: {}, posts: { 1: { id: 1, userId: 1, title: 'Title 01' } } }) store.$repo(User).save({ id: 1, name: '<NAME>', posts: [ { id: 1, userId: 1, title: 100 }, { id: 2, userId: 1, title: 200 } ] }) assertState(store, { users: { 1: { id: 1, name: '<NAME>' } }, posts: { 1: { id: 1, userId: 1, title: '100' }, 2: { id: 2, userId: 1, title: '200' } } }) }) it('generates missing foreign key', async () => { const store = createStore() await store.$repo(User).save({ id: 1, name: '<NAME>', posts: [ { id: 1, title: 'Title 01' }, { id: 2, title: 'Title 02' } ] }) assertState(store, { users: { 1: { id: 1, name: '<NAME>' } }, posts: { 1: { id: 1, userId: 1, title: 'Title 01' }, 2: { id: 2, userId: 1, title: 'Title 02' } } }) }) it('can insert a record with missing relational key', async () => { const store = createStore() await store.$repo(User).save({ id: 1, name: '<NAME>' }) assertState(store, { users: { 1: { id: 1, name: '<NAME>' } }, posts: {} }) }) it('returns normalized schema when saving a model', () => { const store = createStore() const schema = store.$repo(User).save({ id: 1, name: '<NAME>', posts: [ { id: 1, userId: 1, title: 'Title 01' }, { id: 2, userId: 1, title: 'Title 02' } ] }) expect(schema).toEqual({ __id: '1', id: 1, name: '<NAME>', posts: [ { __id: '1', id: 1, userId: 1, title: 'Title 01' }, { __id: '2', id: 2, userId: 1, title: 'Title 02' } ] }) }) })
adinvadim/vuex-orm-next
test/feature/relations/has_many_insert_uid.spec.ts
<gh_stars>0 import { createStore, assertState, mockUid } from 'test/Helpers' import { Model, Attr, Uid, Str, HasMany } from '@/index' describe('feature/relations/has_many_insert_uid', () => { beforeEach(() => { Model.clearRegistries() }) it('inserts "has many" relation with parent having "uid" field as the primary key', async () => { class User extends Model { static entity = 'users' @Uid() id!: string @Str('') name!: string @HasMany(() => Post, 'userId') posts!: Post[] } class Post extends Model { static entity = 'posts' @Attr() id!: number @Attr() userId!: number @Str('') title!: string } mockUid(['uid1']) const store = createStore() await store.$repo(User).insert({ name: '<NAME>', posts: [ { id: 1, title: 'Title 01' }, { id: 2, title: 'Title 02' } ] }) assertState(store, { users: { uid1: { id: 'uid1', name: '<NAME>' } }, posts: { 1: { id: 1, userId: 'uid1', title: 'Title 01' }, 2: { id: 2, userId: 'uid1', title: 'Title 02' } } }) }) it('inserts "has many" relation with child having "uid" as the foreign key', async () => { class User extends Model { static entity = 'users' @Uid() id!: string @Str('') name!: string @HasMany(() => Post, 'userId') posts!: Post[] } class Post extends Model { static entity = 'posts' @Attr() id!: number @Uid() userId!: string @Str('') title!: string } mockUid(['uid1', 'uid2', 'uid3']) const store = createStore() await store.$repo(User).insert({ name: '<NAME>', posts: [ { id: 1, title: 'Title 01' }, { id: 2, title: 'Title 02' } ] }) assertState(store, { users: { uid1: { id: 'uid1', name: '<NAME>' } }, posts: { 1: { id: 1, userId: 'uid1', title: 'Title 01' }, 2: { id: 2, userId: 'uid1', title: 'Title 02' } } }) }) })
adinvadim/vuex-orm-next
src/connection/Connection.ts
<reponame>adinvadim/vuex-orm-next import { Store } from 'vuex' import { Element, Elements } from '../data/Data' import { Database } from '../database/Database' import { Model } from '../model/Model' export interface ConnectionNamespace { connection: string entity: string } export class Connection<M extends Model> { /** * The store instance. */ store: Store<any> /** * The connection name. */ connection: string /** * The entity name. */ model: M /** * Create a new connection instance. */ constructor(database: Database, model: M) { this.store = database.store this.connection = database.connection this.model = model } /** * Commit a namespaced store mutation. */ private commit(name: string, payload?: any): void { const type = `${this.connection}/${this.model.$entity()}/${name}` this.store.commit(type, payload) } /** * Get all existing records. */ get(): Elements { return this.store.state[this.connection][this.model.$entity()].data } /** * Find a model by its index id. */ find(id: string): Element | null { return this.get()[id] ?? null } /** * Commit `save` mutation to the store. */ save(records: Elements): void { const newRecords = {} as Elements const data = this.get() for (const id in records) { const record = records[id] const existing = data[id] newRecords[id] = existing ? Object.assign({}, existing, this.model.$sanitize(record)) : this.model.$sanitizeAndFill(record) } this.commit('save', newRecords) } /** * Commit `insert` mutation to the store. */ insert(records: Elements): void { this.commit('insert', records) } /** * Commit `fresh` mutation to the store. */ fresh(records: Elements): void { this.commit('fresh', records) } /** * Commit `update` mutation to the store. */ update(records: Elements): void { this.commit('update', records) } /** * Commit `delete` mutation to the store. */ delete(ids: string[]): void { this.commit('delete', ids) } /** * Commit `flush` mutation to the store. */ flush(): void { this.commit('flush') } }
adinvadim/vuex-orm-next
test/feature/relations/belongs_to_retrieve.spec.ts
import { createStore, fillState, assertModel } from 'test/Helpers' import { Model, Attr, Str, BelongsTo } from '@/index' describe('feature/relations/belongs_to_retrieve', () => { class User extends Model { static entity = 'users' @Attr() id!: number @Str('') name!: string } class Post extends Model { static entity = 'posts' @Attr() id!: number @Attr() userId!: number | null @Str('') title!: string @BelongsTo(() => User, 'userId') author!: User | null } it('can eager load belongs to relation', async () => { const store = createStore() fillState(store, { users: { 1: { id: 1, name: '<NAME>' } }, posts: { 1: { id: 1, userId: 1, title: 'Title 01' } } }) const post = store.$repo(Post).with('author').first()! expect(post).toBeInstanceOf(Post) expect(post.author).toBeInstanceOf(User) assertModel(post, { id: 1, userId: 1, title: 'Title 01', author: { id: 1, name: '<NAME>' } }) }) it('can eager load missing relation as `null`', async () => { const store = createStore() fillState(store, { users: {}, posts: { 1: { id: 1, userId: 1, title: 'Title 01' } } }) const post = store.$repo(Post).with('author').first()! expect(post).toBeInstanceOf(Post) assertModel(post, { id: 1, userId: 1, title: 'Title 01', author: null }) }) it('ignores the relation with the empty foreign key', async () => { const store = createStore() fillState(store, { users: { 1: { id: 1, name: '<NAME>' } }, posts: { 1: { id: 1, userId: null, title: 'Title 01' } } }) const post = store.$repo(Post).with('author').first()! expect(post).toBeInstanceOf(Post) assertModel(post, { id: 1, userId: null, title: 'Title 01', author: null }) }) })
adinvadim/vuex-orm-next
src/schema/Schema.ts
import { schema as Normalizr, Schema as NormalizrSchema } from 'normalizr' import { isNullish, isArray } from '../support/Utils' import { Uid } from '../model/attributes/types/Uid' import { Relation } from '../model/attributes/relations/Relation' import { Model } from '../model/Model' export class Schema { /** * The list of generated schemas. */ private schemas: Record<string, Normalizr.Entity> = {} /** * The model instance. */ private model: Model /** * Create a new Schema instance. */ constructor(model: Model) { this.model = model } /** * Create a single schema. */ one(model?: Model, parent?: Model): Normalizr.Entity { model = model || this.model parent = parent || this.model const entity = `${model.$entity()}${parent.$entity()}` if (this.schemas[entity]) { return this.schemas[entity] } const schema = this.newEntity(model, parent) this.schemas[entity] = schema const definition = this.definition(model) schema.define(definition) return schema } /** * Create an array schema for the given model. */ many(model: Model, parent?: Model): Normalizr.Array { return new Normalizr.Array(this.one(model, parent)) } /** * Create a new normalizr entity. */ private newEntity(model: Model, parent: Model): Normalizr.Entity { const entity = model.$entity() const idAttribute = this.idAttribute(model, parent) return new Normalizr.Entity(entity, {}, { idAttribute }) } /** * The `id` attribute option for the normalizr entity. * * Generates any missing primary keys declared by a Uid attribute. Missing * primary keys where the designated attributes do not exist will * throw an error. * * Note that this will only generate uids for primary key attributes since it * is required to generate the "index id" while the other attributes are not. * * It's especially important when attempting to "update" records since we'll * want to retain the missing attributes in-place to prevent them being * overridden by newly generated uid values. * * If uid primary keys are omitted, when invoking the "update" method, it will * fail because the uid values will never exist in the store. * * While it would be nice to throw an error in such a case, instead of * silently failing an update, we don't have a way to detect whether users * are trying to "update" records or "inserting" new records at this stage. * Something to consider for future revisions. */ private idAttribute( model: Model, parent: Model ): Normalizr.StrategyFunction<string> { // We'll first check if the model contains any uid attributes. If so, we // generate the uids during the normalization process, so we'll keep that // check result here. This way, we can use this result while processing each // record, instead of looping through the model fields each time. const uidFields = this.getUidPrimaryKeyPairs(model) return (record, parentRecord, key) => { // If the `key` is not `null`, that means this record is a nested // relationship of the parent model. In this case, we'll attach any // missing foreign keys to the record first. if (key !== null) { ;(parent.$fields()[key] as Relation).attach(parentRecord, record) } // Next, we'll generate any missing primary key fields defined as // uid field. for (const key in uidFields) { if (isNullish(record[key])) { record[key] = uidFields[key].make(record[key]) } } // Finally, obtain the index id, attach it to the current record at the // special `__id` key. The `__id` key is used when we try to retrieve // the models via the `revive` method using the data that is currently // being normalized. const id = model.$getIndexId(record) record.__id = id return id } } /** * Get all primary keys defined by the Uid attribute for the given model. */ private getUidPrimaryKeyPairs(model: Model): Record<string, Uid> { const fields = model.$fields() const key = model.$getKeyName() const keys = isArray(key) ? key : [key] const attributes = {} as Record<string, Uid> keys.forEach((k) => { const attr = fields[k] if (attr instanceof Uid) { attributes[k] = attr } }) return attributes } /** * Create a definition for the given model. */ private definition(model: Model): NormalizrSchema { const fields = model.$fields() const definition: NormalizrSchema = {} for (const key in fields) { const field = fields[key] if (field instanceof Relation) { definition[key] = field.define(this) } } return definition } }
adinvadim/vuex-orm-next
test/feature/relations/has_many_by_insert_custom_key.spec.ts
import { createStore, assertState } from 'test/Helpers' import { Model, Attr, Str, HasManyBy } from '@/index' describe('feature/relations/has_many_by_insert_custom_key', () => { beforeEach(() => { Model.clearRegistries() }) it('inserts "has many by" relation with custom primary key', async () => { class Node extends Model { static entity = 'nodes' @Attr() id!: number @Str('') name!: string } class Cluster extends Model { static entity = 'clusters' static primaryKey = 'clusterId' @Attr() clusterId!: number @Attr() nodeIds!: number[] @Str('') name!: string @HasManyBy(() => Node, 'nodeIds') nodes!: Node[] } const store = createStore() await store.$repo(Cluster).insert({ clusterId: 1, name: 'Cluster 01', nodes: [ { id: 1, name: 'Node 01' }, { id: 2, name: 'Node 02' } ] }) assertState(store, { nodes: { 1: { id: 1, name: 'Node 01' }, 2: { id: 2, name: 'Node 02' } }, clusters: { 1: { clusterId: 1, nodeIds: [1, 2], name: 'Cluster 01' } } }) }) it('inserts "has many by" relation with custom owner key', async () => { class Node extends Model { static entity = 'nodes' @Attr() id!: number @Attr() nodeId!: number @Str('') name!: string } class Cluster extends Model { static entity = 'clusters' @Attr() id!: number @Attr() nodeIds!: number[] @Str('') name!: string @HasManyBy(() => Node, 'nodeIds', 'nodeId') nodes!: Node[] } const store = createStore() await store.$repo(Cluster).insert({ id: 1, name: 'Cluster 01', nodes: [ { id: 1, nodeId: 1, name: 'Node 01' }, { id: 2, nodeId: 2, name: 'Node 02' } ] }) assertState(store, { nodes: { 1: { id: 1, nodeId: 1, name: 'Node 01' }, 2: { id: 2, nodeId: 2, name: 'Node 02' } }, clusters: { 1: { id: 1, nodeIds: [1, 2], name: 'Cluster 01' } } }) }) })