0," import {checkAvifFeature} from ""./check-avif-feature.js""; import {checkWebpFeature} from ""./check-webp-feature.js""; type FormatType = ""avif"" | ""webp"" | null; const promisesPool: ((value: FormatType) => void)[] = []; const resolvePromises = (format: FormatType): void => { promisesPool.forEach((resolve) => resolve(format)); }; const checkFormats = async (): Promise => { const isAvif = await checkAvifFeature(); if (isAvif) { resolvePromises(""avif""); return; } const [MASK] = await checkWebpFeature(); if ( [MASK] ) { resolvePromises(""webp""); return; } resolvePromises(null); }; export const getFormatFeatures = (): Promise => { if (promisesPool.length === 0) { checkFormats(); } return new Promise((resolve) => { promisesPool.push(resolve); }); }; ",isWebp 1,"import * as v from 'valibot' type Message< Type extends string, Payload extends object | undefined = undefined, > = Payload extends object ? { type: Type } & Payload : { type: Type } export type MessageToHostApp = | Message<'request-auth-token'> | Message<'request-query-params'> | Message<'set-query-params', { queryParams: Record }> const messageFromHostApp = v.union([ v.object({ type: v.literal('theme'), theme: v.picklist(['light', 'dark']), }), v.object({ type: v.literal('set-auth-token'), authToken: v.string(), }), v.object({ type: v.literal('remove-auth-token'), }), v.object({ type: v.literal('query-params-updated'), queryParams: v.record(v.string(), v.string()), }), ]) export type MessageFromHostApp = v.InferInput export function useHostAppMessaging() { function onHostAppMessage( type: MessageType, callback: (message: Extract) => void, ): void { useEventListener('message', async ( [MASK] ) => { const { hostAppOrigin } = await resolveConfig() if ( [MASK] .origin !== hostAppOrigin) { return } const result = v.safeParse(messageFromHostApp, [MASK] .data) if (!result.success || result.output.type !== type) { return } callback(result.output as Extract) }) } async function notifyHostApp(message: MessageToHostApp): Promise { const { hostAppOrigin } = await resolveConfig() globalThis.window.parent.postMessage(message, hostAppOrigin) } return { onHostAppMessage, notifyHostApp, } } ",event 2,"import * as yargs from 'yargs'; export class CliApp { private args: yargs.Argv; constructor() { this.init(); } public init(): void { // Init as described in: https://github.com/yargs/yargs/blob/master/docs/advanced.md#using-the-non-singleton-interface this.args = yargs((process.argv.slice(2))) .command('download heartrate [enddate]', 'the serve command', (args: yargs.Argv) => { return yargs.option('samples', { default: 50000, type: 'number', description: 'The number of samples for heartrate to download' }).option('enddate', { demand: false, type: 'string', description: 'A date formated like 2019-10-12' }).option('startdate', { demand: true, type: 'string', description: 'A date formated like 2019-10-12' }); }, (argv) => { const [MASK] : RegExp = /^([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))$/; if (! [MASK] .test(argv.startdate)) { throw new Error(""The provided startDate does not seem valid""); } if (argv.enddate) { if (! [MASK] .test(argv.enddate)) { throw new Error(""The provided endDate does not seem valid""); } if (argv.startdate.localeCompare(argv.enddate) >= 0) { throw new Error(""Enddate must be after startdate""); } } }) .option('password', { 'string': true, demand: true, description: 'The password you use to login to flow.polar.com' }) .option('email', { 'string': true, demand: true, description: 'The email you use to login to flow.polar.com' }) .demandOption(['email', 'password'], 'Please provide both run and path arguments to work with this tool') .help(); } public start(): void { } }",dateRegex 3,"import { u128, VM, Context as VMContext } from ""near-sdk-as""; import { name, symbol, decimals, totalSupply, initialize, balanceOf, transfer, allowance, approve, transferFrom } from ""../erc20""; import { getNewestTransferEvent, getNewestApprovalEvent } from ""../events"" // accounts const zero = ""0x0""; // the ""zero-account"" as specified by ERC-20 const contract = ""example-token""; // initialized with totalSupply() const alice = ""alice""; // valid account const bob = ""bob""; // valid account const carol = ""carol""; // valid account const derek = ""derek""; // invalid account // token metadata const _name = "" Token""; const _symbol = ""SWT""; const _decimals: u8 = 2; const _supply = 100_000_000; // wallet sizes const small = u128.from(111) const medium = u128.from(222) const large = u128.from(333) function logs(): string[] { return VM.outcome().logs; } describe(""ERC-20 Token (optional)"", () => { beforeAll(() => { VMContext.setCurrent_account_id(contract); VMContext.setSigner_account_id(contract); }) it(""should have a name"", () => { expect(name()).toBe(_name) }) it(""should have a symbol"", () => { expect(symbol()).toBe(_symbol) }) it(""should have decimals"", () => { expect(decimals()).toBe(_decimals) }) }) describe(""ERC-20 Token (startup)"", () => { it(""should respond to totalSupply()"", () => { expect(totalSupply()).toBe(u128.from(_supply)) }) it(""should initially assign entire token supply to a single account"", () => { // after successful initialization VMContext.setCurrent_account_id(contract); VMContext.setSigner_account_id(contract); expect(initialize()).toBeTruthy(); // the balance of the initial owner should match the total supply expect(balanceOf(contract)).toBe(totalSupply()) }) it(""should record an initial transfer event"", () => { // and event lots should include a record of the TransferEvent // log(logs()) // log(getNewestTransferEvent()) const event = getNewestTransferEvent(); expect(event.spender).toBe(zero); expect(event.from).toBe(zero); expect(event.to).toBe(contract); expect(event.value).toBe(totalSupply()); }) }) describe(""ERC-20 Token (steady state) "", () => { beforeEach(() => { // prepare the reset balances after each test VM.saveState() // prepare to send a transaction as if coming from the contract account VMContext.setCurrent_account_id(contract); VMContext.setSigner_account_id(contract); initialize() // spread the wealth around transfer(alice, small) transfer(bob, medium) transfer(carol, large) // derek gets no love here }) afterEach(() => { VM.restoreState() // reset balances after each test // log(logs()) }) describe(""Transfers"", () => { it(""should allow transfers between accounts"", () => { // record starting balances const aliceStart = balanceOf(alice); const bobStart = balanceOf(bob); // assume alice signs a transfer transaction VMContext.setSigner_account_id(alice); // alice transfers amount to bob const amount = u128.from(10); transfer(bob, amount); // respective balances should reflect the change expect(balanceOf(alice)).toBe(u128.sub(aliceStart, amount)); expect(balanceOf(bob)).toBe(u128.add(bobStart, amount)); // test that a transfer event was recorded // log(getNewestTransferEvent()) const event = getNewestTransferEvent(); expect(event.spender).toBe(alice); expect(event.from).toBe(alice); expect(event.to).toBe(bob); expect(event.value).toBe(amount); }) throws(""should not allow transfers if balance is too low"", () => { // assume alice signs a transfer transaction VMContext.setSigner_account_id(alice); // alice transfers amt to bob let amount = u128.from(10); transfer(bob, amount); // assume bob signs a transfer transaction VMContext.setSigner_account_id(bob); // record starting balances const bobStartBalance = balanceOf(bob); // bob attempts to transfer amount to carol but fails amount = u128.from(999); transfer(carol, amount); // expect this line to throw an exception }) throws(""should not allow transfers from unfunded accounts"", () => { // assume derek signs a transfer transaction VMContext.setSigner_account_id(derek); // derek attempts to transfer amount to alice even though he has no tokens const amount = u128.from(1); transfer(alice, amount) }) }) describe(""Transfer Delegation "", () => { it(""should gracefully default to zero allowance"", () => { expect(allowance(alice, bob)).toBe(u128.Zero); }) it(""should support approved allowances"", () => { const approvedAmount = u128.from(10) // assume alice signs a transfer transaction VMContext.setSigner_account_id(alice); // alice approves bob to spend 10 tokens on her behalf approve(bob, approvedAmount) expect(allowance(alice, bob)).toBe(u128.from(10)); // test that a approve event was recorded // log(getNewestApprovalEvent()) const event = getNewestApprovalEvent(); expect(event.owner).toBe(alice); expect(event.spender).toBe(bob); expect(event.oldValue).toBe(u128.Zero); expect(event.value).toBe(approvedAmount); }) it(""should support updating allowances"", () => { const limit1 = u128.from(10) const limit2 = u128.from(20) // assume alice signs a transfer transaction VMContext.setSigner_account_id(alice); // alice approves bob to spend some limit of tokens on her behalf approve(bob, limit1) expect(allowance(alice, bob)).toBe(limit1); // test that a approve event was recorded // log(getNewestApprovalEvent()) const event1 = getNewestApprovalEvent(); expect(event1.owner).toBe(alice); expect(event1.spender).toBe(bob); expect(event1.oldValue).toBe(u128.Zero); expect(event1.value).toBe(limit1); // alice approves bob to spend a different limit of tokens on her behalf approve(bob, limit2) expect(allowance(alice, bob)).toBe(limit2); // test that a approve event was recorded // log(getNewestApprovalEvent()) const [MASK] = getNewestApprovalEvent(); expect( [MASK] .owner).toBe(alice); expect( [MASK] .spender).toBe(bob); expect( [MASK] .oldValue).toBe(limit1); expect( [MASK] .value).toBe(limit2); }) throws(""should avoid approving allowances when owner has insufficient funds"", () => { const approvedAmount = u128.from(10) // assume derek signs a transfer transaction VMContext.setSigner_account_id(derek); // derek approves bob to spend 10 tokens on his behalf approve(bob, approvedAmount) // test that a approve event was recorded // log(getNewestApprovalEvent()) const event = getNewestApprovalEvent(); expect(event.owner).toBe(alice); expect(event.spender).toBe(bob); expect(event.oldValue).toBe(u128.from(0)); expect(event.value).toBe(approvedAmount); }) it(""should allow approved transfers"", () => { const approvedAmount = u128.from(10) const transferredAmount = u128.from(9) // assume alice signs a transfer transaction VMContext.setSigner_account_id(alice); // alice approves bob to spend 10 tokens on her behalf approve(bob, approvedAmount) // test that a approve event was recorded // log(getNewestApprovalEvent()) const approvalEvent = getNewestApprovalEvent(); expect(approvalEvent.owner).toBe(alice); expect(approvalEvent.spender).toBe(bob); expect(approvalEvent.oldValue).toBe(u128.Zero); expect(approvalEvent.value).toBe(approvedAmount); // assume bob signs a transfer transaction VMContext.setSigner_account_id(bob); const aliceBefore = balanceOf(alice); const carolBefore = balanceOf(carol); transferFrom(alice, carol, transferredAmount); expect(balanceOf(alice)).toBe(u128.sub(aliceBefore, transferredAmount)) expect(balanceOf(carol)).toBe(u128.add(carolBefore, transferredAmount)) // test that a transfer event was recorded // log(getNewestTransferEvent()) const transferEvent = getNewestTransferEvent(); expect(transferEvent.spender).toBe(bob); expect(transferEvent.from).toBe(alice); expect(transferEvent.to).toBe(carol); expect(transferEvent.value).toBe(transferredAmount); }) describe("""", () => { beforeEach(() => { // assume alice signs a transfer transaction VMContext.setSigner_account_id(alice); // alice approves bob to spend 10 tokens on her behalf approve(bob, u128.from(10)) // assume bob signs a transfer transaction VMContext.setSigner_account_id(bob); }) throws(""should disallow transfers that exceed allowance limit"", () => { transferFrom(alice, carol, u128.from(11)); }) throws(""should disallow transfers that incrementally rise above allowance limit"", () => { transferFrom(alice, carol, u128.from(9)); transferFrom(alice, carol, u128.from(2)); }) }) }) })",event2 4,"import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { apiCall } from './api'; // Mock the auth module - move this before any constants vi.mock('./auth', () => { return { refreshToken: vi.fn(), }; }); // Get the mocked function after vi.mock const mockRefreshToken = vi.mocked(await import('./auth')).refreshToken; // Mock fetch globally const mockFetch = vi.fn(); global.fetch = mockFetch; // Helper to create mock Response objects const createMockResponse = ( status: number, body: unknown = {}, ok?: boolean ): Response => { const response = { status, ok: ok !== undefined ? ok : status >= 200 && status < 300, json: vi.fn().mockResolvedValue(body), text: vi .fn() .mockResolvedValue( typeof body === 'string' ? body : JSON.stringify(body) ), } as unknown as Response; return response; }; // Helper to set document.cookie const setCookie = (name: string, value: string) => { Object.defineProperty(document, 'cookie', { writable: true, value: `${name}=${encodeURIComponent(value)}`, configurable: true, }); }; describe('apiCall', () => { beforeEach(() => { vi.clearAllMocks(); // Clear cookies Object.defineProperty(document, 'cookie', { writable: true, value: '', configurable: true, }); }); afterEach(() => { vi.restoreAllMocks(); }); describe('basic functionality', () => { it('makes a successful GET request', async () => { const mockResponseData = { success: true }; mockFetch.mockResolvedValue(createMockResponse(200, mockResponseData)); const result = await apiCall('https://api.example.com/test'); expect(mockFetch).toHaveBeenCalledWith('https://api.example.com/test', { credentials: 'include', headers: { 'Content-Type': 'application/json', }, }); expect(result.status).toBe(200); }); it('makes a successful POST request with body', async () => { const requestBody = { name: 'test' }; const mockResponseData = { id: 1, name: 'test' }; mockFetch.mockResolvedValue(createMockResponse(201, mockResponseData)); const result = await apiCall('https://api.example.com/create', { method: 'POST', body: JSON.stringify(requestBody), }); expect(mockFetch).toHaveBeenCalledWith('https://api.example.com/create', { method: 'POST', body: JSON.stringify(requestBody), credentials: 'include', headers: { 'Content-Type': 'application/json', }, }); expect(result.status).toBe(201); }); it('handles 204 No Content responses', async () => { mockFetch.mockResolvedValue(createMockResponse(204, null, true)); const result = await apiCall('https://api.example.com/delete', { method: 'DELETE', }); expect(result.status).toBe(204); }); it('preserves custom headers', async () => { mockFetch.mockResolvedValue(createMockResponse(200, {})); await apiCall('https://api.example.com/test', { headers: { 'Custom-Header': 'custom-value', 'Content-Type': 'text/plain', }, }); expect(mockFetch).toHaveBeenCalledWith('https://api.example.com/test', { credentials: 'include', headers: { 'Content-Type': 'text/plain', // Custom content type should override 'Custom-Header': 'custom-value', }, }); }); }); describe('CSRF token handling', () => { it('adds CSRF token to non-GET requests when token exists', async () => { setCookie('csrf_token', ''); mockFetch.mockResolvedValue(createMockResponse(200, {})); await apiCall('https://api.example.com/create', { method: 'POST', body: JSON.stringify({ test: 'data' }), }); expect(mockFetch).toHaveBeenCalledWith('https://api.example.com/create', { method: 'POST', body: JSON.stringify({ test: 'data' }), credentials: 'include', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': 'test-csrf-token', }, }); }); it('omits CSRF token with GET methods', async () => { setCookie('csrf_token', ''); mockFetch.mockResolvedValue(createMockResponse(200, {})); await apiCall('https://api.example.com/test', { method: 'GET' }); // Check that CSRF token is not included in headers const calledOptions = mockFetch.mock.calls?.[0]?.[1] as RequestInit; expect(calledOptions['headers']).not.toHaveProperty('X-CSRF-Token'); }); it('handles missing CSRF token gracefully', async () => { // No CSRF token in cookies mockFetch.mockResolvedValue(createMockResponse(200, {})); await apiCall('https://api.example.com/create', { method: 'POST', }); expect(mockFetch).toHaveBeenCalledWith('https://api.example.com/create', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json', // No X-CSRF-Token header }, }); }); }); describe('error handling', () => { it('throws error for non-2xx status codes', async () => { const [MASK] = { message: 'Bad Request' }; mockFetch.mockResolvedValue( createMockResponse(400, [MASK] , false) ); await expect(apiCall('https://api.example.com/error')).rejects.toThrow( 'Bad Request' ); }); it('throws generic error when no error message in response', async () => { mockFetch.mockResolvedValue(createMockResponse(500, {}, false)); await expect(apiCall('https://api.example.com/error')).rejects.toThrow( 'HTTP error! status: 500' ); }); it('handles malformed JSON error responses', async () => { const mockResponse = { status: 400, ok: false, json: vi.fn().mockRejectedValue(new Error('Invalid JSON')), } as unknown as Response; mockFetch.mockResolvedValue(mockResponse); await expect(apiCall('https://api.example.com/error')).rejects.toThrow( 'Invalid JSON' ); }); it('handles network errors', async () => { const networkError = new Error('Network error'); mockFetch.mockRejectedValue(networkError); await expect(apiCall('https://api.example.com/error')).rejects.toThrow( 'Network error' ); }); it('handles timeout errors', async () => { const timeoutError = new Error('Request timeout'); mockFetch.mockRejectedValue(timeoutError); await expect(apiCall('https://api.example.com/slow')).rejects.toThrow( 'Request timeout' ); }); }); describe('authentication and token refresh', () => { it('handles 401 response by attempting token refresh and retrying', async () => { const successResponse = createMockResponse(200, { data: 'success' }); mockFetch .mockResolvedValueOnce(createMockResponse(401, {}, false)) // First call fails with 401 .mockResolvedValueOnce(successResponse); // Retry succeeds mockRefreshToken.mockResolvedValue(true); const result = await apiCall('https://api.example.com/protected'); expect(mockFetch).toHaveBeenCalledTimes(2); expect(mockRefreshToken).toHaveBeenCalledTimes(1); expect(result.status).toBe(200); }); it('throws error when token refresh fails', async () => { mockFetch.mockResolvedValue(createMockResponse(401, {}, false)); mockRefreshToken.mockResolvedValue(false); await expect( apiCall('https://api.example.com/protected') ).rejects.toThrow('Authentication failed'); expect(mockFetch).toHaveBeenCalledTimes(1); expect(mockRefreshToken).toHaveBeenCalledTimes(1); }); it('does not attempt refresh for auth/refresh endpoint', async () => { mockFetch.mockResolvedValue(createMockResponse(401, {}, false)); await expect( apiCall('https://api.example.com/auth/refresh') ).rejects.toThrow('Authentication failed'); expect(mockFetch).toHaveBeenCalledTimes(1); expect(mockRefreshToken).not.toHaveBeenCalled(); }); it('handles successful token refresh but failed retry', async () => { mockFetch .mockResolvedValueOnce(createMockResponse(401, {}, false)) // First call fails .mockResolvedValueOnce( createMockResponse(403, { message: 'Forbidden' }, false) ); // Retry fails with different error mockRefreshToken.mockResolvedValue(true); await expect( apiCall('https://api.example.com/protected') ).rejects.toThrow('Forbidden'); expect(mockFetch).toHaveBeenCalledTimes(2); expect(mockRefreshToken).toHaveBeenCalledTimes(1); }); it('handles token refresh throwing an error', async () => { mockFetch.mockResolvedValue(createMockResponse(401, {}, false)); mockRefreshToken.mockRejectedValue(new Error('Refresh failed')); await expect( apiCall('https://api.example.com/protected') ).rejects.toThrow('Refresh failed'); // The test should match the actual error from the mock expect(mockFetch).toHaveBeenCalledTimes(1); expect(mockRefreshToken).toHaveBeenCalledTimes(1); }); it('preserves original request options in retry', async () => { const requestBody = { data: 'test' }; const customHeaders = { 'Custom-Header': 'value' }; mockFetch .mockResolvedValueOnce(createMockResponse(401, {}, false)) .mockResolvedValueOnce(createMockResponse(200, { success: true })); mockRefreshToken.mockResolvedValue(true); await apiCall('https://api.example.com/protected', { method: 'POST', body: JSON.stringify(requestBody), headers: customHeaders, }); // Check that both calls had the same options expect(mockFetch).toHaveBeenCalledTimes(2); expect(mockFetch).toHaveBeenNthCalledWith( 1, 'https://api.example.com/protected', { method: 'POST', body: JSON.stringify(requestBody), credentials: 'include', headers: { 'Content-Type': 'application/json', 'Custom-Header': 'value', }, } ); expect(mockFetch).toHaveBeenNthCalledWith( 2, 'https://api.example.com/protected', { method: 'POST', body: JSON.stringify(requestBody), credentials: 'include', headers: { 'Content-Type': 'application/json', 'Custom-Header': 'value', }, } ); }); }); describe('console logging', () => { it('logs debug information for requests and responses', async () => { const consoleSpy = vi .spyOn(console, 'debug') .mockImplementation(() => {}); mockFetch.mockResolvedValue(createMockResponse(200, {})); await apiCall('https://api.example.com/test'); expect(consoleSpy).toHaveBeenCalledWith( 'Making API call to: https://api.example.com/test' ); expect(consoleSpy).toHaveBeenCalledWith( 'Response status: 200 for URL: https://api.example.com/test' ); consoleSpy.mockRestore(); }); it('logs errors when API calls fail', async () => { const consoleSpy = vi .spyOn(console, 'error') .mockImplementation(() => {}); const networkError = new Error('Network failure'); mockFetch.mockRejectedValue(networkError); await expect(apiCall('https://api.example.com/error')).rejects.toThrow(); expect(consoleSpy).toHaveBeenCalledWith( 'API call failed: Network failure' ); consoleSpy.mockRestore(); }); }); describe('request options handling', () => { it('merges provided options with defaults', async () => { mockFetch.mockResolvedValue(createMockResponse(200, {})); await apiCall('https://api.example.com/test', { method: 'PUT', cache: 'no-cache' as RequestCache, redirect: 'follow' as RequestRedirect, }); expect(mockFetch).toHaveBeenCalledWith('https://api.example.com/test', { method: 'PUT', cache: 'no-cache', redirect: 'follow', credentials: 'include', headers: { 'Content-Type': 'application/json', }, }); }); it('handles undefined options parameter', async () => { mockFetch.mockResolvedValue(createMockResponse(200, {})); await apiCall('https://api.example.com/test'); expect(mockFetch).toHaveBeenCalledWith('https://api.example.com/test', { credentials: 'include', headers: { 'Content-Type': 'application/json', }, }); }); it('handles empty options object', async () => { mockFetch.mockResolvedValue(createMockResponse(200, {})); await apiCall('https://api.example.com/test', {}); expect(mockFetch).toHaveBeenCalledWith('https://api.example.com/test', { credentials: 'include', headers: { 'Content-Type': 'application/json', }, }); }); }); describe('HTTP methods', () => { it('handles different HTTP methods correctly', async () => { setCookie('csrf_token', ''); mockFetch.mockResolvedValue(createMockResponse(200, {})); const methods = ['POST', 'PUT', 'PATCH', 'DELETE']; for (const method of methods) { mockFetch.mockClear(); await apiCall('https://api.example.com/test', { method }); expect(mockFetch).toHaveBeenCalledWith('https://api.example.com/test', { method, credentials: 'include', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': '', }, }); } }); }); describe('edge cases', () => { it('handles null response body', async () => { const mockResponse = { status: 200, ok: true, json: vi.fn().mockResolvedValue(null), } as unknown as Response; mockFetch.mockResolvedValue(mockResponse); const result = await apiCall('https://api.example.com/test'); expect(result.status).toBe(200); }); }); }); ",errorResponse 5,"import { EmotivePoint } from ""../shared/models/emotivePoint""; import { Face } from ""../shared/models/faces""; import * as FaceApi from ""../shared/faceapi""; import * as emojiLookup from ""emoji-dictionary""; const EMOJIS_TO_TRAIN = [ ""☺️"", ""🤓"", ""😃"", ""😆"", ""😉"", ""😍"", ""😎"", ""😐"", ""😕"", ""😖"", ""😘"", ""😜"", ""😝"", ""😠"", ""😧"", ""😩"", ""😬"", ""😭"", ""😱"", ""😳"", ""😴"" ]; async function getCalibrationArrayString(context) { let str = ""[""; for (let emoji of EMOJIS_TO_TRAIN) { context.log(`Processing ${emoji}`); // Given an emoji like 😴 returns the word version, like 'sleepy' let emojiName = emojiLookup.getName(emoji); let emotion = await FaceApi.getEmotionFromLocalProxyImage(context, emojiName); let point = new EmotivePoint(emotion); let face = new Face(point, null); str += `{ emotiveValues: new EmotivePoint({ anger: ${emotion.anger}, contempt: ${emotion.contempt}, disgust: ${emotion.disgust}, fear: ${emotion.fear}, happiness: ${emotion.happiness}, neutral: ${emotion.neutral}, sadness: ${emotion.sadness}, surprise: ${emotion.surprise} }), emojiIcon: ""${emoji}"" },`; } str += ""]""; return str; } export async function index(context, req) { context.log(`Calibrate HTTP trigger`); const [MASK] = await getCalibrationArrayString(context); const body = {MOJIS: [MASK] }; context.res = { status: 200, headers: { ""Content-Type"": ""application/json"" }, body: body }; }",array 6,"class Case { CaseID: number; DTCreated: Date; DTReceived: Date; DTClosed: Date; DTAbandoned: Date; CustomerFirstName: string; CustomerLastName: string; CustomerUserID: string; CustomerComputerName: string; CustomerPhone: string; CustomerEmail: string; SupportCategory: string; SupportType: string; SupportQueue: string; Details: string; Locked: boolean; LockedBy: string; } class Tech_Account { FirstName: string; LastName: string; UserID: string; HashedPassword: string; AuthenticationToken: string; TempPassword: string; BadLoginAttempts: number; LastBadLogin: Date; Email: string; ComputerGroups: string[]; AccessLevel: AccessLevel; } class Computer { ComputerName: string; LastReboot: Date; CurrentUser: string; LastLoggedOnUser: string; ComputerGroup: string; } enum AccessLevel { Standard, Admin } enum ConnectionType { Customer, Technician } class Main_Model { constructor() { this.Cases = []; } UserID: string; AuthenticationToken: string; LoggedIn: boolean; Socket_Main: WebSocket; Socket_Port: string; Secure_Socket_Port: string; Cases: Case[]; Tech_Accounts: Tech_Account[]; Hub_Computers: Computer[]; Context: ConnectionType; LastTypingStatus: Date; QueueWaitTimer: null; PartnerFirstName: string; PartnerLastName: string; ComputerGroups: string[]; Temp: {}; get HostAndPort():string { var [MASK] = location.host; if (this.Secure_Socket_Port != ""443"") { if (location.protocol.search(""https"") > -1) { [MASK] = location.hostname + "":"" + this.Secure_Socket_Port; } } if (this.Socket_Port != ""80"") { if (location.protocol.search(""https"") == -1) { [MASK] = location.hostname + "":"" + this.Socket_Port; } } return [MASK] ; } } const InstaTech = new Main_Model(); InstaTech.Socket_Port = ""80""; InstaTech.Secure_Socket_Port = ""443""; InstaTech.Temp = {};",hostAndPort 7,"import {Component} from '@angular/core'; import {StompService} from 'ng2-stomp-service'; import {Subscription} from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { connected = false; greetings = new Array(); subscription: Subscription = null; constructor(private stomp: StompService) { stomp.configure({host: '/stomp-websocket'}); } connect() { this.stomp.startConnect().then(() => { this.connected = true; console.log('connected'); // there appears to be a bug in stomp-service which means the promise is // resolved before the connection state is properly changed setTimeout(() => { console.log('subscribing'); this.subscription = this.stomp.subscribe('/topic/greetings', ( [MASK] ) => this.greetings.push( [MASK] .content) ); }, 500); }); } disconnect() { this.subscription.unsubscribe(); this.stomp.disconnect().then(() => { console.log('disconnected'); this.connected = false }); } sendName(name: string) { this.stomp.send('/app/hello', {'name': name}); } } ",data 8,"// This code was generated by the angular-custom-elements-schematic. Any changes will be overwritten next time it runs. import { Component, ElementRef, ChangeDetectionStrategy, ChangeDetectorRef, NgZone, Input, inject } from '@angular/core'; import { AccordionComponent as AccordionComponentCustomElement, defineAccordionComponent } from '@tylertech/forge'; /** */ @Component({ selector: 'forge-accordion', changeDetection: ChangeDetectionStrategy.OnPush, template: '', standalone: false }) export class AccordionComponent { protected elementRef = inject>(ElementRef); protected zone = inject(NgZone); /** The forge-accordion element. */ public readonly nativeElement = this.elementRef.nativeElement; /** * Gets/sets the selector to use for finding the child expansion panels. Defaults to searching the direct children for `` elements. * Use this if you need to scope this accordion to a specific set of expansion panels, or your expansion panels are not direct children of the accordion. */ @Input() public set panelSelector(value: AccordionComponentCustomElement['panelSelector']) { this.zone.runOutsideAngular(() => { this.nativeElement.panelSelector = value; }); } public get panelSelector(): AccordionComponentCustomElement['panelSelector'] { return this.nativeElement.panelSelector; } constructor() { defineAccordionComponent(); const [MASK] = inject(ChangeDetectorRef); [MASK] .detach(); } } ",changeDetectorRef 9,"import { urlGenerator } from './urlGenerator' export const getParentTitle = (slug: string, allMdx?: any) => { const allContent = allMdx && allMdx.edges && allMdx.edges.map((mdx: any) => ({ ...mdx.node.fields, title: mdx.node.frontmatter.title, staticLink: mdx.node.frontmatter.staticLink, codeStyle: mdx.node.frontmatter.codeStyle, })) allContent?.map((content: any) => { content.parentTitle = [] const parts = content.slug.split('/') const [MASK] = parts.slice( 1, parts[parts.length - 1] === 'index' ? parts.length - 2 : parts.length - 1 ) [MASK] .forEach((part: any) => { const parent = allContent.find((ac: any) => { const parentParts = ac.slug.split('/') return ( parentParts[parentParts.length - 1] === 'index' && parentParts[parentParts.length - 2] === part ) }) if (parent) { // const parts = parent.slug.split('/') // const topLevel = parts.length == 3 && parts[parts.length - 1] === 'index' ? true : false content.parentTitle.push({ title: parent?.title, codeStyle: parent?.codeStyle, link: urlGenerator(parent.modSlug), // link: topLevel || parent.staticLink ? null : urlGenerator(parent.modSlug), }) } }) }) const currentSlug = allContent.find((mdx: any) => mdx.modSlug === slug) return currentSlug ? currentSlug.parentTitle : [] } ",slicedParts 10,"import * as jspb from 'google-protobuf'; import { Event, MethodEnum } from './event_pb'; export class Context { private bytes: Uint8Array; constructor(bytes: Uint8Array) { this.bytes = bytes; } toObject(pb: any): any { const m = pb.deserializeBinary(this.bytes); return m.toObject(); } } export interface Router { path: string; handler(c: Context): void; } export class Door { private routes: Router[][]; constructor() { this.routes = []; } openBind(handler: (c: Context) => void, ...paths: string[]) { this.add(handler, MethodEnum.OPEN, paths); } closeBind(handler: (c: Context) => void, ...paths: string[]) { this.add(handler, MethodEnum.CLOSE, paths); } getBind(handler: (c: Context) => void, ...paths: string[]) { this.add(handler, MethodEnum.GET, paths); } putBind(handler: (c: Context) => void,...paths: string[]) { this.add(handler, MethodEnum.PUT, paths); } postBind(handler: (c: Context) => void,...paths: string[]) { this.add(handler, MethodEnum.POST, paths); } deleteBind(handler: (c: Context) => void,...paths: string[]) { this.add(handler, MethodEnum.DELETE, paths); } private add(handler: (c: Context) => void, method: MethodEnum, paths: string[]) { const path = paths.join('/'); let routes = this.routes[method]; if (!routes) { routes = []; this.routes[method] = routes; } for (let r of routes) { if (r.path === path) { r.handler = handler; return; } } routes.push({ path: path, handler: handler, }); } onMessage(msg: MessageEvent) { readFile(msg.data).then(( [MASK] ) => { const array = new Uint8Array( [MASK] ); const event = Event.deserializeBinary(array).toObject(); const routes = this.routes[event.method]; if (!routes) return; for (let r of routes) { if (r.path === event.path) { r.handler(new Context(event.data as Uint8Array)); return; } } }); } private serializeBinary(pb: jspb.Message, method: MethodEnum, paths: string[]): Uint8Array{ const e = new Event(); e.setMethod(method); e.setPath(paths.join('/')); if (pb) { e.setData(pb.serializeBinary()); } return e.serializeBinary() } openBinary(pb: jspb.Message, ...paths: string[]): Uint8Array { return this.serializeBinary(pb, MethodEnum.OPEN, paths) } closeBinary(pb: jspb.Message, ...paths: string[]): Uint8Array { return this.serializeBinary(pb, MethodEnum.CLOSE, paths) } getBinary(pb: jspb.Message, ...paths: string[]): Uint8Array { return this.serializeBinary(pb, MethodEnum.GET, paths) } postBinary(pb: jspb.Message, ...paths: string[]): Uint8Array { return this.serializeBinary(pb, MethodEnum.POST, paths) } putBinary(pb: jspb.Message, ...paths: string[]): Uint8Array { return this.serializeBinary(pb, MethodEnum.PUT, paths) } deleteBinary(pb: jspb.Message, ...paths: string[]): Uint8Array { return this.serializeBinary(pb, MethodEnum.DELETE, paths) } } function readFile(blob: Blob): Promise { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onloadend = () => { resolve(reader.result); } reader.onerror = (event) => { reject(event.error); } reader.readAsArrayBuffer(blob); }); } ",buffer 11,"import { KeyRotator } from ""@economist/aws-key-rotator""; import { IAM } from ""aws-sdk""; import { createCircleCIHandler } from ""./circleci""; import { RotationJob } from ""./jobs""; export function batchRotateKeys(iam: IAM, jobs: RotationJob[]) { const [MASK] : Promise[] = []; const failedJobs: { user: string, reason: any }[] = []; for (const job of jobs) { const keyHandler = createCircleCIHandler(job.vcsProvider, job.vcsUser, job.project, job.apiToken, job.accessKeyName, job.secretKeyName); const keyRotator = new KeyRotator(iam, keyHandler); const promise = keyRotator.rotateKeys(job.user) .catch((err) => { console.error(err); failedJobs.push({ user: job.user, reason: err, }); }); [MASK] .push(promise); } return Promise.all( [MASK] ) .then(() => { if (failedJobs.length !== 0) { const err = `Key rotation failed for the following users: ${JSON.stringify(failedJobs)}`; console.error(err); throw err; } console.log(`Successfully rotated the Access Keys for: ${jobs.map((job) => job.user)}`); }); } ",promises 12,"import fs from 'fs' import path from 'path' import matter from 'gray-matter' const postsDirectory = path.join(process.cwd(), 'content/blogs') export interface Source { title: string; url: string; author?: string; publishedDate?: string; } export interface BlogPost { slug: string title: string date: string description: string image: string tags: string[] content: string sources?: Source[] } export function getAllBlogPosts() { const fileNames = fs.readdirSync(postsDirectory) const [MASK] = fileNames.map((fileName) => { const slug = fileName.replace(/\.md$/, '') const fullPath = path.join(postsDirectory, fileName) const fileContents = fs.readFileSync(fullPath, 'utf8') const { data, content } = matter(fileContents) return { slug, content, ...data, } as BlogPost }) return [MASK] .sort((a, b) => (a.date < b.date ? 1 : -1)) } export function getBlogPost(slug: string): BlogPost | null { try { const fullPath = path.join(postsDirectory, `${slug}.md`) const fileContents = fs.readFileSync(fullPath, 'utf8') const { data, content } = matter(fileContents) return { slug, content, ...data, } as BlogPost } catch { return null } }",allPostsData 13,"import { Assets, Exports } from './typings/assets.typings'; import sendRequest from './utils/send-request'; import endpoints from './utils/endpoints'; /** * Gets all asset paths in the current game version * @returns Array of paths */ async function getAssets(): Promise { return await sendRequest(endpoints.Assets); } /** * Gets all asset paths in the supplied pak number (does technically support pakchunk 0, 10, and 20, but it's not intended for that use) * @param pak Pak Number * @returns Array of Paths */ async function getAssetsFromPak(pak: string): Promise { if (!pak) { throw new Error('Please provide a pak number'); } const [MASK] = Number(pak); if (! [MASK] ) { throw new Error('Please provide a valid pak number') }; return await sendRequest(`${endpoints.Assets_Dynamic}/${pak}`); } /** * Gets the properties, or visible export, of a specified asset path. * @param path Path you want to export * @param raw Force Raw Export * @returns Json Export or if Image Buffr of the image */ async function exportPath(path: string, raw: boolean = false): Promise { if (!path) { throw new Error('Please provide a path you want to export'); } const data = await sendRequest(endpoints.Assets_Export, { path, raw, }); if (typeof data === 'object') { const result = await Promise.resolve(data); return result; } else if (typeof data === 'string') { const data = await sendRequest(endpoints.Assets_Export, { path, raw, }, 'GET', { responseType: 'arraybuffer', }); return data; } } export { getAssets, getAssetsFromPak, exportPath }; ",parsed 14,"import { Component, OnInit } from '@angular/core'; import { Web3Service } from '../../../services/web3/web3.service'; import { PersonService } from '../../../services/person/person.service'; import { AssetService } from '../../../services/asset/asset.service'; declare let require: any; const assetListArtifacts = require('../../../../../build/contracts/AssetList.json'); const personListArtifacts = require('../../../../../build/contracts/PersonList.json'); @Component({ selector: 'app-admin-dashboard', templateUrl: './admin-dashboard.component.html', styleUrls: ['./admin-dashboard.component.css'], }) export class AdminDashboardComponent implements OnInit { AssetList: any; PersonList: any; newAsset: any; assets: any; newPerson: any; persons: any; constructor( private web3Service: Web3Service, private personService: PersonService, private assetService: AssetService ) { this.newAsset = { name: null, desc: null, }; this.assets = []; this.newPerson = { name: null, age: null, }; this.persons = []; } ngOnInit() {} generateAccount() { var mnemonic = this.web3Service.generateMnemonic(); console.log('seed words = ' + mnemonic); var wallet = this.web3Service.generateWalletFromSeed(mnemonic); var address = wallet.getChecksumAddressString(); var publicKey = wallet.getPublicKeyString(); var privateKey = wallet.getPrivateKeyString(); console.log('address = ' + address); console.log('publicKey = ' + publicKey); console.log('privateKey = ' + privateKey); // var message = 'Vivek'; var message1 = { firstname: 'Vivek', lastname: 'Badrinarayan', }; var message2 = { lastname: 'Badrinarayan', firstname: 'Vivekk', }; var signature1 = this.web3Service.sign(message1, privateKey); console.log(signature1); var [MASK] = this.web3Service.recoverFromSignatureObj(signature1); console.log('recover = ' + [MASK] ); var signature2 = this.web3Service.sign(message2, privateKey); console.log(signature2); var recover2 = this.web3Service.recoverFromSignatureObj(signature2); console.log('recover = ' + recover2); } async createAsset(event, form) { event.preventDefault(); if (!form.valid) { alert('Please fill all fields'); return; } let result = await this.assetService.createAsset(this.newAsset); if (!result.success) { console.log(result['message']); } else { console.log('Transaction Successful! TxHash: ' + result['transaction']); alert('Transaction Successful! TxHash: ' + result['transaction']); } this.newAsset.name = null; this.newAsset.desc = null; } async getAssets() { this.assets = await this.assetService.getAssets(); console.log(this.assets); } async createPerson(event, form) { event.preventDefault(); if (!form.valid) { alert('Please fill all fields'); return; } let result = await this.personService.createPerson(this.newPerson); if (!result['success']) { console.log(result['message']); } else { console.log('Transaction Successful! TxHash: ' + result['transaction']); alert('Transaction Successful! TxHash: ' + result['transaction']); } this.newPerson.name = null; this.newPerson.age = null; } async getPersons() { this.persons = await this.personService.getPersons(); console.log(this.persons); } } ",recover1 15,"const timeMessage = '⏰ The checks finished in'; console.time(timeMessage); // Load config at the beginning import { FileOption, getConfig } from './utils/config.js'; const config = await getConfig(); import fs from 'fs'; import path from 'path'; import { VFile } from 'vfile'; import { VFileMessage } from 'vfile-message'; import { FileExtension, getAllContentFileNamesWithExtension, getFilePathFromRepoRoot, outputDirectory, readFileSync, repositoryRoot, writeListToFile, } from './utils/files.js'; import { getFilesChangedComparedToBaseByExtension, getFilesChangedInLastCommitByExtensions, } from './utils/git.js'; import { GitHubLabel, addLabelToIssue, getNewPullRequestCommentForVFileMessage, postPullRequestComments, pullRequestReviewComments, } from './utils/github.js'; import { REQUIRED_CHECKS, RETEXT_INAPPROPRIATE, RETEXT_PROFANITIES, RETEXT_SPELL, compileMdx, getReTextAnalysis, } from './utils/unified.js'; import { Locale, checkEnglishVersionExists, checkFileIsTranslatable, checkFileImportEquality, checkMdxEquality, isLocaleFile, outdatedTranslationFiles, checkVoidTagsHaveNoChildren, } from './utils/localization.js'; import { Emoji } from './utils/utils.js'; import { deduplicate } from './utils/utils.js'; import { allowedHttpLinksTextFileFullPath, checkContentLinks, allNonRobloxHttpLinks, checkUnusedAssets, } from './utils/links.js'; import { addToSummaryOfRequirements, addToSummaryOfSuggestions, logSummariesToConsole, summaryOfRequirements, } from './utils/console.js'; import { checkMarkdownLint } from './utils/markdownlint.js'; import { checkEngineReferenceContent } from './utils/engineReferenceChecks.js'; import { containsOpenApiSchema, validateOpenApiSchema, } from './utils/openApiSchemaChecks.js'; let filesToCheck: string[] = []; let labelPullRequestAsInappropriate = false; let missSpelledWords: string[] = []; const getFilesToCheck = async () => { console.log(`::group::${Emoji.OpenFileFolder} Getting changed files`); if (config.files === FileOption.All) { if (config.checkLocalizedContent === true) { for (const locale of Object.values(Locale)) { filesToCheck.push( ...getAllContentFileNamesWithExtension({ locale, fileExtension: FileExtension.MARKDOWN, }), ...getAllContentFileNamesWithExtension({ locale, fileExtension: FileExtension.YAML, }), ...getAllContentFileNamesWithExtension({ locale, fileExtension: FileExtension.JSON, }) ); } } else { filesToCheck.push( ...getAllContentFileNamesWithExtension({ locale: Locale.EN_US, fileExtension: FileExtension.MARKDOWN, }), ...getAllContentFileNamesWithExtension({ locale: Locale.EN_US, fileExtension: FileExtension.YAML, }), ...getAllContentFileNamesWithExtension({ locale: Locale.EN_US, fileExtension: FileExtension.JSON, }) ); } filesToCheck.push(...['README.md', 'STYLE.md', 'CODE_OF_CONDUCT.md']); } else if (config.files === FileOption.Changed) { filesToCheck = await getFilesChangedComparedToBaseByExtension({ baseBranch: config.baseBranch, fileExtensions: [ FileExtension.MARKDOWN, FileExtension.YAML, FileExtension.JSON, ], }); } else if (config.files === FileOption.LastCommit) { filesToCheck = await getFilesChangedInLastCommitByExtensions([ FileExtension.MARKDOWN, FileExtension.YAML, FileExtension.JSON, ]); } if (!config.checkLocalizedContent) { filesToCheck = filesToCheck.filter((filePath) => { return isLocaleFile(filePath, Locale.EN_US); }); } const prefixesToIgnore = [ '.github/', 'content/common/navigation/', 'tools/', 'content/en-us/reference/engine/code_samples/', ]; filesToCheck = filesToCheck.filter((filePath) => { return !prefixesToIgnore.some((prefix) => filePath.startsWith(prefix)); }); console.log(`Files to check (${filesToCheck.length}):`, filesToCheck); console.log('::endgroup::'); }; const processRetextVFileMessage = ({ filePathFromRepoRoot, message, }: { filePathFromRepoRoot: string; message: VFileMessage; }) => { const [MASK] = `In ${filePathFromRepoRoot}, line ${message.line}, column ${message.column}, ${message.reason}`; let isRequiredCheck = false; if (message.source) { if ( message.source === RETEXT_INAPPROPRIATE || message.source === RETEXT_PROFANITIES ) { labelPullRequestAsInappropriate = true; } if (message.source === RETEXT_SPELL && message.actual) { missSpelledWords.push(message.actual); } if (REQUIRED_CHECKS.has(message.source)) { isRequiredCheck = true; addToSummaryOfRequirements( `${Emoji.NoEntry} Requirement: ${ [MASK] }` ); } else { addToSummaryOfSuggestions(`${Emoji.Bulb} Suggestion: ${ [MASK] }`); } } // Always print required messages, suggestions are optional if (isRequiredCheck || !config.onlyRequiredChecks) { console.log(`${Emoji.EnvelopeWithArrow} Message from check:`); console.log(isRequiredCheck ? Emoji.NoEntry : Emoji.Bulb, message); } // Only comment required checks to avoid too much noise if (isRequiredCheck && config.postPullRequestComments) { const pullRequestReviewComment = getNewPullRequestCommentForVFileMessage({ commit_id: config.commitHash, isRequiredCheck, message, path: filePathFromRepoRoot, pull_number: config.pullRequestNumber, repository: config.repository, }); console.log(`${Emoji.Mailbox} Comment to post:`); console.log(pullRequestReviewComment); pullRequestReviewComments.push(pullRequestReviewComment); } }; const processRetextVFileMessages = ({ filePathFromRepoRoot, retextVFile, }: { filePathFromRepoRoot: string; retextVFile: VFile; }) => { if (retextVFile.messages.length > 0) { retextVFile.messages.forEach((message) => { processRetextVFileMessage({ filePathFromRepoRoot, message }); }); } else { console.log(`${Emoji.WhiteCheckMark} No messages from checks`); } }; const postCommentsToGitHub = async () => { await postPullRequestComments({ pullRequestReviewComments, pull_number: config.pullRequestNumber, repository: config.repository, }); const labelsForPullRequest = [ GitHubLabel.ChangesRequested, ...(labelPullRequestAsInappropriate ? [GitHubLabel.Inappropriate] : []), ]; console.log(`::group::${Emoji.Label} Labeling pull request`); const labelResponse = await addLabelToIssue({ labels: labelsForPullRequest, issue_number: config.pullRequestNumber, repository: config.repository, }); console.log(labelResponse); console.log('::endgroup::'); }; try { await getFilesToCheck(); for (const filePath of filesToCheck) { const filePathFromRepoRoot = getFilePathFromRepoRoot( filePath, repositoryRoot ); const isMarkdownFile = filePath.endsWith(FileExtension.MARKDOWN); const isYamlFile = filePath.endsWith(FileExtension.YAML); const isJsonFile = filePath.endsWith(FileExtension.JSON); console.log(`::group::${Emoji.Mag} Checking`, filePathFromRepoRoot); if (!fs.existsSync(filePath)) { console.log( `${Emoji.NoEntry} File does not exist: ${filePathFromRepoRoot}` ); console.log('::endgroup::'); continue; } const fileContent = readFileSync(filePath); if (isJsonFile) { if (containsOpenApiSchema(fileContent)) { await validateOpenApiSchema({ config, filePath: filePathFromRepoRoot, }); } // The remaining checks are not applicable to JSON files console.log('::endgroup::'); continue; } if ( config.checkLocalizedContent && !isLocaleFile(filePathFromRepoRoot, Locale.EN_US) // skip for English ) { checkVoidTagsHaveNoChildren(filePathFromRepoRoot); checkEnglishVersionExists(filePathFromRepoRoot); await checkMdxEquality(filePathFromRepoRoot, fileContent); checkFileImportEquality(filePathFromRepoRoot, fileContent); checkFileIsTranslatable(filePathFromRepoRoot); } if (config.checkRetextAnalysis) { const retextVFile = (await getReTextAnalysis( fileContent )) as unknown as VFile; if (config.debug) { console.log(retextVFile); } processRetextVFileMessages({ retextVFile, filePathFromRepoRoot }); } if (isMarkdownFile) { checkVoidTagsHaveNoChildren(filePathFromRepoRoot); const mdxVFileMessage = (await compileMdx(fileContent)) as VFileMessage; if (mdxVFileMessage) { processRetextVFileMessage({ message: mdxVFileMessage, filePathFromRepoRoot, }); } } if (config.checkHttpLinks || config.checkRelativeLinks) { checkContentLinks({ config, fileContent, filePath: filePathFromRepoRoot, }); } if (isMarkdownFile && config.checkMarkdownLint) { checkMarkdownLint({ config, fileContent, filePath: filePathFromRepoRoot, }); } if (isYamlFile) { await checkEngineReferenceContent({ config, fileContent, filePath: filePathFromRepoRoot, }); } console.log('::endgroup::'); } if (config.checkUnusedAssets) { checkUnusedAssets({ config }); } if (config.debug) { writeListToFile( path.join(outputDirectory, 'misspelled-words.txt'), deduplicate(missSpelledWords).sort(), 'utf-8' ); writeListToFile( allowedHttpLinksTextFileFullPath, deduplicate(allNonRobloxHttpLinks).sort(), 'utf-8' ); } if (config.checkLocalizedContent && outdatedTranslationFiles.length > 0) { const outdatedTranslationFilesPath = path.join( outputDirectory, 'outdated-translation-files.txt' ); writeListToFile( outdatedTranslationFilesPath, outdatedTranslationFiles, 'utf-8' ); } if (config.postPullRequestComments && pullRequestReviewComments.length > 0) { await postCommentsToGitHub(); } logSummariesToConsole(config); } catch (e) { console.error(`${Emoji.NoEntry} Error running the check, exiting 911`, e); process.exit(911); console.log('Exit code 911'); // This should never output } console.timeEnd(timeMessage); if (summaryOfRequirements) { console.log(""::error::There are required checks that didn't pass. Exiting 1""); process.exit(1); console.log('Exit code 1'); // This should never output } ",messageSummary 16,"import { indexSearchParameterBundle, indexStructureDefinitionBundle } from '@medplum/core'; import { readJson, SEARCH_PARAMETER_BUNDLE_FILES } from '@medplum/definitions'; import { Bundle, Claim, HumanName, SearchParameter } from '@medplum/fhirtypes'; import { MockClient } from '@medplum/mock'; import { createWriteStream } from 'fs'; import PdfPrinter from 'pdfmake'; import { formatHumanName, getCms1500DocumentDefinition, handler } from './cms-1500-pdf'; import { fullAnswer } from './cms-1500-test-data'; describe('CMS 1500 PDF Bot', async () => { let medplum: MockClient; beforeAll(() => { indexStructureDefinitionBundle(readJson('fhir/r4/profiles-types.json') as Bundle); indexStructureDefinitionBundle(readJson('fhir/r4/profiles-resources.json') as Bundle); for (const filename of SEARCH_PARAMETER_BUNDLE_FILES) { indexSearchParameterBundle(readJson(filename) as Bundle); } }); beforeEach(async () => { medplum = new MockClient(); }); test.skip('Actual PDF', async () => { await medplum.executeBatch(fullAnswer); const claim = (await medplum.searchOne('Claim', { identifier: 'example-claim-cms1500', })) as Claim; const docDefinition = await getCms1500DocumentDefinition(medplum, claim); const printer = new PdfPrinter({ Helvetica: { normal: 'Helvetica', bold: 'Helvetica-Bold', italics: 'Helvetica-Oblique', bolditalics: 'Helvetica-BoldOblique', }, }); const pdfDoc = printer.createPdfKitDocument(docDefinition); pdfDoc.pipe(createWriteStream(`cms-1500-${Date.now()}.pdf`)); pdfDoc.end(); }); test('Fully answered CMS1500 pdf', async () => { await medplum.executeBatch(fullAnswer); const claim = (await medplum.searchOne('Claim', { identifier: 'example-claim-cms1500', })) as Claim; const [MASK] = await handler(medplum, { bot: { reference: 'Bot/123' }, input: claim, secrets: {}, contentType: 'application/fhir+json', }); expect( [MASK] ).toBeDefined(); expect( [MASK] .resourceType).toStrictEqual('Media'); expect( [MASK] .content.contentType).toStrictEqual('application/pdf'); }); }); describe('formatHumanName', () => { test('formats full name with middle name', () => { const name: HumanName = { family: 'Smith', given: ['John', 'Michael'], }; expect(formatHumanName(name)).toBe('Smith, '); }); test('formats name without middle name', () => { const name: HumanName = { family: 'Smith', given: ['John'], }; expect(formatHumanName(name)).toBe(''); }); test('formats multiple middle names', () => { const name: HumanName = { family: 'Smith', given: ['John', 'Michael', 'Robert'], }; expect(formatHumanName(name)).toBe('Smith, John, '); }); test('formats family name only', () => { const name: HumanName = { family: 'Smith', }; expect(formatHumanName(name)).toBe('Smith'); }); test('formats given names only', () => { const name: HumanName = { given: ['John', 'Michael'], }; expect(formatHumanName(name)).toBe(''); }); test('handles empty name', () => { const name: HumanName = {}; expect(formatHumanName(name)).toBe(''); }); test('handles undefined fields', () => { const name: HumanName = { family: undefined, given: undefined, }; expect(formatHumanName(name)).toBe(''); }); }); ",response 17,"import { GameState } from ""./models/GameState.ts""; import BulletController from ""./controllers/BulletController.ts""; import EnemyController from ""./controllers/EnemyController.ts""; import Player from ""./models/Player.ts""; const background = new Image(); background.src = ""assets/images/background.jpg""; export class GameEngine { private lastFrameTime = 0; private readonly targetFPS = 60; private readonly targetFrameTime = 1000 / this.targetFPS; private gameState: GameState; private playerBulletController: BulletController; private enemyBulletController: BulletController; private enemyController: EnemyController; private player: Player; constructor( private canvas: HTMLCanvasElement, private ctx: CanvasRenderingContext2D, ) { this.gameState = new GameState(canvas, ctx); this.playerBulletController = new BulletController( canvas, 10, ""#d0620e"", true, ); this.enemyBulletController = new BulletController( canvas, 4, ""white"", false, ); this.enemyController = new EnemyController( canvas, this.enemyBulletController, this.playerBulletController, ); this.player = new Player(canvas, 3, this.playerBulletController); } start() { this.gameState.reset(); requestAnimationFrame(this.gameLoop); } private gameLoop = (timestamp: number) => { const deltaTime = timestamp - this.lastFrameTime; if (deltaTime >= this.targetFrameTime) { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); if (background.complete) { this.ctx.drawImage( background, 0, 0, this.gameState.canvas.width, this.gameState.canvas.height, ); } this.lastFrameTime = timestamp - (deltaTime % this.targetFrameTime); } if (!this.gameState.isGameOver) { this.update(); this.render(); requestAnimationFrame(this.gameLoop); } else { this.displayGameOver(); } }; private update() { this.enemyController.update(); this.player.update(); this.playerBulletController.update(); this.enemyBulletController.update(); if (this.enemyBulletController.collideWith(this.player)) { this.handlePlayerGameOver(); } } private render() { this.enemyController.draw(this.ctx); this.player.draw(this.ctx); this.playerBulletController.draw(this.ctx); this.enemyBulletController.draw(this.ctx); } // to implement on update(); private handlePlayerGameOver() { this.gameState.isGameOver = true; this.gameState.didWin = false; } private displayGameOver() { let text = this.gameState.didWin ? ""You Win"" : ""Game Over""; let [MASK] = this.gameState.didWin ? 3.5 : 5; this.ctx.fillStyle = ""white""; this.ctx.font = ""70px Arial""; this.ctx.fillText( text, this.gameState.canvas.width / [MASK] , this.gameState.canvas.height / 2, ); } } ",textOffset 18,"import { setRequestLocale } from 'next-intl/server'; import { notFound } from ""next/navigation""; import { buildIndexJSON } from ""@/blogs/post"" import { locales } from ""@/navigation"" export async function generateStaticParams() { return locales.map((locale) => ({locale})) } export async function GET(req: Request, [MASK] :{params: Promise<{locale:string}>}) { const params = await [MASK] .params; const { locale } = params; if (!locales.includes(locale as any)) notFound() setRequestLocale(locale) const json = await buildIndexJSON(locale) const buffer = Buffer.from(json, 'utf8') const headers = new Headers() headers.append('Content-Disposition', 'attachment; filename=""index.json""') headers.append('Content-Type', 'application/json') return new Response(buffer, {headers}) }",props 19,"import * as functions from ""firebase-functions""; import {initializeApp} from ""firebase-admin/app""; import {getFirestore} from ""firebase-admin/firestore""; const app = initializeApp(); const db = getFirestore(app); exports.assistantVotesCreatedListener = functions.firestore .document(""assistantVotes/{assistantVoteId}"") // eslint-disable-next-line @typescript-eslint/no-unused-vars .onCreate(async (doc) => { const batch = db.batch(); let assistantStatRef: FirebaseFirestore.DocumentReference; const assistantStats = await db.collection(""assistantStats"").get(); let likes = 0; let dislikes = 0; if (assistantStats.docs.length) { assistantStatRef = db.collection(""assistantStats"").doc(assistantStats.docs[0].id); likes = assistantStats.docs[0].data()?.likes || 0; dislikes = assistantStats.docs[0].data()?.dislikes || 0; } else { assistantStatRef = db.collection(""assistantStats"").doc(); } const assistantVote = doc.data(); const vote: null | boolean = typeof assistantVote?.vote === ""boolean"" ? assistantVote?.vote : null; if (vote === true) { likes += 1; } else if (vote === false) { dislikes += 1; } if (assistantStats.docs.length) { batch.update(assistantStatRef, { likes, dislikes, }); } else { batch.set(assistantStatRef, { likes, dislikes, }); } await batch.commit(); }); exports.assistantVotesUpdatedListener = functions.firestore .document(""assistantVotes/{assistantVoteId}"") // eslint-disable-next-line @typescript-eslint/no-unused-vars .onUpdate(async (change) => { const batch = db.batch(); let assistantStatRef: FirebaseFirestore.DocumentReference; const assistantStats = await db.collection(""assistantStats"").get(); let likes = 0; let dislikes = 0; if (assistantStats.docs.length) { assistantStatRef = db.collection(""assistantStats"").doc(assistantStats.docs[0].id); likes = assistantStats.docs[0].data()?.likes || 0; dislikes = assistantStats.docs[0].data()?.dislikes || 0; } else { assistantStatRef = db.collection(""assistantStats"").doc(); } const assistantVote = change.after.data(); const vote: null | boolean = typeof assistantVote?.vote === ""boolean"" ? assistantVote?.vote : null; if (vote === true) { likes += 1; } else if (vote === false) { dislikes += 1; } const [MASK] = change.before.data(); const _vote: null | boolean = typeof [MASK] ?.vote === ""boolean"" ? [MASK] ?.vote : null; if (_vote === true) { likes -= 1; } if (_vote === false) { dislikes -= 1; } if (assistantStats.docs.length) { batch.update(assistantStatRef, { likes, dislikes, }); } else { batch.set(assistantStatRef, { likes, dislikes, }); } await batch.commit(); }); ",pAssistantVote 20,"import { HANDLE_CHECKS } from ""./constants.js""; import logger from ""./logger.js""; import { createAccountReport, createAccountComment, createAccountLabel, } from ""./moderation.js""; export const checkHandle = async ( did: string, handle: string, time: number, ) => { // Get a list of labels const labels: string[] = Array.from( HANDLE_CHECKS, (handleCheck) => handleCheck.label, ); // iterate through the labels labels.forEach((label) => { const [MASK] = HANDLE_CHECKS.find( (handleCheck) => handleCheck.label === label, ); if ( [MASK] ?.ignoredDIDs) { if ( [MASK] .ignoredDIDs.includes(did)) { logger.info(`Whitelisted DID: ${did}`); return; } } if ( [MASK] !.check.test(handle)) { // False-positive checks if ( [MASK] ?.whitelist) { if ( [MASK] ?.whitelist.test(handle)) { logger.info(`Whitelisted phrase found for: ${handle}`); return; } } if ( [MASK] ?.toLabel === true) { logger.info(`[CHECKHANDLE]: Labeling ${did} for ${ [MASK] !.label}`); { createAccountLabel( did, `${ [MASK] !.label}`, `${time}: ${ [MASK] !.comment} - ${handle}`, ); } } if ( [MASK] ?.reportAcct === true) { logger.info(`[CHECKHANDLE]: Reporting ${did} for ${ [MASK] !.label}`); createAccountReport(did, `${time}: ${ [MASK] !.comment} - ${handle}`); } if ( [MASK] ?.commentAcct === true) { logger.info( `[CHECKHANDLE]: Commenting on ${did} for ${ [MASK] !.label}`, ); createAccountComment(did, `${time}: ${ [MASK] !.comment} - ${handle}`); } } }); }; ",checkList 21,"/* eslint-disable @typescript-eslint/no-explicit-any */ import { JestChrome } from ""jest-chrome/types/jest-chrome"" import { sendMessage } from ""./sendMessage"" describe(""sendMessage"", () => { it(""should send the message correctly"", async () => { const message: Message = { type: ""rating"", subType: ""get"" } const response: MessageResponse = { statusCode: 200, data: 2 } const jestChrome = chrome as any as JestChrome jestChrome.runtime.sendMessage.mockImplementation( (_message: any, callback: any) => { return callback(response) }, ) const [MASK] = await sendMessage(message) expect( [MASK] ).toEqual(2) expect(chrome.runtime.sendMessage).toHaveBeenCalledWith( message, expect.any(Function), ) }) it(""should resolve the promise if response success"", (done) => { const message: Message = { type: ""rating"", subType: ""get"" } const response: MessageResponse = { statusCode: 200, data: 2 } const jestChrome = chrome as any as JestChrome jestChrome.runtime.sendMessage.mockImplementation( (_message: any, callback: any) => { return callback(response) }, ) sendMessage(message).then((data) => { expect(data).toBe(2) done() }) }) it(""should reject the promise if response fails"", (done) => { const message: Message = { type: ""rating"", subType: ""get"" } const response: MessageResponse = { statusCode: 500, data: ""background script error"", } const jestChrome = chrome as any as JestChrome jestChrome.runtime.sendMessage.mockImplementation( (_message: any, callback: any) => { return callback(response) }, ) sendMessage(message).catch((error) => { expect(error).toBe(""background script error"") done() }) }) }) ",promiseResult 22,"import { BASE_URL, COUNTERS_ENDPOINT, LOGS_ENDPOINT, TIMERS_ENDPOINT, } from ""./constants""; import { ConsoleTransport, MonitoringAPITransport } from ""./transports""; /** * DEPRECATED: will be removed once versioning is handled */ class Logger { transports: ILoggingTransport[]; constructor(apiKey: string, [MASK] : boolean = false) { this.transports = []; this.transports.push( new MonitoringAPITransport({ apiKey: apiKey, loggerUrl: BASE_URL, logsEndpoint: LOGS_ENDPOINT, countersEndpoint: COUNTERS_ENDPOINT, timersEndpoint: TIMERS_ENDPOINT, }) ); if ( [MASK] ) this.transports.push(new ConsoleTransport()); } logMessage = (payload: MessagePayload) => { this.transports.forEach((transport) => { transport.logMessageAsync(payload); }); }; logCounter = (payload: CounterPayload) => { this.transports.forEach((transport) => { transport.logCounterAsync(payload); }); }; logTimer = (payload: TimerPayload) => { this.transports.forEach((transport) => { transport.logTimerAsync(payload); }); }; } export default Logger; ",useConsoleTransport 23,"import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { CommonModule } from './module/common/common.module'; import { AuthModule } from './module/auth/auth.module'; import { UserModule } from './module/user/user.module'; import { UserController } from './module/user/user.controller'; import { ProxyMiddleware } from './middleware/proxy.middleware'; import { ItemModule } from './module/item/item.module'; import { TeamModule } from './module/team/team.module'; import { CatalogModule } from './module/catalog/catalog.module'; import { PageModule } from './module/page/page.module'; import { AttachmentModule } from './module/attachment/attachment.module'; @Module({ imports: [ TypeOrmModule.forRoot({ type: 'sqlite', database: 'sqlite/showdoc.db.php', autoLoadEntities: true, }), CommonModule, AuthModule, UserModule, ItemModule, TeamModule, CatalogModule, PageModule, AttachmentModule, ], controllers: [AppController, UserController], providers: [AppService], }) export class AppModule implements NestModule { configure( [MASK] : MiddlewareConsumer) { [MASK] .apply(ProxyMiddleware).forRoutes('server/index.php'); } } ",consumer 24,"/* Copyright 2021 The Matrix.org Foundation C.I.C. 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. */ import { MatrixClient } from ""../../../src""; import { Room } from ""../../../src/models/room""; import { MatrixEvent } from ""../../../src/models/event""; import { UNSTABLE_MSC3089_BRANCH } from ""../../../src/@types/event""; import { EventTimelineSet } from ""../../../src/models/event-timeline-set""; import { EventTimeline } from ""../../../src/models/event-timeline""; import { MSC3089Branch } from ""../../../src/models/MSC3089Branch""; describe(""MSC3089Branch"", () => { let client: MatrixClient; // @ts-ignore - TS doesn't know that this is a type let indexEvent: MatrixEvent; let branch: MSC3089Branch; const branchRoomId = ""!room:example.org""; const fileEventId = ""$file""; const staticTimelineSets = {} as EventTimelineSet; const staticRoom = { getUnfilteredTimelineSet: () => staticTimelineSets, } as any as Room; // partial beforeEach(() => { // TODO: Use utility functions to create test rooms and clients client = { getRoom: (roomId: string) => { if (roomId === branchRoomId) { return staticRoom; } else { throw new Error(""Unexpected fetch for unknown room""); } }, }; indexEvent = { getRoomId: () => branchRoomId, getStateKey: () => fileEventId, }; branch = new MSC3089Branch(client, indexEvent); }); it('should know the file event ID', () => { expect(branch.id).toEqual(fileEventId); }); it('should know if the file is active or not', () => { indexEvent.getContent = () => ({}); expect(branch.isActive).toBe(false); indexEvent.getContent = () => ({ active: false }); expect(branch.isActive).toBe(false); indexEvent.getContent = () => ({ active: true }); expect(branch.isActive).toBe(true); indexEvent.getContent = () => ({ active: ""true"" }); // invalid boolean, inactive expect(branch.isActive).toBe(false); }); it('should be able to delete the file', async () => { const stateFn = jest.fn() .mockImplementation((roomId: string, eventType: string, content: any, stateKey: string) => { expect(roomId).toEqual(branchRoomId); expect(eventType).toEqual(UNSTABLE_MSC3089_BRANCH.unstable); // test that we're definitely using the unstable value expect(content).toMatchObject({}); expect(content['active']).toBeUndefined(); expect(stateKey).toEqual(fileEventId); return Promise.resolve(); // return value not used }); client.sendStateEvent = stateFn; const [MASK] = jest.fn().mockImplementation((roomId: string, eventId: string) => { expect(roomId).toEqual(branchRoomId); expect(eventId).toEqual(fileEventId); return Promise.resolve(); // return value not used }); client.redactEvent = [MASK] ; await branch.delete(); expect(stateFn).toHaveBeenCalledTimes(1); expect( [MASK] ).toHaveBeenCalledTimes(1); }); it('should know its name', async () => { const name = ""My File.txt""; indexEvent.getContent = () => ({ active: true, name: name }); const res = branch.getName(); expect(res).toEqual(name); }); it('should be able to change its name', async () => { const name = ""My File.txt""; indexEvent.getContent = () => ({ active: true, retained: true }); const stateFn = jest.fn() .mockImplementation((roomId: string, eventType: string, content: any, stateKey: string) => { expect(roomId).toEqual(branchRoomId); expect(eventType).toEqual(UNSTABLE_MSC3089_BRANCH.unstable); // test that we're definitely using the unstable value expect(content).toMatchObject({ retained: true, // canary for copying state active: true, name: name, }); expect(stateKey).toEqual(fileEventId); return Promise.resolve(); // return value not used }); client.sendStateEvent = stateFn; await branch.setName(name); expect(stateFn).toHaveBeenCalledTimes(1); }); it('should be able to return event information', async () => { const mxcLatter = ""example.org/file""; const fileContent = { isFile: ""not quite"", url: ""mxc://"" + mxcLatter }; const eventsArr = [ { getId: () => ""$not-file"", getContent: () => ({}) }, { getId: () => fileEventId, getContent: () => ({ file: fileContent }) }, ]; client.getEventTimeline = () => Promise.resolve({ getEvents: () => eventsArr, }) as any as Promise; // partial client.mxcUrlToHttp = (mxc: string) => { expect(mxc).toEqual(""mxc://"" + mxcLatter); return `https://example.org/_matrix/media/v1/download/${mxcLatter}`; }; client.decryptEventIfNeeded = () => Promise.resolve(); const res = await branch.getFileInfo(); expect(res).toBeDefined(); expect(res).toMatchObject({ info: fileContent, // Escape regex from MDN guides: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions httpUrl: expect.stringMatching(`.+${mxcLatter.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`), }); }); }); ",redactFn 25,"import {Body, Controller, ForbiddenException, Get, HttpCode, Inject, Post} from '@nestjs/common' import {LarkBotService} from './lark-bot.service' import {LARK_BOT} from './lark-bot.constants' import {BotMessageDto, SessionResponseDto} from './lark-bot.dto' @Controller('lark') export class LarkBotController { @Inject(LARK_BOT) private readonly botService: LarkBotService @Get('/options') async printOptions(): Promise { if (this.botService.options.debug) { return JSON.stringify(this.botService.options) } throw new ForbiddenException() } @Post('/callback') @HttpCode(200) async handleLarkRequest(@Body() [MASK] : BotMessageDto): Promise { if ( [MASK] .challenge) { return {challenge: [MASK] .challenge} } switch ( [MASK] .header.event_type) { case 'im.message.receive_v1': return this.botService.onMessage( [MASK] .event) default: } } } ",body 26,"/* eslint-disable no-console */ import * as jp from ""jsonpath""; import * as _ from ""lodash"" import payload from ""./payload""; const jsonPaths: Array = [ // '$', // '$.level_0_string', '$.name', '$.description', '$.packages[:].tour.itinerary', // '$.*' ]; const pathMap= {} const allPaths = [] jsonPaths.forEach((jpPath) => { const paths = jp.paths(payload, jpPath) allPaths.push(...paths) }); const orderedPaths = allPaths.sort((a, b) => a.length > b.length ? -1 : 1) for (const path of orderedPaths) { let node = pathMap for (let i = 0; i < path.length; i++) { const key = path[i]; if (node[key] === null) { break } if (node[key] === undefined) { if(i < path.length - 1 && typeof path[i+1] === 'number') { node[key] = []; } else { node[key] = {}; } } if (i === path.length - 1) { node[key] = null } else { node = node[key] } } } // console.log(JSON.stringify(pathMap, null, 2)) const contentCopy = { '$': _.cloneDeep(payload) }; const content = crop(contentCopy, pathMap) console.log(JSON.stringify(content, null, 2)) function crop(obj, [MASK] ) { if ( [MASK] === null) { return `Translate(de_DE, '${obj}')` } for (const key of Object.keys(obj)) { if (!(key in [MASK] )) { delete obj[key] } else { obj[key] = crop(obj[key], [MASK] [key]) } } return obj } ",keepMap 27,"import nodeHashcash from './index'; const sleep = (time: number) => new Promise(r => setTimeout(r, time)); describe('NodeHashcash', () => { const SECRET = 'my secret'; it('should generate random tokens', () => { const firstValue = nodeHashcash['generateToken'](8); const [MASK] = nodeHashcash['generateToken'](8); expect(firstValue).not.toBe( [MASK] ); }); it('should generate correct sized tokens', () => { const LENGTH = 8; const token = nodeHashcash['generateToken'](LENGTH); expect(token.length).toBe(LENGTH); }); it('should generate valid challenge', () => { const hardness = 7; const challenge = nodeHashcash.createChallenge(SECRET, { hardness }); const challengeObj = JSON.parse(Buffer.from(challenge, 'base64').toString('ascii')); expect(challengeObj.signature.length).toBe(16); expect(challengeObj.content.token.length).toBe(16); expect(challengeObj.content.hardness).toBe(hardness); expect(challengeObj.content.iat.length).not.toBe(0); }); it('should give the correct amount of solutions to a challenge', async () => { const hardness = 3; const challenge = nodeHashcash.createChallenge(SECRET, { hardness }); const solution = await nodeHashcash.solveChallenge(challenge); const solutions = JSON.parse(Buffer.from(solution, 'base64').toString('ascii')); expect(solutions.length).toBe(hardness); }); it('should update onProgress correctly', async () => { const updates = []; let last = -1; const hardness = 3; const challenge = nodeHashcash.createChallenge(SECRET, { hardness }); await nodeHashcash.solveChallenge(challenge, progress => { expect(progress).toBeGreaterThan(last); last = progress; updates.push(progress); }); expect(updates.length).toBe(hardness + 1); }); it('should validate correctly solved challenge', async () => { const hardness = 3; const challenge = nodeHashcash.createChallenge(SECRET, { hardness }); const solution = await nodeHashcash.solveChallenge(challenge); const isValid = nodeHashcash.validateChallenge(challenge, solution, SECRET); expect(isValid).toBe(true); }); it('should not validate wrong signature', async () => { const hardness = 3; const challenge = nodeHashcash.createChallenge(SECRET, { hardness }); const solution = await nodeHashcash.solveChallenge(challenge); const isValid = nodeHashcash.validateChallenge(challenge, solution, 'wrong secret'); expect(isValid).toBe(false); }); it('should not validate wrong solutions', async () => { const hardness = 3; const challenge = nodeHashcash.createChallenge(SECRET, { hardness }); const solution = Buffer.from(JSON.stringify(['0', '0', '0']), 'binary').toString('base64'); const isValid = nodeHashcash.validateChallenge(challenge, solution, SECRET); expect(isValid).toBe(false); }); it('should not validate expired solution', async () => { const hardness = 3; const challenge = nodeHashcash.createChallenge(SECRET, { hardness }); const solution = await nodeHashcash.solveChallenge(challenge); await sleep(200); const isValid = nodeHashcash.validateChallenge(challenge, solution, SECRET, { expiration: 200 }); expect(isValid).toBe(false); }); }); ",secondValue 28,"/** * @copyright 2017 * @license Apache License, Version 2.0 * @see NOTICE file */ import {Constructable} from '../types/constructable'; import {instantiateFactories} from './instantiate-factories'; import {InjectionRecord} from '../interfaces/injection-record'; import {InjectionCycleError} from '../errors/injection-cycle.error'; /** * Instantiates injections with their dependencies from given * injection records array. Throws errors when injection cycle * encountered or when injection factory internal error occurs. * * @param records {InjectionRecord[]} injection record array * * @return {Promise>} a WeakMap of * injection instances (asynchronous) * * @throws {InjectionCycleError} when an injection cycle encountered * @throws {InstantiationError} when an injection factory internal * error occurs, InstantiationError is rethrown */ export async function injectInternal( records: InjectionRecord[] ): Promise> { // selecting factory injections const factoryInjections = records.filter(record => { return !!record.factory; }); // getting factory injections map const [MASK] = await instantiateFactories(factoryInjections); // deleting instantiated factory injection records for (const record of records) { if ( [MASK] .has(record.constructor)) { const index = records.indexOf(record); records.splice(index, 1); } } // injecting & instantiating... while (records.length) { // selecting injections without registered dependencies const instantiationCandidates: InjectionRecord[] = []; for (const record of records) { let isCandidate: boolean = true; for (const dependency of record.dependencies) { const hasRegistered = records.some(r => { return r.constructor === dependency; }); if (hasRegistered) { isCandidate = false; break; } } if (isCandidate) { // to instantiation candidates instantiationCandidates.push(record); } } // no candidates - injection cycle if (instantiationCandidates.length === 0) { let injectionList: string = records[0].constructor.name; for (let i = 1; i < records.length; i++) { injectionList += '-' + records[i].constructor.name; } throw new InjectionCycleError( 'An injection cycle encountered among injections ' + injectionList); } // if there are instance candidates for (const candidate of instantiationCandidates) { const dependencies = candidate.dependencies; const args = []; for (const dependency of dependencies) { args.push( [MASK] .get(dependency)); } const instance = new candidate.constructor(...args); [MASK] .set(candidate.constructor, instance); const index = records.indexOf(candidate); records.splice(index, 1); } } return [MASK] ; } ",instanceMap 29,"import { Component, Input, ViewChild, Optional } from '@angular/core'; import { Color, BaseChartDirective } from 'ng2-charts'; import { FilterValues } from '../filter/filtervalues.model'; import { StatisticsSourceInterface } from '../../services/statistics-source.interface'; import { Subscription, Observable, Subject } from 'rxjs'; import { Dataset } from '../../mappers/dataset.model'; export enum StatusType { NoData, Loading, Loaded, Error } @Component({ selector: 'chart', templateUrl: './chart.component.html', styleUrls: ['./chart.component.css'] }) export class ChartComponent { @Input() public filterValues: Observable; @Input() public dataSource: StatisticsSourceInterface; @Input('seriesColours') set seriesColours(value: any[]) { this.colors = [{ backgroundColor: value }]; } @ViewChild(BaseChartDirective) chart: BaseChartDirective; private statisticsService: StatisticsSourceInterface; private filterValuesSubscription: Subscription; public chartType: string; public labels: string[] = []; public data: number[] = []; public colors: any[]; public options: any; public status: StatusType = StatusType.NoData; public statusType = StatusType; ngOnInit() { this.statisticsService = this.dataSource; this.subscribe(); } private subscribe(): void { this.filterValuesSubscription = this.filterValues .debounceTime(300) .distinctUntilChanged() .do(val => { if (val.clear === true) { this.status = StatusType.NoData; } }) .filter(val => val.clear !== true) .do(() => (this.status = StatusType.Loading)) .switchMap(val => this.statisticsService.getStatistics( val.beginDate, val.endDate, val.domainId ) ) .subscribe( (data: Dataset) => { if (data.series.length === 0) { this.status = StatusType.NoData; } else { this.updateChart(data); this.status = StatusType.Loaded; } }, (error: any) => { this.status = StatusType.Error; if (this.filterValuesSubscription) { this.filterValuesSubscription.unsubscribe(); this.filterValuesSubscription = null; } this.subscribe(); } ); } updateChart(data: Dataset) { this.chart.datasets = data.series; this.labels = data.labels; this.chart.datasets = data.series.map((item, [MASK] ) => { return { data: item.data, label: item.name, backgroundColor: this.colors[ [MASK] ] }; }); this.labels = data.labels; if (this.chart && this.chart.chart && this.chart.chart.config) { this.chart.chart.config.data.labels = this.labels; this.chart.chart.update(); } } ngOnDestroy() { this.filterValuesSubscription.unsubscribe(); } } ",index 30,"import { Logger } from '../logger/Logger'; /** * 适配屏幕工具类 */ export class FitScreenUtil { // 当前设计分辨率 private curDR: any = null; /** * 适配屏幕 * @param canvasNode 画布节点 */ fitScreen(canvasNode: cc.Node) { if (cc.sys.isNative) { this.fitNativeScreen(canvasNode); } if (cc.sys.platform === cc.sys.DESKTOP_BROWSER) { const resizeAction = () => { let cvs = canvasNode.getComponent(cc.Canvas); //保存原始设计分辨率,供屏幕大小变化时使用 if (!this.curDR) { this.curDR = cvs.designResolution; } let dr = this.curDR; let s = cc.view.getFrameSize(); let rw = s.width; let rh = s.height; let finalW = rw; let finalH = rh; if (rw / rh > dr.width / dr.height) { //!#zh: 是否优先将设计分辨率高度撑满视图高度。 */ //cvs.fitHeight = true; //如果更长,则用定高 finalH = dr.height; finalW = (finalH * rw) / rh; } else { /*!#zh: 是否优先将设计分辨率宽度撑满视图宽度。 */ //cvs.fitWidth = true; //如果更短,则用定宽 finalW = dr.width; finalH = (rh / rw) * finalW; } cvs.designResolution = cc.size(finalW, finalH); cvs.node.width = finalW; cvs.node.height = finalH; }; window.onresize = resizeAction; resizeAction(); } } /** * 原生适配 * @param canvasNode 画布节点 */ fitNativeScreen(canvasNode: cc.Node) { let size = cc.view.getFrameSize(); let aspect1 = size.height / size.width; let [MASK] = 16 / 9; var cvs = canvasNode.getComponent(cc.Canvas); if (!CC_BUILD) Logger.log( cc.sys.platform + ':::' + cc.sys.browserType + '::' + cc.sys.OS_IOS ); if (aspect1 > [MASK] && cc.sys.OS_IOS === 'iOS') { cvs.fitHeight = true; cvs.fitWidth = true; Logger.log('----------iphone notch screen-----------'); return; } else { cvs.fitHeight = false; cvs.fitWidth = true; } let frameSize = cc.view.getFrameSize(); let designSize = cc.view.getDesignResolutionSize(); if ( frameSize.width / frameSize.height > designSize.width / designSize.height ) { canvasNode.width = (designSize.height * frameSize.width) / frameSize.height; canvasNode.height = designSize.height; canvasNode.getComponent(cc.Canvas).designResolution = cc.size( canvasNode.width, canvasNode.height ); } else { canvasNode.width = designSize.width; canvasNode.height = (designSize.width * frameSize.height) / frameSize.width; canvasNode.getComponent(cc.Canvas).designResolution = cc.size( canvasNode.width, canvasNode.height ); } //this.fitScreenBackground(node, designSize); } /** * 背景适配 * @param canvasnode * @param designSize */ fitScreenBackground(canvasnode: any, designSize: any) { let scaleW = canvasnode.width / designSize.width; let scaleH = canvasnode.height / designSize.height; let bgNode = canvasnode.getChildByName('background'); if (!bgNode) return; let bgScale = canvasnode.height / bgNode.height; bgNode.width *= bgScale; bgNode.height *= bgScale; if (scaleW > scaleH) { bgScale = canvasnode.width / bgNode.width; bgNode.width *= bgScale; bgNode.height *= bgScale; } } } ",aspect2 31,"import { ServerResponse } from 'http' import { TOKEN_RENEW_LIMIT, DEVICES_COUNT_LIMIT, EXPIRATION_CHECK_INTERVAL, } from '@core/config' import { User } from '@core/core-types' import { createToken, parseToken } from '@core/token' import { setToken, unsetToken } from '@core/cookie' import { hashString } from '@core/tools' import { getUserByName, addUser } from './model/auth-model' const usersTokens: Map = new Map export const authorization = ( res: ServerResponse, token: string, ): number => { if (!token) { return null } const now = Date.now() const { id, expires } = parseToken(token) const userTokens = usersTokens.get(id) if (!userTokens || expires < now || !userTokens.includes(token)) { unsetToken(res) return null } if (expires - now < TOKEN_RENEW_LIMIT) { const newToken = createToken(id) const index = userTokens.indexOf(token) userTokens.splice(index, 1) userTokens.push(newToken) setToken(res, newToken) } return id } export const authentication = async ( res: ServerResponse, name: string, password: string, ): Promise => { const user = await getUserByName(name) if (!user || user.password != hashString(user.name + password)) { return null } if (!usersTokens.has(user.id)) { usersTokens.set(user.id, []) } const tokens = usersTokens.get(user.id) const token = createToken(user.id) tokens.push(token) while (tokens.length > DEVICES_COUNT_LIMIT) { tokens.shift() } setToken(res, token) return user } export const registration = async ( res: ServerResponse, name: string, password: string, ): Promise => { const user = await getUserByName(name) if (user) { return null } const hashPassword = hashString(name + password) const id = await addUser(name, hashPassword) const token = createToken(id) usersTokens.set(id, [token]) setToken(res, token) return id } export const logOut = ( res: ServerResponse, [MASK] : number, token: string, mode: string, ): void => { // Токен точно существует, т.к. клиент авторизован по нему const tokens = usersTokens.get( [MASK] ) const tokenIndex = tokens.indexOf(token) switch (mode) { case 'this': tokens.splice(tokenIndex, 1) unsetToken(res) break case 'all': usersTokens.delete( [MASK] ) unsetToken(res) break case 'others': tokens.length = 0 tokens.push(token) break } } const expirationCheck = () => { const now = Date.now() usersTokens.forEach((tokens, key) => { const aliveTokens = tokens.filter(token => { const { expires } = parseToken(token) return now < expires }) if (tokens.length == aliveTokens.length) { return } if (!aliveTokens.length) { usersTokens.delete(key) return } usersTokens.set(key, aliveTokens) }) } setInterval(expirationCheck, EXPIRATION_CHECK_INTERVAL) ",userId 32,"import {IRepository} from ""./interfaces/repository.interface.js""; import {User} from ""../domain/user.js""; import {Bet} from ""../domain/bet.js""; import {Dice} from ""../domain/dice.js""; export class CreateBetUseCase { constructor(private userRepository: IRepository, private betRepository: IRepository) { } async execute(userId: number, betAmount: number, chance: number): Promise { const user = await this.userRepository.findOneById(userId); if (!user) { throw new Error('User not found'); } let bet: Bet = Bet.createWithoutId({ userId: user.id, betAmount, chance, payout: betAmount * 2 }); let [MASK] = bet.placeBet(user.balance, new Dice()) // TODO: Potentially better to handle as a single transaction await this.userRepository.updateOneById(user.id, { balance: [MASK] }); bet = await this.betRepository.createOne(bet); return bet; } }",updatedBalance 33,"import { AbstractCommandModule, Message } from ""botyo-api""; const Spotify = require('spotify-web-api-node'); export default class SpotifyCommand extends AbstractCommandModule { private readonly market: string; private readonly spotify: any; private readonly authPromise: Promise; private tokenExpiryTimestamp: number; constructor() { super(); this.market = this.getRuntime().getConfiguration().getProperty(""market""); this.spotify = new Spotify({ clientId: this.getRuntime().getConfiguration().getProperty(""clientId""), clientSecret: this.getRuntime().getConfiguration().getProperty(""clientSecret"") }); this.authPromise = this.authenticateSpotify(); } getCommand(): string { return ""spotify""; } getDescription(): string { return ""Posts a Spotify song in the chat""; } getUsage(): string { return """"; } validate(msg: Message, args: string): boolean { return args.length > 0; } async execute(msg: Message, args: string): Promise { await this.authPromise; await this.refreshSpotifyToken(); const data = await this.spotify.searchTracks(args, { market: this.market, limit: 1 }); if (!data.body || !data.body.tracks || !data.body.tracks.items) { throw new Error(""Could not parse Spotify response""); } if (data.body.tracks.items.length === 0) { return this.getRuntime().getChatApi().sendMessage(msg.threadID, ""Sorry, I couldn't find this track. :/""); } const track = data.body.tracks.items[0]; const trackUrl = track.external_urls.spotify; const artists = track.artists.map((a: any) => a.name).join("", ""); const response = `\u{1F3B5} ${track.name} by ${artists}\n` + `\u{1F517} Play now: ${trackUrl}`; return this.getRuntime().getChatApi().sendMessage(msg.threadID, { url: trackUrl, body: response }); } private async authenticateSpotify(): Promise { const logger = this.getRuntime().getLogger(); return this.spotify.clientCredentialsGrant() .then((data: any) => { // Save the access token so that it's used in future calls const accessToken = data.body['access_token']; const refreshToken = data.body['refresh_token']; const [MASK] = data.body['expires_in']; this.spotify.setAccessToken(accessToken); this.spotify.setRefreshToken(refreshToken); this.tokenExpiryTimestamp = Date.now() + [MASK] * 1000; logger.verbose(`The access token expires in ${ [MASK] }`); logger.verbose(`The access token is ${accessToken}`); logger.verbose(`The refresh token is ${refreshToken}`); }) .catch((err: any) => { logger.error('Something went wrong when retrieving an access token', err); }); } private async refreshSpotifyToken(): Promise { const logger = this.getRuntime().getLogger(); if (Date.now() < this.tokenExpiryTimestamp) { return; } try { const data = await this.spotify.refreshAccessToken(); this.spotify.setAccessToken(data.body['access_token']); } catch (err) { logger.warn('Could not refresh access token. Will try to re-authenticate...', err); return this.authenticateSpotify(); } logger.verbose('The access token has been refreshed!'); } }",tokenExpiresIn 34,"import type { UseQueryStoreResult, MutationStoreResult, } from '@sveltestack/svelte-query'; import { QueryClient, useQuery, useMutation } from '@sveltestack/svelte-query'; import { getVersion } from '@tauri-apps/api/app'; import { appDir } from '@tauri-apps/api/path'; import { type FsOptions, readTextFile, createDir } from '@tauri-apps/api/fs'; export const APPLICATION_NAMESPACE = 'latreutes'; export const QUERY_KEY_CONFIG = [APPLICATION_NAMESPACE, 'config']; // Utils async function readFile(path: string, options?: FsOptions) { const fileContents = await readTextFile(path, options); if (fileContents) { return fileContents; } throw new Error('Empty file!'); } // Queries // App Version const QUERY_KEY_VERSION = [APPLICATION_NAMESPACE, 'version']; export const useVersion = (): UseQueryStoreResult< string, unknown, string, string[] > => useQuery(QUERY_KEY_VERSION, getVersion, { staleTime: Infinity, cacheTime: Infinity, }); // Config Directory const QUERY_KEY_CONFIG_PATH = [...QUERY_KEY_CONFIG, 'path']; export const useConfigPath = (): UseQueryStoreResult< string, unknown, string, string[] > => useQuery(QUERY_KEY_CONFIG_PATH, appDir, { staleTime: Infinity, cacheTime: Infinity, }); export const useConfigDirMaker = (): MutationStoreResult => useMutation(async () => { const configPath = await appDir(); await createDir(configPath, { recursive: true }); }); // ZeroTier Auth Token export const AUTHTOKEN_FILENAME = 'authtoken.secret'; const QUERY_KEY_ZT = [...QUERY_KEY_CONFIG, 'zt']; const QUERY_KEY_AUTHTOKEN = [...QUERY_KEY_ZT, 'authtoken']; export const useAuthToken = ( configDirPath?: string, ): UseQueryStoreResult => useQuery( QUERY_KEY_AUTHTOKEN, async () => { if (configDirPath === undefined) { throw Error('Missing directory path for authtoken.secret file!'); } const [MASK] = `${configDirPath}${AUTHTOKEN_FILENAME}`; const fileContents = await readFile( [MASK] ); return fileContents.trim(); }, { enabled: !!configDirPath, retry: false, retryOnMount: false, // if this is true, the query will always retry instantly in a svelte component with transitions, blocking other work refetchOnWindowFocus: false, staleTime: Infinity, cacheTime: Infinity, }, ); export const invalidateAuthTokenCache = (queryClient: QueryClient): void => { void queryClient.invalidateQueries(QUERY_KEY_AUTHTOKEN, { refetchInactive: true, }); }; ",filePath 35,"import * as assert from 'assert'; import * as vscode from 'vscode'; import { getDocUri, activate } from './helper'; // You can import and use all API from the 'vscode' module // as well as import your extension to test it // import * as myExtension from '../../extension'; suite('Extension Test Suite', function () { vscode.window.showInformationMessage('Start all tests.'); this.timeout(20000); const diagnosdoc1 = getDocUri('one.sol'); test('Testing for Row and Col pos.', async () => { await testdiagnos(diagnosdoc1, [ { message: `unrecognised token 'aa', expected "";"", ""=""`, range: toRange(4, 0, 5, 2), severity: vscode.DiagnosticSeverity.Error, source: 'solidity', }, ]); }); this.timeout(20000); const diagnosdoc2 = getDocUri('two.sol'); test('Testing for diagnostic errors.', async () => { await testdiagnos(diagnosdoc2, [ { message: `unrecognised token '}', expected ""!"", ""("", ""+"", ""++"", ""-"", ""--"", ""["", ""address"", ""bool"", ""byte"", ""bytes"", ""case"", ""default"", ""delete"", ""error"", ""false"", ""function"", ""leave"", ""mapping"", ""new"", ""payable"", ""revert"", ""string"", ""switch"", ""this"", ""true"", ""type"", ""~"", Bytes, Int, Uint, address, hexnumber, hexstring, identifier, number, rational, string`, range: toRange(13, 1, 13, 2), severity: vscode.DiagnosticSeverity.Error, source: 'solidity', }, ]); }); this.timeout(20000); const diagnosdoc3 = getDocUri('three.sol'); test('Testing for diagnostic info.', async () => { await testdiagnos(diagnosdoc3, []); }); this.timeout(20000); const diagnosdoc4 = getDocUri('four.sol'); test('Testing for diagnostics warnings.', async () => { await testdiagnos(diagnosdoc4, [ { message: `unknown pragma 'foo' with value 'bar' ignored`, range: toRange(0, 0, 0, 14), severity: vscode.DiagnosticSeverity.Warning, source: `solidity`, }, { message: `function can be declared 'pure'`, range: toRange(3, 5, 3, 40), severity: vscode.DiagnosticSeverity.Warning, source: `solidity`, }, ]); }); // Tests for hover. this.timeout(20000); const hoverdoc1 = getDocUri('hover1.sol'); test('Testing for Hover', async () => { await testhover(hoverdoc1); }); }); function toRange( [MASK] : number, charno1: number, lineno2: number, charno2: number) { const start = new vscode.Position( [MASK] , charno1); const end = new vscode.Position(lineno2, charno2); return new vscode.Range(start, end); } async function testhover(docUri: vscode.Uri) { await activate(docUri); const pos1 = new vscode.Position(74, 14); const actualhover = (await vscode.commands.executeCommand( 'vscode.executeHoverProvider', docUri, pos1 )) as vscode.Hover[]; const contentarr1 = actualhover[0].contents as vscode.MarkdownString[]; assert.strictEqual(contentarr1[0].value, '(mapping(address => uint256))'); const pos2 = new vscode.Position(78, 19); const actualhover2 = (await vscode.commands.executeCommand( 'vscode.executeHoverProvider', docUri, pos2 )) as vscode.Hover[]; const contentarr2 = actualhover2[0].contents as vscode.MarkdownString[]; assert.strictEqual( contentarr2[0].value, '```\nevent SimpleAuction.HighestBidIncreased {\n\taddress bidder,\n\tuint256 amount\n};\n```\n' ); const pos3 = new vscode.Position(53, 13); const actualhover3 = (await vscode.commands.executeCommand( 'vscode.executeHoverProvider', docUri, pos3 )) as vscode.Hover[]; const contentarr3 = actualhover3[0].contents as vscode.MarkdownString[]; assert.strictEqual(contentarr3[0].value, '[built-in] void require (bool): Abort execution if argument evaulates to false'); } async function testdiagnos(docUri: vscode.Uri, expecteddiag: vscode.Diagnostic[]) { await activate(docUri); const actualDiagnostics = vscode.languages.getDiagnostics(docUri); if (actualDiagnostics) { expecteddiag.forEach((expectedDiagnostic, i) => { const actualDiagnostic = actualDiagnostics[i]; assert.strictEqual(actualDiagnostic.message, expectedDiagnostic.message); assert.deepStrictEqual(actualDiagnostic.range, expectedDiagnostic.range); assert.strictEqual(actualDiagnostic.severity, expectedDiagnostic.severity); }); } else { console.error('the diagnostics are incorrect', actualDiagnostics); } } ",lineno1 36,"import { Item } from ""../../components/products/item""; const items = new Array( { id: 1, name: ""Gura phone case"", description: ""A Gawr Gura phone case, damn gura is too smart "", img_cover: ""https://i.pinimg.com/originals/71/96/cf/7196cfdf85e22579fe08e82385d4061a.png"", fav: true, }, { id: 2, name: ""Sonata 2005"", description: ""Sonata 2005 new only 150.000 kilómetros"", img_cover: ""https://i1.wp.com/criticalcarcare.com/wp-content/uploads/2019/08/Hyundai-sonata-autobody-repair-1.jpg?ssl=1"", fav: false, }, { id: 3, name: """", description: ""awesome figure of pekora"", img_cover: ""https://www.nendoworld.com/wp-content/uploads/2021/06/c9b8a3ea6e07fe76bd5eb18d16746301.jpg"", fav: true, } ); export default function handler( [MASK] , res) { if ( [MASK] .method === ""POST"") { const view = JSON.parse( [MASK] .body); res.json(items[view.id - 1]); } else if ( [MASK] .method === ""GET"") { res.json(items); } else { // Handle any other HTTP method } } ",req 37,"import { createSlice, createAsyncThunk, createEntityAdapter } from '@reduxjs/toolkit'; import { Book, getBookList } from 'src/apis/booksApi'; import { RootState } from '../store'; const booksAdapter = createEntityAdapter(); interface InitialState { status: 'idle' | 'loading' | 'succeeded' | 'failed'; error: any; filter: { categoryId?: number; size?: number; page?: number; }; } const initialState = booksAdapter.getInitialState({ status: 'idle', error: null, filter: { categoryId: undefined, size: 10, page: undefined, }, }); export const getBookListAsync = createAsyncThunk( 'books/getBookListAsync', async (_, { getState }) => { const state = getState() as RootState; if (!state.books.filter.categoryId) { booksAdapter.setAll(state.books, []); throw new Error('No categoryId'); } const [MASK] = await getBookList(state.books.filter); // The value we return becomes the `fulfilled` action payload return [MASK] .data; }, ); export const booksSlice = createSlice({ name: 'books', initialState, reducers: { setBooksFilter( state, action: { type: string; payload: { categoryId?: number; size?: number; page?: number } }, ) { const { categoryId, size, page } = action.payload; state.filter.categoryId = categoryId; state.filter.size = size; state.filter.page = page; }, }, extraReducers: (builder) => { builder .addCase(getBookListAsync.pending, (state) => { state.status = 'loading'; }) .addCase(getBookListAsync.fulfilled, (state, action) => { state.status = 'succeeded'; booksAdapter.setAll(state, action); }) .addCase(getBookListAsync.rejected, (state, action) => { state.status = 'failed'; state.error = action.error.message; }); }, }); export const { setBooksFilter } = booksSlice.actions; export const getBooksFilter = (state: RootState) => state.books.filter; export const { selectAll: selectAllBooks, selectById: selectBookById, selectEntities: selectBooksEntities, } = booksAdapter.getSelectors((state) => state.books); ",response 38,"import axios from 'axios'; import { Message as DiscordMessage, Channel as DiscordChannel, } from 'discord.js'; import { axiosErrorHandler } from './errorHandler'; const { DISCORD_BOT_TOKEN = '' } = process.env; const headers = { Authorization: `Bot ${DISCORD_BOT_TOKEN}`, 'Content-Type': 'application/json', }; const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); export const postMessage = async ( channelId: string, message: string, ): Promise => { try { const url = `https://discord.com/api/channels/${channelId}/messages`; const body = { content: message }; const config = { headers }; const response = await axios.post(url, body, config); await delay(1000); // prevent rate limit error return response.data as DiscordMessage; } catch (error) { if (axios.isAxiosError(error)) axiosErrorHandler(error); throw error; } }; export const postRawMessage = async ( channelId: string, object: any, ): Promise => { try { const url = `https://discord.com/api/channels/${channelId}/messages`; const config = { headers }; const response = await axios.post(url, object, config); await delay(1000); // prevent rate limit error return response.data as DiscordMessage; } catch (error) { if (axios.isAxiosError(error)) axiosErrorHandler(error); throw error; } }; export const postNewThread = async ( channelId: string, messageId: string, channelName: string, message1: string, message2: string, [MASK] : string, ): Promise => { try { // create new thread const url = `https://discord.com/api/channels/${channelId}/messages/${messageId}/threads`; const body = { name: channelName }; const config = { headers }; const response = await axios.post(url, body, config); await delay(1000); // prevent rate limit error // post message const threadChannel = response.data as DiscordChannel; await postMessage(threadChannel.id, message1); await delay(1000); await postMessage(threadChannel.id, message2); await delay(1000); if ( [MASK] .length > 0) { await postMessage(threadChannel.id, [MASK] ); await delay(1000); } } catch (error) { if (axios.isAxiosError(error)) axiosErrorHandler(error); throw error; } }; export default { postMessage }; ",message3 39,"import * as React from 'react'; import * as ReactDom from 'react-dom'; import { Version } from '@microsoft/sp-core-library'; import { IPropertyPaneConfiguration, PropertyPaneTextField, PropertyPaneToggle } from '@microsoft/sp-property-pane'; import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base'; import {CoundDownToRefresh} from ""./components/CountDownToRefresh""; import * as strings from 'CountDownToRefreshWebPartStrings'; import { ICountDownToRefreshProps } from './components/ICountDownToRefreshProps'; export interface ICountDownToRefreshWebPartProps { minutes: number; seconds:number; autostart:boolean; } export default class CountDownToRefreshWebPart extends BaseClientSideWebPart { public render(): void { if(this.properties.minutes === undefined){ this.properties.minutes = 0; } if(this.properties.seconds === undefined){ this.properties.seconds = 60; } if(this.properties.autostart === undefined){ this.properties.autostart = true; } const [MASK] : React.ReactElement = React.createElement( CoundDownToRefresh, { minutes: this.properties.minutes, seconds: this.properties.seconds, autostart: this.properties.autostart } ); ReactDom.render( [MASK] , this.domElement); } protected onDispose(): void { ReactDom.unmountComponentAtNode(this.domElement); } protected get dataVersion(): Version { return Version.parse('1.0'); } protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { return { pages: [ { header: { description: strings.PropertyPaneDescription }, groups: [ { groupName: strings.BasicGroupName, groupFields: [ PropertyPaneTextField('minutes', { label: strings.MinutesToRefreshFieldLabel },), PropertyPaneTextField('seconds', { label: strings.SecondsToRefreshFieldLabel },), PropertyPaneToggle('autostart', { label: strings.AutoStartLabel, onText: strings.StartOnText, offText: strings.StartOffText, },), ] } ] } ] }; } } ",element 40,"import * as secp from ""https://deno.land/x/secp256k1/mod.ts""; import { Buffer } from ""https://deno.land/std/node/buffer.ts""; async function test() { const [MASK] = Buffer.alloc(32); var i = 0; for (i = 0; i < [MASK] .length; i++) { [MASK] [i] = Math.random() * 256; } //.toString(""hex""); console.log( `${ [MASK] .toString(""hex"").length} , ${ [MASK] .toString(""hex"")}` ); const messageHash = ""9c1185a5c5e9fc54612808977ee8f548b2258d31""; const publicKey = secp.getPublicKey( [MASK] .toString(""hex"")); console.log(`pubkey ${publicKey.length}, ${publicKey} `); const signature = await secp.sign(messageHash, [MASK] ); const isSigned = secp.verify(signature, messageHash, publicKey); console.log(`signature ${signature}`); } test().then((result) => { console.log(`ok`); }); ",privateKey 41,"import ""./index.css""; import Stats from ""stats.js""; import * as BABYLON from ""@babylonjs/core""; //import ""@babylonjs/loaders/glTF""; import Level from ""./level""; class Game { private static mInstance: Game | null = null; mStats: Stats | null = null; //mLog: Log | null = null; mEngine: BABYLON.Engine | BABYLON.WebGPUEngine | null = null; mLevel: Level | null = null; static Instance() { if (!Game.mInstance) { Game.mInstance = new Game(); // ... any one time initialization goes here ... } return Game.mInstance; } async Init( [MASK] : HTMLCanvasElement, logElement: HTMLDivElement): Promise { this.mStats = new Stats(); this.mStats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom document.body.appendChild(this.mStats.dom); //this.mLog = new Log(logElement); const antialias = true; const adaptToDeviceRatio = true; if (navigator.gpu) { // load the 3D engine this.mEngine = new BABYLON.WebGPUEngine( [MASK] , { antialias, adaptToDeviceRatio }); await (this.mEngine as BABYLON.WebGPUEngine).initAsync(); } else { this.mEngine = new BABYLON.Engine( [MASK] , antialias, {}, adaptToDeviceRatio); } // call the createScene function this.mLevel = new Level(); this.mLevel.Init(this.mEngine); //this.mLevel.Init(this.mEngine, this.mLog); this.mEngine.runRenderLoop(() => { this.mStats?.begin(); this.mLevel?.Step(); this.mLevel?.Render(); this.mStats?.end(); //this.mLog.Display(); }); // // the canvas/window resize event handler // window.addEventListener(""resize"", () => { // this.mEngine.resize(); // }); } OnKeyDown(event: KeyboardEvent): void { this.mLevel?.OnKeyDown(event); } OnKeyUp(event: KeyboardEvent): void { this.mLevel?.OnKeyUp(event); } } export default Game; ",canvasElement 42,"import { createClient } from 'microcms-js-sdk'; export type worksItem = { id: string; createdAt: string; updatedAt: string; publishedAt: string; revisedAt: string; title: string; thumbnail: { url: string; height: number; width: number; }; isWorks: string[]; // ""is-works"" のハイフンをキャメルケースに変換 creationTime: number; // ""creation-time"" releaseDate: string; // ISO8601形式の日時 part: string; about: string; point: string; movie: string; // HTML文字列 background: string; concept: string; process: string; // HTML文字列 note: string; photos: string[]; // 配列だが、要素がない }; if (!process.env.SERVICE_ENDPOINT) { throw new Error(""MICROCMS_SERVICE_ENDPOINT is required""); } if (!process.env.API_KEY) { throw new Error(""MICROCMS_SERVICE_DOMAIN is required""); } console.log(""Fetching from:"", process.env.SERVICE_ENDPOINT); export const client = createClient({ serviceDomain: process.env.SERVICE_ENDPOINT, apiKey: process.env.API_KEY, }); // ブログ一覧を取得 export const getItems = async () => { const blogs = await client.getList({ endpoint: ""works"" }); return blogs; } // ブログの詳細を取得 export const getDetail = async (contentId: string) => { const [MASK] = await client.getListDetail({ endpoint: ""works"", contentId, }); return [MASK] ; }; ",item 43,"import { Component } from '@angular/core'; import { MyRandomNumberComponent } from './my.random.number.component'; import { DefaultService } from 'hello-world-api/api/default.service'; import { HelloWorldResponse } from 'hello-world-api/model/helloWorldResponse'; // HttpClient lives in a separate Angular module, so we'll need to import it in our main application module before we can use it. import { Observable } from 'rxjs/Observable'; import {ErrorResponse} from 'hello-world-api/model/errorResponse'; import {HttpErrorResponse, HttpResponse} from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; value: string; helloWorldResponse: HelloWorldResponse; public myRandomNumberComponent: MyRandomNumberComponent; constructor(private defaultService: DefaultService) { this.myRandomNumberComponent = new MyRandomNumberComponent(); } showMyRandomNumber() { return this.myRandomNumberComponent.doit(); } // https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular // Observables are lazy so you have to subscribe to get the value. helloWorldGet() { let [MASK] = null; if (this.value) { [MASK] = this.value; } // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS // https://www.chromestatus.com/feature/5629709824032768 this.defaultService .sayHello( [MASK] , 'response', false) .subscribe( (helloWorldResponse: HttpResponse) => { this.helloWorldResponse = helloWorldResponse.body; console.log(helloWorldResponse); }, (httpErrorResponse: HttpErrorResponse) => { console.log(httpErrorResponse); }, () => { console.log(this.defaultService); }); } helloWorldGetMessage() { return this.helloWorldResponse && this.helloWorldResponse.message; } } ",tmpName 44,"import * as iam from '@aws-cdk/aws-iam'; import * as lambda from '@aws-cdk/aws-lambda'; import * as logs from '@aws-cdk/aws-logs'; import * as cdk from '@aws-cdk/core'; // eslint-disable-next-line import/prefer-default-export export class Mem2CwStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, [MASK] ?: cdk.StackProps) { super(scope, id, [MASK] ); const mem2cwFn = new lambda.Function(this, 'mem2cw-function', { code: lambda.Code.fromAsset('src/lambda'), handler: 'mem2cw.handler', runtime: lambda.Runtime.NODEJS_12_X, logRetention: logs.RetentionDays.ONE_YEAR, timeout: cdk.Duration.seconds(3), }); mem2cwFn.addToRolePolicy( new iam.PolicyStatement({ actions: ['cloudwatch:PutMetricData'], effect: iam.Effect.ALLOW, resources: ['*'], }), ); this.mem2cwFn = mem2cwFn; } mem2cwFn: lambda.IFunction; } ",props 45,"/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ Copyright 2020 Adobe Systems Incorporated ~ ~ 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. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ import {ComponentFixture, TestBed} from '@angular/core/testing'; import {BrowserDynamicTestingModule} from '@angular/platform-browser-dynamic/testing'; import {ButtonV1Component} from './button.v1.component'; import {RouterTestingModule} from ""@angular/router/testing""; import {RouterLinkWithHref} from ""@angular/router""; import {By} from ""@angular/platform-browser""; import {AemAngularCoreWcmComponentsCore,MetaUtils} from ""@adobe/aem-core-components-angular-base/core""; describe('ButtonV1Component', () => { let component: ButtonV1Component; let fixture: ComponentFixture; let isInEditorSpy; beforeEach(() => { isInEditorSpy = spyOn(MetaUtils,'isInEditor').and.returnValue(false); TestBed.configureTestingModule({ declarations: [ ButtonV1Component ], imports: [ AemAngularCoreWcmComponentsCore, RouterTestingModule.withRoutes([]), ], }).overrideModule(BrowserDynamicTestingModule, { set: { entryComponents: [ButtonV1Component] } }).compileComponents(); fixture = TestBed.createComponent(ButtonV1Component); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create placeholder', () => { isInEditorSpy.and.returnValue(true); fixture.detectChanges(); const element = fixture.nativeElement; expect(element.querySelector('core-placeholder .cq-placeholder')).toBeDefined(); }); it('should not render the component', () => { isInEditorSpy.and.returnValue(false); fixture.detectChanges(); const element = fixture.nativeElement; expect(component.isEmpty).toBeTrue(); expect(element.querySelector('core-placeholder .cq-placeholder')).toBeNull(); }); it('render proper DOM - text', () => { isInEditorSpy.and.returnValue(false); component.ariaLabel = 'myarialabel'; component.icon = 'awesomeness'; component.text = 'mytext'; component.id = 'myId'; component.dataLayer = { ""testaccordion"": { ""test1"": ""test"", ""test2"": ""test"" } }; fixture.detectChanges(); const element = fixture.nativeElement; const button = element.querySelector('button#myId.cmp-button[data-cmp-data-layer][type=""button""]'); expect(button.getAttribute(""data-cmp-data-layer"")).toEqual('{""testaccordion"":{""test1"":""test"",""test2"":""test""}}'); expect(button.querySelector(""span.cmp-button__icon.cmp-button__icon--awesomeness"")).toBeDefined(); expect(button.querySelector(""span.cmp-button__text"").innerText).toEqual(""mytext""); }); it('should establish a routed link', () => { component.link = '/expectedUrl'; component.text = 'mytext'; component.routed = true; fixture.detectChanges(); const linkDebugEl = fixture.debugElement.query(By.css('a')); const [MASK] = linkDebugEl.injector.get(RouterLinkWithHref); expect( [MASK] ['commands']).toEqual(['/expectedUrl']); expect( [MASK] ['href']).toEqual('/expectedUrl'); }); it('should NOT establish a routed link but a normal link', () => { component.link = '/expectedUrl'; component.text = 'mytext'; component.routed = false; component.id = 'myId'; component.baseCssClass = 'cmp-my-button'; component.dataLayer = { ""testaccordion"": { ""test1"": ""test"", ""test2"": ""test"" } }; expect(component.isEmpty).toBeFalse(); fixture.detectChanges(); const linkDebugEl = fixture.debugElement.query(By.css('a')); expect(() => linkDebugEl.injector.get(RouterLinkWithHref)).toThrowError(); const element = fixture.nativeElement; const link = element.querySelector('a#myId.cmp-my-button[data-cmp-data-layer][href=""/expectedUrl""]'); expect(link.getAttribute(""data-cmp-data-layer"")).toEqual('{""testaccordion"":{""test1"":""test"",""test2"":""test""}}'); expect(link.querySelector(""span.cmp-my-button__icon.cmp-my-button__icon--awesomeness"")).toBeDefined(); expect(link.querySelector(""span.cmp-my-button__text"").innerText).toEqual(""mytext""); spyOn(component.clickRequest, 'emit'); link.dispatchEvent(new Event('click')); expect(component.clickRequest.emit).toHaveBeenCalled(); }); }); ",routerLinkInstance 46,"import initSections, { goToSection } from ""../sections""; import { allCardDataBase, UniqCard } from ""../cards""; import initClient from ""./thirdWebClient""; import initPrivateKey, { generateNewPrivateKey, setPrivateKey, getPublicKey, } from ""./keys""; import { checkFile, setFile, getDeckContent, saveFile } from ""./mu""; import initUI, { showPrivateKey, showPrivateKeyError, hidePrivateKeyError, renderCharacterList, setCardsInputValue, renderDeckIngredients, setCharacterName, } from ""./ui""; const gameURL = new URLSearchParams(window.location.search).get(""b"") || ""https://adrien-gueret.github.io/brewing_disaster/index.html""; (async () => { initClient( """" ); const privateKey = await initPrivateKey(); async function checkPrivateKey(onCheckFail: () => void) { const publicKey = await getPublicKey(); const isOK = await checkFile(publicKey); if (isOK) { goToSection(""list""); } else { setPrivateKey(""""); onCheckFail(); } } let editedName: string; let editedCards: string; const isEdit = () => Boolean(editedName) && Boolean(editedCards); initUI({ allIngredients: allCardDataBase.map(({ id }) => new UniqCard(id)), async onPrivateKeyEnter(key) { hidePrivateKeyError(); await setPrivateKey(key); checkPrivateKey(() => showPrivateKeyError()); }, onCancel() { window.location.href = gameURL; }, onIngredientAdded(newIngredientIds) { renderDeckIngredients(newIngredientIds.map((id) => new UniqCard(id))); }, async onDeckSaved(name, [MASK] ) { let fileContent = getDeckContent().split(""\n"").filter(Boolean); const newLine = `${name}|${ [MASK] }`; if (isEdit()) { const editedLine = `${editedName}|${editedCards}`; fileContent = fileContent.map((line) => { if (line !== editedLine) { return line; } return newLine; }); } else { fileContent.push(newLine); } goToSection(""saving""); await saveFile(fileContent); goToSection(""list""); }, }); initSections(({ nextSection, vars }) => { switch (nextSection) { case ""newPrivateKey"": generateNewPrivateKey().then(async (privateKey) => { const publicKey = await getPublicKey(); try { await setFile(publicKey, """"); showPrivateKey(privateKey); } catch (e) { setPrivateKey(""""); throw e; } }); break; case ""list"": { const userDeckContent = getDeckContent(); const customCharactersData = Boolean(userDeckContent) ? userDeckContent.split(""\n"") : []; const characters = customCharactersData.map((characterData) => { const [name, cards] = characterData.split(""|""); const editLink = document.createElement(""a""); editLink.href = ""#create""; editLink.className = ""inlineLink""; editLink.dataset.name = name; editLink.dataset.cards = cards; editLink.innerHTML = ""Edit""; const playLink = document.createElement(""button""); playLink.type = ""button""; playLink.className = ""inlineLink""; playLink.dataset.cards = cards; playLink.dataset.action = ""play""; playLink.innerHTML = ""Play""; const deleteLink = document.createElement(""button""); deleteLink.type = ""button""; deleteLink.className = ""inlineLink""; deleteLink.dataset.name = name; deleteLink.dataset.cards = cards; deleteLink.dataset.action = ""delete""; deleteLink.innerHTML = ""Delete""; return { id: ""totter"", name: name.replaceAll(""<"", ""<"").replaceAll("">"", "">""), desc: `${deleteLink.outerHTML} ${editLink.outerHTML} ${playLink.outerHTML}`, }; }); renderCharacterList([ { id: ""create"", name: ""Create character"", desc: ""And choose its starter ingredients"", href: ""#create"", }, ...characters, ]); break; } case ""create"": { editedName = vars.name || """"; editedCards = vars.cards || """"; setCardsInputValue(editedCards); setCharacterName(editedName); break; } } }); document.body.addEventListener(""click"", async (e) => { const clickedElement = e.target as HTMLElement; const { dataset } = clickedElement; switch (dataset.action) { case ""play"": { document.body.inert = true; window.location.href = `${gameURL}?d=${dataset.cards}#rules`; break; } case ""delete"": { const cardToRemove = clickedElement.closest("".card"") as HTMLDivElement; document.body.inert = true; cardToRemove.style.opacity = ""0.5""; try { const lineToDelete = `${dataset.name}|${dataset.cards}`; const fileContent = getDeckContent() .split(""\n"") .filter((line) => Boolean(line) && line !== lineToDelete); await saveFile(fileContent); cardToRemove.remove(); } finally { cardToRemove.style.opacity = ""1""; document.body.inert = false; } } } }); if (!privateKey) { goToSection(""askPrivateKey""); } else { checkPrivateKey(() => goToSection(""askPrivateKey"")); } })(); ",cardData 47,"import { collection, doc, addDoc, updateDoc, deleteDoc, getDoc, getDocs, query, where, orderBy, limit, startAfter, DocumentData, QueryDocumentSnapshot, serverTimestamp, Timestamp } from ""firebase/firestore""; import { db } from ""./firebase""; import { ReportPost, ReportThread, ReportPostWithChildren, GroupConfig } from ""../types""; const POSTS_PER_PAGE = 20; // Create a new thread export const createThread = async ( title: string, content: string, userId: string, userName: string, group?: string, recipient?: string, customName?: string, userPhotoURL?: string, priority?: string ): Promise => { try { const actualName = customName || userName; // Create the root post first const postRef = await addDoc(collection(db, ""posts""), { content, createdAt: serverTimestamp(), updatedAt: serverTimestamp(), authorId: userId, authorName: actualName, authorPhotoURL: userPhotoURL || null, parentId: null, threadId: ""temp"", // Will update after thread creation childrenIds: [], group: group || null, recipient: recipient || null, title: title, priority: priority || 'none' }); // Now create the thread with reference to root post const threadRef = await addDoc(collection(db, ""threads""), { title, createdAt: serverTimestamp(), authorId: userId, authorName: actualName, rootPostId: postRef.id, group: group || null, recipient: recipient || null }); // Update the post with the correct threadId await updateDoc(postRef, { threadId: threadRef.id }); return threadRef.id; } catch (error) { console.error(""Error creating thread:"", error); throw error; } }; // Create a new post (reply) export const createPost = async ( content: string, parentId: string, threadId: string, userId: string, userName: string, group?: string, recipient?: string, customName?: string, title?: string, userPhotoURL?: string, priority?: string ): Promise => { try { const actualName = customName || userName; // Create the new post const postRef = await addDoc(collection(db, ""posts""), { content, createdAt: serverTimestamp(), updatedAt: serverTimestamp(), authorId: userId, authorName: actualName, authorPhotoURL: userPhotoURL || null, parentId, threadId, childrenIds: [], group: group || null, recipient: recipient || null, title: title || null, priority: priority || 'none' }); // Update parent post's childrenIds array const parentRef = doc(db, ""posts"", parentId); const parentDoc = await getDoc(parentRef); if (parentDoc.exists()) { const parentData = parentDoc.data(); await updateDoc(parentRef, { childrenIds: [...(parentData.childrenIds || []), postRef.id] }); } return postRef.id; } catch (error) { console.error(""Error creating post:"", error); throw error; } }; // Get all threads with pagination export const getThreads = async (lastVisible?: QueryDocumentSnapshot): Promise<{ threads: ReportThread[]; lastVisible: QueryDocumentSnapshot | null; hasMore: boolean; }> => { try { let threadsQuery; if (lastVisible) { threadsQuery = query( collection(db, ""threads""), orderBy(""createdAt"", ""desc""), startAfter(lastVisible), limit(POSTS_PER_PAGE) ); } else { threadsQuery = query( collection(db, ""threads""), orderBy(""createdAt"", ""desc""), limit(POSTS_PER_PAGE) ); } const snapshot = await getDocs(threadsQuery); const threads: ReportThread[] = []; snapshot.forEach((doc) => { const data = doc.data(); threads.push({ id: doc.id, title: data.title, createdAt: (data.createdAt as Timestamp).toDate(), authorId: data.authorId, authorName: data.authorName, rootPostId: data.rootPostId, group: data.group || null, recipient: data.recipient || null }); }); const newLastVisible = snapshot.docs[snapshot.docs.length - 1] || null; const hasMore = snapshot.docs.length === POSTS_PER_PAGE; return { threads, lastVisible: newLastVisible, hasMore }; } catch (error) { console.error(""Error getting threads:"", error); throw error; } }; // Get a single thread by ID export const getThreadById = async (threadId: string): Promise => { try { const threadRef = doc(db, ""threads"", threadId); const threadDoc = await getDoc(threadRef); if (!threadDoc.exists()) { return null; } const data = threadDoc.data(); return { id: threadDoc.id, title: data.title, createdAt: (data.createdAt as Timestamp).toDate(), authorId: data.authorId, authorName: data.authorName, rootPostId: data.rootPostId, group: data.group || null, recipient: data.recipient || null }; } catch (error) { console.error(""Error getting thread:"", error); throw error; } }; // Get all posts for a thread with tree structure export const getPostsByThreadId = async (threadId: string): Promise => { try { // Get all posts for this thread const postsQuery = query( collection(db, ""posts""), where(""threadId"", ""=="", threadId) ); const snapshot = await getDocs(postsQuery); if (snapshot.empty) { return null; } // Convert to map for easy lookup const postsMap = new Map(); snapshot.forEach((doc) => { const data = doc.data(); postsMap.set(doc.id, { id: doc.id, content: data.content, createdAt: (data.createdAt as Timestamp).toDate(), updatedAt: (data.updatedAt as Timestamp).toDate(), authorId: data.authorId, authorName: data.authorName, authorPhotoURL: data.authorPhotoURL, parentId: data.parentId, threadId: data.threadId, childrenIds: data.childrenIds || [], group: data.group || null, recipient: data.recipient || null, title: data.title || null, priority: data.priority || null, children: [] }); }); // Build tree structure let rootPost: ReportPostWithChildren | null = null; // For each post postsMap.forEach((post) => { // If it's the root post if (post.parentId === null) { rootPost = post; } else { // Add this post to its parent's children const parent = postsMap.get(post.parentId); if (parent) { parent.children.push(post); } } }); return rootPost; } catch (error) { console.error(""Error getting posts:"", error); throw error; } }; // グループ関連の関数 // グループを作成 export const createGroup = async (name: string): Promise => { try { const groupRef = await addDoc(collection(db, ""groups""), { name, createdAt: serverTimestamp() }); return groupRef.id; } catch (error) { console.error(""Error creating group:"", error); throw error; } }; // グループ一覧を取得 export const getGroups = async (): Promise => { try { const groupsQuery = query( collection(db, ""groups""), orderBy(""name"", ""asc"") ); const snapshot = await getDocs(groupsQuery); const groups: GroupConfig[] = []; snapshot.forEach((doc) => { const data = doc.data(); groups.push({ id: doc.id, name: data.name, createdAt: (data.createdAt as Timestamp).toDate() }); }); return groups; } catch (error) { console.error(""Error getting groups:"", error); throw error; } }; // グループを更新 export const updateGroup = async (groupId: string, name: string): Promise => { try { const groupRef = doc(db, ""groups"", groupId); await updateDoc(groupRef, { name }); } catch (error) { console.error(""Error updating group:"", error); throw error; } }; // グループを削除 export const deleteGroup = async (groupId: string): Promise => { try { const groupRef = doc(db, ""groups"", groupId); await deleteDoc(groupRef); } catch (error) { console.error(""Error deleting group:"", error); throw error; } }; // スレッドと、そのスレッドに属するすべての投稿を取得する export const getThreadWithPosts = async (threadId: string): Promise<{thread: ReportThread, rootPost: ReportPostWithChildren} | null> => { try { const [thread, rootPost] = await Promise.all([ getThreadById(threadId), getPostsByThreadId(threadId), ]); if (!thread || !rootPost) { return null; } return { thread, rootPost }; } catch (error) { console.error(""Error getting thread with posts:"", error); throw error; } }; // すべてのスレッドと、それぞれのルート投稿を取得する export const getThreadsWithRootPosts = async ( [MASK] = 10): Promise<{thread: ReportThread, rootPost: ReportPostWithChildren}[]> => { try { // まずスレッドを取得 const threadsQuery = query( collection(db, ""threads""), orderBy(""createdAt"", ""desc""), limit( [MASK] ) ); const threadsSnapshot = await getDocs(threadsQuery); if (threadsSnapshot.empty) { return []; } // 各スレッドに対応するルート投稿を取得 const threadDataPromises = threadsSnapshot.docs.map(async (threadDoc) => { const threadData = threadDoc.data(); const thread: ReportThread = { id: threadDoc.id, title: threadData.title, createdAt: (threadData.createdAt as Timestamp).toDate(), authorId: threadData.authorId, authorName: threadData.authorName, rootPostId: threadData.rootPostId, group: threadData.group || null, recipient: threadData.recipient || null }; const rootPostId = threadData.rootPostId; // ルート投稿と返信を取得 const rootPost = await getPostsByThreadId(threadDoc.id); if (!rootPost) { return null; } return { thread, rootPost }; }); const threadDataResults = await Promise.all(threadDataPromises); // nullの結果をフィルタリング return threadDataResults.filter((result): result is {thread: ReportThread, rootPost: ReportPostWithChildren} => result !== null ); } catch (error) { console.error(""Error getting threads with root posts:"", error); throw error; } };",limitCount 48,"import { Component, OnInit, Injectable } from '@angular/core'; import { OhmIndexService } from '../ohm-index.service'; import {SelectionModel} from '@angular/cdk/collections'; import {FlatTreeControl} from '@angular/cdk/tree'; import {BehaviorSubject} from 'rxjs'; import {MatTreeFlatDataSource, MatTreeFlattener} from '@angular/material/tree'; export class TodoItemNode { children: TodoItemNode[]; item: string; } /** Flat to-do item node with expandable and level information */ export class TodoItemFlatNode { item: string; level: number; expandable: boolean; } /** * Checklist database, it can build a tree structured Json object. * Each node in Json object represents a to-do item or a category. * If a node is a category, it has children items and new items can be added under the category. */ @Injectable() export class ChecklistDatabase { dataChange = new BehaviorSubject([]); get data(): TodoItemNode[] { return this.dataChange.value; } constructor() { } initialize(TREE_DATA: any) { // Build the tree nodes from Json object. The result is a list of `TodoItemNode` with nested // file node as children. const data = this.buildFileTree(TREE_DATA, 0); // Notify the change. this.dataChange.next(data); } /** * Build the file structure tree. The `value` is the Json object, or a sub-tree of a Json object. * The return value is the list of `TodoItemNode`. */ buildFileTree(obj: {[key: string]: any}, level: number): TodoItemNode[] { return Object.keys(obj).reduce((accumulator, key) => { const value = obj[key]; const node = new TodoItemNode(); node.item = key; if (value != null) { if (typeof value === 'object') { node.children = this.buildFileTree(value, level + 1); } else { node.item = value; } } return accumulator.concat(node); }, []); } /** Add an item to to-do list */ insertItem(parent: TodoItemNode, name: string) { if (parent.children) { parent.children.push({item: name} as TodoItemNode); this.dataChange.next(this.data); } } updateItem(node: TodoItemNode, name: string) { node.item = name; this.dataChange.next(this.data); } } @Component({ selector: 'app-index', templateUrl: './index.component.html', styleUrls: ['./index.component.scss'], providers: [ChecklistDatabase] }) export class IndexComponent implements OnInit { /** Map from flat node to nested node. This helps us finding the nested node to be modified */ flatNodeMap = new Map(); /** Map from nested node to flattened node. This helps us to keep the same object for selection */ nestedNodeMap = new Map(); /** A selected parent node to be inserted */ selectedParent: TodoItemFlatNode | null = null; public treeControl: FlatTreeControl; treeFlattener: MatTreeFlattener; dataSource: MatTreeFlatDataSource; /** The selection for checklist */ checklistSelection = new SelectionModel(true /* multiple */); out; indices; selected = []; constructor( private ohm: OhmIndexService, private _database: ChecklistDatabase ) { this.treeFlattener = new MatTreeFlattener(this.transformer, this.getLevel, this.isExpandable, this.getChildren); this.treeControl = new FlatTreeControl(this.getLevel, this.isExpandable); this.dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener); _database.dataChange.subscribe(data => { this.dataSource.data = data; }); this.checklistSelection.changed.subscribe(data =>{ this.selected.push(...data.added); data.removed.forEach(x=>{ const c = this.selected.indexOf(x); if (c > -1){ this.selected.splice(c,1); } }) }) } getLevel = (node: TodoItemFlatNode) => node.level; isExpandable = (node: TodoItemFlatNode) => node.expandable; getChildren = (node: TodoItemNode): TodoItemNode[] => node.children; hasChild = (_: number, _nodeData: TodoItemFlatNode) => _nodeData.expandable; hasNoContent = (_: number, _nodeData: TodoItemFlatNode) => _nodeData.item === ''; spaceFilter = null; ngOnInit(): void { this.ohm.getIndices().subscribe(indices => { this.indices = indices; this.ohm.getIndex().subscribe((data: any) => { this.out = data; }); this._database.initialize(this.indices.trees); }) } get topics() { return Object.keys(this.indices.topics); } getIndex(y, t) { return this.out.filter(x=>{ return (x['interval'][0] === y[0]) && (x['interval'][1] === y[1]) && (x['topic'] === t); })[0].available; } iconFor(t) { return this.ohm.iconFor(t); } getReference(t){ return Object.keys(this.indices.topics[t]) } getFound(y,t){ return this.out.filter(x=>{ return (x['interval'][0] === y[0]) && (x['interval'][1] === y[1]) && (x['topic'] === t); })[0].subs } buildFileTree(obj: {[key: string]: any}, level: number): TodoItemNode[] { return Object.keys(obj).reduce((accumulator, key) => { const value = obj[key]; const node = new TodoItemNode(); node.item = key; if (value != null) { if (typeof value === 'object') { node.children = this.buildFileTree(value, level + 1); } else { node.item = value; } } return accumulator.concat(node); }, []); } /** * Transformer to convert nested node to flat node. Record the nodes in maps for later use. */ transformer = (node: TodoItemNode, level: number) => { const existingNode = this.nestedNodeMap.get(node); const flatNode = existingNode && existingNode.item === node.item ? existingNode : new TodoItemFlatNode(); flatNode.item = node.item; flatNode.level = level; flatNode.expandable = !!node.children?.length; this.flatNodeMap.set(flatNode, node); this.nestedNodeMap.set(node, flatNode); return flatNode; } /** Whether all the descendants of the node are selected. */ descendantsAllSelected(node: TodoItemFlatNode): boolean { const descendants = this.treeControl.getDescendants(node); const descAllSelected = descendants.length > 0 && descendants.every(child => { return this.checklistSelection.isSelected(child); }); return descAllSelected; } /** Whether part of the descendants are selected */ descendantsPartiallySelected(node: TodoItemFlatNode): boolean { const descendants = this.treeControl.getDescendants(node); const result = descendants.some(child => this.checklistSelection.isSelected(child)); return result && !this.descendantsAllSelected(node); } /** Toggle the to-do item selection. Select/deselect all the descendants node */ todoItemSelectionToggle(node: TodoItemFlatNode): void { this.checklistSelection.toggle(node); const descendants = this.treeControl.getDescendants(node); this.checklistSelection.isSelected(node) ? this.checklistSelection.select(...descendants) : this.checklistSelection.deselect(...descendants); // Force update for the parent descendants.forEach(child => this.checklistSelection.isSelected(child)); this.checkAllParentsSelection(node); } /** Toggle a leaf to-do item selection. Check all the parents to see if they changed */ todoLeafItemSelectionToggle(node: TodoItemFlatNode): void { this.checklistSelection.toggle(node); this.checkAllParentsSelection(node); } /* Checks all the parents when a leaf node is selected/unselected */ checkAllParentsSelection(node: TodoItemFlatNode): void { let parent: TodoItemFlatNode | null = this.getParentNode(node); while (parent) { this.checkRootNodeSelection(parent); parent = this.getParentNode(parent); } } /** Check root node checked state and change it accordingly */ checkRootNodeSelection(node: TodoItemFlatNode): void { const nodeSelected = this.checklistSelection.isSelected(node); const descendants = this.treeControl.getDescendants(node); const descAllSelected = descendants.length > 0 && descendants.every(child => { return this.checklistSelection.isSelected(child); }); if (nodeSelected && !descAllSelected) { this.checklistSelection.deselect(node); } else if (!nodeSelected && descAllSelected) { this.checklistSelection.select(node); } } /* Get the parent node of a node */ getParentNode(node: TodoItemFlatNode): TodoItemFlatNode | null { const currentLevel = this.getLevel(node); if (currentLevel < 1) { return null; } const [MASK] = this.treeControl.dataNodes.indexOf(node) - 1; for (let i = [MASK] ; i >= 0; i--) { const currentNode = this.treeControl.dataNodes[i]; if (this.getLevel(currentNode) < currentLevel) { return currentNode; } } return null; } applySpaceFilter(){ if(this.selected.length === 0 || this.selected.filter(x=> x.level===0).length === 1){ this.spaceFilter = null; } else { this.spaceFilter = [this.selected.map(x=>x.item)]; } console.log(this.spaceFilter); this.ohm.getIndex(this.spaceFilter).subscribe((data: any) => { this.out = data; }); } } ",startIndex 49,"import { BotBuilder, BotBuilderExt } from '@telefonica/bot-core'; import http = require('http'); export default [ dialog ]; function dialog(session: BotBuilder.Session, [MASK] : any, next: Function) { let groupEntity: BotBuilder.IEntity = BotBuilder.EntityRecognizer.findEntity( [MASK] .entities, 'laura.group'); let entityName = groupEntity ? groupEntity.entity : ''; http.get(`http://gsb.devel.e-paths.com/role/${encodeURIComponent(entityName)}`, (res) => { const statusCode = res.statusCode; const contentType = res.headers['content-type']; let error; if (statusCode !== 200) { error = new Error(`Request Failed.\nStatus Code: ${statusCode}`); } else if (!/^application\/json/.test(contentType)) { error = new Error(`Invalid content-type.\nExpected application/json but received ${contentType}`); } if (error) { console.log(error.message); res.resume(); session.endDialog(error.message); } let rawData = ''; res.on('data', (chunk) => rawData += chunk); res.on('end', () => { try { console.log(rawData) let employees: Employee[] = JSON.parse(rawData).data || []; console.log(employees); let choicesKeyboard = new BotBuilderExt.Keyboard(session).buttons( employees.map(employee => BotBuilder.CardAction.imBack( session, session.gettext('suggestion.employee.head.value', employee.fullname.toLowerCase().replace(/\b\w/g, function(l: any) {return l.toUpperCase() })), employee.fullname) .image(employee.pic || 'https://the-pastry-box-project.net/assets/basiks/front/icons/github.png') ) ); let message = new BotBuilder.Message(session) .text(`Estos son los ${entityName} que hay en CDO`) .addAttachment(choicesKeyboard); let choices = employees.map(employee => employee.fullname); session.endDialog(message, choices); } catch (e) { console.log(e.message); } }); }).on('error', (e) => { console.log(`Got error: ${e.message}`); session.endDialog(e.message); }); } export class Employee { totalTeam: number; numOfChildren: number; fullname: string; pic: string; title: string; phone: string; email: string; location: string; } ",args 50,"import type { UserFromGetMe } from ""grammy/types""; // Types import type { IJSONConfig } from ""./utilities/types.ts""; import path from ""path""; // stdlib import { Bot } from ""grammy""; // 3rd-party deps import { ReadJson, CreateJsonFromDict } from ""./utilities/json.ts""; // Utilities import logging from ""./utilities/logging.ts""; import HandleCommands from ""./utilities/commands.ts""; // Init config path and read config file let cfgPath: string; let cfg: IJSONConfig; // Functions async function InitConfig(): Promise { await logging.info(""Initializing config...""); cfgPath = path.resolve(__dirname, "".."", ""config.json""); cfg = await ReadJson(cfgPath); if (cfg === undefined) { // Base config.json keys cfg = { token: """", debug: false, prefix: """" }; await CreateJsonFromDict(cfgPath, cfg); } if (cfg.debug) { await logging.info(""Starting in debug mode!""); } // Fail initializing if config keys don't exist const keys1 = Object.keys(cfg); const keys2 = Object.keys(cfg); const bAllKeysExist = keys1.every(key => keys2.includes(key)); if (!bAllKeysExist) { await logging.error(""Missing key in config.json""); return false; } // Fail initializing config if token doesn't exist if (cfg.token == """" || cfg.prefix == """") { // Note: !cfg.token check might be useless await logging.error(""Missing bot token or prefix in config file.""); return false; } // After this, it's safe to read the file at any point return true; } async function OnStart( [MASK] : UserFromGetMe): Promise { for (const msg of [ ""Started bot!"", `Name: ${ [MASK] .first_name} | User: @${ [MASK] .username} | ID: ${ [MASK] .id}` ]) { await logging.info(msg); } } async function main(): Promise { // Init bot const bCfgInitSuccess = await InitConfig(); if (!bCfgInitSuccess) { return; // Don't run any further } const bot = new Bot(cfg.token); await HandleCommands(bot); await bot.init(); await bot.start({ onStart: OnStart }); return; } await main(); ",botInfo 51,"import { graphql } from ""@octokit/graphql""; import { map, of } from ""rxjs""; const getEnv = () => { const organization = process.env.ORGANIZATION as string; const githubToken = process.env.GITHUB_TOKEN as string; const projectNumber = parseInt(process.env.PROJECT_NUMBER as string); const status = process.env.ITEM_FIELD_KEY as string; const closeStatus = process.env.ITEM_FIELD_VALUE; return { organization, status, githubToken, projectNumber, closeStatus, } } export type EnvSettings = ReturnType; export type GraphQL = typeof graphql; export type Context = [EnvSettings, GraphQL] const mergeGHGraphqlClient = map((env: EnvSettings): Context => { const [MASK] = graphql.defaults({ headers: { authorization: `token ${env.githubToken}`, }, }); return [env, [MASK] ] }) export const contextObservable = of(getEnv()) .pipe( mergeGHGraphqlClient, ) ",requestGraphql 52,"/// import _ from 'lodash'; import {WifiPlugQueryCtrl} from ""./query_ctrl""; export default class WifiPlugDatasource { id: number; name: string; url: string; /** @ngInject */ constructor(instanceSettings, private backendSrv, private templateSrv, private $q) { this.name = instanceSettings.name; this.id = instanceSettings.id; this.url = instanceSettings.url; } query(options) { let url = `${this.url}`; // trim dates let dateFrom = options.range.from.format('YYYY-MM-DDTHH:mm:ss'); let dateTo = options.range.to.format('YYYY-MM-DDTHH:mm:ss'); // build promises array let promises = {}; for (let target of options.targets) { let targetComponents = target.target.split('@'); let deviceUuid = targetComponents[0]; let serviceUuid = targetComponents[1]; if (targetComponents.length == 0 || (target.device_requirement == null || target.device_requirement == """")) continue; if (target.device_requirement == ""consumption"") { promises[`${target.target}#consumption`] = this.backendSrv.datasourceRequest({ url: `${url}/wifiplug-v1.0/device/${deviceUuid}/service/${serviceUuid}/energy/consumption/historic?date_from=${dateFrom}Z&date_to=${dateTo}Z&grouping=hour`, method: 'GET', withCredentials: true }).then(response => { if (response.status === 200) { return { rows: response.data.map(d => { return { ""time"": Date.parse(d[""time""]), ""value"": d[""kwh""] * 1000 }; }), target: ""Consumption (WH)"" } } }); } else { let deviceRequirement = target.device_requirement; let targetStr = ""Power""; if (deviceRequirement == ""current"") targetStr = ""Current (A)""; else if (deviceRequirement == ""voltage"") targetStr = ""Voltage (V)""; ((a, b, c, e, f) => { promises[`${c}#${b}`] = this.backendSrv.datasourceRequest({ url: `${url}/wifiplug-v1.0/device/${e}/service/${f}/energy/historic?date_from=${dateFrom}Z&date_to=${dateTo}Z&grouping=hour`, method: 'GET', withCredentials: true }).then(response => { if (response.status === 200) { return { rows: response.data.map(d => { return { ""time"": Date.parse(d[""time""]), ""value"": d[b] }; }), target: a } } }); })(targetStr, deviceRequirement, target.target, deviceUuid, serviceUuid); } } // return promise return this.$q.all(promises).then(d => { let [MASK] = []; for(let key in d) { [MASK] .push({ ""target"": d[key].target, ""datapoints"": d[key].rows.map(r => [r.value, r.time]) }); } return { data: [MASK] }; }); } annotationQuery(options) { throw new Error(""Annotation Support not implemented yet.""); } metricFindQuery(query: string) { let url = `${this.url}`; return this.backendSrv.datasourceRequest({ url: `${url}/wifiplug-v1.0/device`, method: 'GET', withCredentials: true }).then(response => { if (response.status === 200) { let kv = []; for (let device of response.data.devices) { // find energy service let energyServices = device.services .filter(s => s.type_uuid == ""e4b8c402-e3f8-4ba3-8593-8565664a18bf""); for(let energyService of energyServices) { if (energyServices.length > 1) kv.push({text: `${device.name} - ${energyService.caption}`, value: `${device.uuid}@${energyService.uuid}`}); else kv.push({text: device.name, value: `${device.uuid}@${energyService.uuid}`}); } } return kv; } }); } testDatasource() { let url = `${this.url}`; return this.backendSrv.datasourceRequest({ url: `${url}/wifiplug-v1.0/user`, method: 'GET', withCredentials: true }).then(response => { if (response.status === 200) { let user = response.data; return { status: ""success"", message: `Authenticated as ${user.username}`, title: ""Success"" }; } }); } } ",results 53,"import { storageGet } from 'stores/storage'; const FORCE_WHITELABEL = process.env.NEXT_PUBLIC_WHITELABEL; // 'jeoi.tkngate.com' || 'test.tkngate.com' || 'tachyon.tkngate.com' || example: 'www.hobbycartelnft.com' const FORCE_PERMISSION_CONTRIB = null; const TPP = process.env.NEXT_PUBLIC_TPP_SERVER || `https://mgate.io`; function getOverride(): string { const isBrowser = typeof window !== 'undefined'; if (isBrowser) { var w = new URLSearchParams(window.location.search).get('whitelabel'); if (!w) w = localStorage.getItem('whitelabel') || storageGet('whitelabel'); if (w) localStorage.setItem('whitelabel', w); } const override = w || null; return override || FORCE_WHITELABEL || null; } // export function getRootProfile(host) { // if (!host) return null; // // if (!host.includes(""."")) return host; // already username // if (host.includes('.mintgate.io') && /^(app|www)/i.test(host) === false) // return host.split('.')[0]; // if (process.env.NODE_ENV !== 'production' && host.includes('.localhost')) // return host.split('.')[0]; // return null; // } export function isBrand(host) { if (getOverride()) return true; if (!host || host === 'app') return false; if (host === 'app.mintgate.io') return false; if (process.env.NODE_ENV !== 'production') { // if (host.includes("".localhost"")) return true; if (host.includes('app.localhost')) return false; if (host === 'localhost:3000' || host === 'localhost') return false; } return true; } export function getBrandURL(host: string): URL { if (!host) return null; // if (typeof window !== 'undefined') host = host || window.location.host; if (!isBrand(host)) return null; let url = new URL(`${TPP}/api/v2/brand/bydomain`); // users/ let username = getOverride() || host; // getRootProfile(host) || if (!username) return null; // ex: mintgate.mintclub.app = use mintclub as username // or ex: mintclub.mintgate.app => mintclub.app [0] = mintclub username = username.toLowerCase(); url.searchParams.set('domain', username); return url; } export async function getBrand(host) { // ensure user is updated and whitelabel already fetched // ignore localhost and mintgate.io... only trigger for xxx.yyy.com (len 2) const [MASK] = getBrandURL(host)?.href; if (! [MASK] ) return null; const response = await fetch( [MASK] , { method: 'GET', }) .then((x) => x.json()) .catch((err) => { return null; }); const data = response; // await response.json(); if (!data) return null; if (data.brand && !data.brand?.brandname) data.brand.brandname = data.username; // data.host = host; data.origin = `https://${host}`; // cache[username] = data; // cacheSet(username, data); data.url = [MASK] ; return data; } // let cache = {}; // function cacheSet(domain: string, data: T): T { // cache[domain] = data; // return data; // } // function cacheget(domain) { // const isBrowser = typeof window !== 'undefined'; // // only cache in browser // if (isBrowser && cache[domain]) return cache[domain]; // // const isBrowser = typeof window !== ""undefined""; // // if(isBrowser) { // // if(localStorage.getItem(domain)) return JSON.parse(localStorage.getItem(domain)); // // } // return null; // } ",urlStr 54,"import { exportToDirectory, importDirectory, cleanupSVG, runSVGO, deOptimisePaths, scaleSVG, resetSVGOrigin, removeFigmaClipPathFromSVG, convertSVGToMask, } from '@iconify/tools'; import fs from ""node:fs/promises""; import svgtofont from 'svgtofont'; import { createTTF } from 'svgtofont/lib/utils'; import path from ""node:path"" const start_char=33; (async () => { // Import icons const iconSet = await importDirectory('src/svg', { prefix: 'ntchrono_fonts', }); // Validate, clean up, fix palette and optimise let character = start_char; iconSet.forEach((name, type) => { if (type !== 'icon') { console.log(`${name} type: ${type}`); // return; } const svg = iconSet.toSVG(name); if (!svg) { // Invalid icon iconSet.remove(name); console.log(`${name} invalid`); return; } // Clean up and optimise icons try { // Clean up icon code cleanupSVG(svg); // Optimise runSVGO(svg,{ keepShapes: true, }); deOptimisePaths(svg); resetSVGOrigin(svg); console.log(`SVG ${name} ${svg.viewBox.width}x${svg.viewBox.height} -> 48x48`); scaleSVG(svg,48/svg.viewBox.width); removeFigmaClipPathFromSVG(svg); // } catch (err) { // Invalid icon console.error(`Error parsing ${name}:`, err); iconSet.remove(name); return; } // Update icon iconSet.fromSVG(name, svg); iconSet.toggleCharacter(name,String.fromCharCode(character++),true); }); console.log(`Exported ${character-33} chars in map!`); // Export as IconifyJSON const [MASK] = JSON.stringify(iconSet.export(), null, '\t') + '\n'; // Save to file await fs.mkdir(""dist/fonts"",{ recursive: true }); await fs.writeFile(`dist/fonts/${iconSet.prefix}.json`, [MASK] , 'utf8'); await exportToDirectory(iconSet, { target: `dist/fonts/${iconSet.prefix}`, cleanup: true, autoHeight: false, includeAliases: true, includeChars: false, log: false, }); // Generated Iconset //console.log(iconSet.export()); // TTF Generation svgtofont({ src: path.resolve(process.cwd(), `dist/fonts/${iconSet.prefix}/`), // svg path dist: path.resolve(process.cwd(), ""dist/fonts""), // output path //styleTemplates: path.resolve(rootPath, ""styles""), // file templates path (optional) fontName: iconSet.prefix, // font name css: false, // Create CSS files. startUnicode: start_char, // unicode start number svgicons2svgfont: { centerHorizontally: true, centerVertically: true, fontHeight: 48, descent: 20, ascent: 48-10, normalize: true, usePathBounds: true, fixedWidth: true, } }).then(() => { console.log('done!'); }); })();",exported 55,"import { Injectable } from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {AlertifyService} from './alertify.service'; import {City} from '../models/city'; import {Router} from '@angular/router'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class CityService { constructor(private httpClient:HttpClient, private router:Router, private alertifyService:AlertifyService) { } path=""http://localhost:62902/api/""; getCities():Observable{ return this.httpClient.get(this.path+""city""); } getCityById( [MASK] ):Observable{ return this.httpClient.get(this.path+""city/""+ [MASK] ); } add(city){ this.httpClient.post(this.path+'city',city).subscribe(data=>{ this.alertifyService.success(""City added"") }); } } ",cityId 56,"import { shallowRef } from 'vue'; import { openDB, IDBPDatabase } from 'idb'; import router from '../router'; interface AssetDB { assets: { key: string; value: Blob; }; } // 资产列表配置 const ASSET_LIST = { sprite: [ 'ax.png', 'bearman.png', 'blackbear.png', 'candle0.png', 'candle1.png', 'candle2.png', 'chas0.png', 'chas1.png', 'chas2.png', 'cloak.png', 'coldeco.png', 'epitaph0.png', 'epitaph1.png', 'fish00.png', 'fish01.png', 'flower0.png', 'flower1.png', 'gameover.png', 'gameover2.png', 'hell0.png', 'hell1.png', 'hell2.png', 'iceflare.png', 'inn.png', 'kudou.png', 'lighter.png', 'lucifer.png', 'memo.png', 'nazo00.png', 'noenemy.png', 'self.png', 'selfclosed.png', 'shop.png', 'snow0.png', 'snow1.png', 'snow2.png', 'snowdoll.png', 'snowman.png', 'snowman2.png', 'snowman3.png', 'snowman4.png', 'snowwes.png', 'snowwes2.png', 'snowwes3.png', 'snowwes4.png', 'title.png', 'warning.png', 'welcome.png', 'whitebear.png', 'whitebear2.png', 'zereta.png' ], cg: [ 'black.bmp', 'dark00.bmp', 'dark01.bmp', 'dark02.bmp', 'scene_colde00.bmp', 'scene_colde01.bmp', 'scene_engine.bmp', 'scene_fire.bmp', 'scene_fireball.bmp', 'scene_fish.bmp', 'scene_house00.bmp', 'scene_house01.bmp', 'scene_house02.bmp', 'scene_house03.bmp', 'scene_kudou.bmp', 'scene_kudou02.bmp', 'scene_self00.bmp', 'scene_self01.bmp', 'scene_self02.bmp', 'scene_self03.bmp', 'scene_self04.bmp', 'scene_self05.bmp', 'scene_self06.bmp', 'scene_self07.bmp', 'scene_self08.bmp', 'scene_self09.bmp', 'scene_self10.bmp', 'scene_snowball.bmp', 'scene_white.bmp' ], music: [ 'coldecot.mp3', 'fuleuden.mp3', 'haruyori.mp3', 'haumu.mp3', 'macchi.mp3', 'simoyake.mp3', 'sironotuiku.mp3', 'thanatos.mp3', 'yukimichi.mp3', 'yukio.mp3' ], sound: [ 'break.wav', 'bub.wav', 'dh.wav', 'dun.wav', 'duty.wav', 'eat.wav', 'fire.wav', 'hyuun.wav', 'kin.wav', 'open.wav', 'popon.wav', 'roar.wav', 'spell00.wav', 'spell01.wav', 'spell02.wav', 'spell03.wav', 'spell04.wav', 'spell05.wav', 'spell06.wav', 'spell07.wav', 'spell08.wav', 'spell09.wav', 'suka.wav', 'thathatha.wav', 'turn.wav', 'up.wav', 'weak.wav', 'zurl.wav', 'step.wav' ], story: [ 'story00.txt', 'story01.txt', 'story02.txt', 'story03.txt', 'story04.txt', 'story05.txt', 'story06.txt', 'story07.txt', 'story08.txt', 'story09.txt', 'story10.txt', 'story_close.txt' ] }; // 缓存已加载的资源 const assetCache = new Map(); class AssetManager { private db: IDBPDatabase | null = null; private totalAssets: number = 0; private loadedAssets: number = 0; private urlCache: Map = new Map(); private imageUrls: string[] = []; constructor() { this.totalAssets = Object.values(ASSET_LIST).reduce( (sum, files) => sum + files.length, 0 ); } async init() { this.db = await openDB('game-assets', 1, { upgrade(db) { db.createObjectStore('assets', { keyPath: 'key' }); }, }); } async hasAssets(): Promise { await this.ensureDB(); const count = await this.db!.count('assets'); return count === this.totalAssets; } private async ensureDB() { if (!this.db) { await this.init(); } } async loadAllAssets(onProgress?: (current: number, total: number) => void) { await this.ensureDB(); this.loadedAssets = 0; for (const [type, files] of Object.entries(ASSET_LIST)) { for (const file of files) { try { const key = `${type}/${file}`; const existing = await this.db!.get('assets', key); if (!existing) { const assetPath = `/assets/${type}/${file}`; const response = await fetch(assetPath); if (!response.ok) { throw new Error(`Failed to load ${key}`); } const blob = await response.blob(); await this.db!.put('assets', { key, value: blob }); } this.loadedAssets++; onProgress?.(this.loadedAssets, this.totalAssets); } catch (error) { console.error(`Error loading asset ${type}/${file}:`, error); throw error; } } } } async getAsset(path: string): Promise { await this.ensureDB(); const asset = await this.db!.get('assets', path); if (!asset) { await router.push('/loading'); throw new Error(`Asset not found: ${path}`); } return asset.value; } /** * 获取资产的 URL * @param path 资产路径 (例如: 'sprite/snow0.png') * @returns 资产的 URL */ async getAssetUrl(path: string): Promise { // 检查缓存 if (this.urlCache.has(path)) { return this.urlCache.get(path)!; } try { const blob = await this.getAsset(path); const url = URL.createObjectURL(blob); this.urlCache.set(path, url); return url; } catch (error) { console.error(`Failed to get asset URL for ${path}:`, error); // 不再直接返回fallback图片,而是让错误传播出去,触发重定向 throw error; } } /** * 清理指定资产的 URL 缓存 * @param path 资产路径 */ clearAssetUrl(path: string) { const url = this.urlCache.get(path); if (url) { URL.revokeObjectURL(url); this.urlCache.delete(path); } } /** * 清理所有 URL 缓存 */ clearAllAssetUrls() { this.urlCache.forEach(url => URL.revokeObjectURL(url)); this.urlCache.clear(); } /** * 组件使用的便捷方法 * @param path 资产路径 * @returns ref对象,包含资产URL */ useAsset(path: string) { const url = shallowRef(''); // 如果已经在缓存中,直接返回 if (assetCache.has(path)) { url.value = assetCache.get(path)!; return url; } // 如果不在缓存中,说明是动态生成的路径(如 snow0.png, snow1.png, snow2.png) // 使用 getAssetUrl 方法从 IndexedDB 获取资源 this.getAssetUrl(path) .then(assetUrl => { // 获取到 URL 后也加入缓存 assetCache.set(path, assetUrl); url.value = assetUrl; }) .catch(error => { console.error(`加载资源失败: ${path}`, error); }); return url; } // 清理函数 - 在应用退出时调用 clearAssets() { assetCache.forEach(url => { URL.revokeObjectURL(url); }); assetCache.clear(); } // 获取所有图片资源的路径 getImagePaths(): string[] { const imagePaths: string[] = []; // 添加 sprite 和 cg 类型的资源 ['sprite', 'cg'].forEach(type => { ASSET_LIST[type as keyof typeof ASSET_LIST].forEach(file => { imagePaths.push(`${type}/${file}`); }); }); return imagePaths; } // 预加载所有图片 async preloadAllImages(onProgress?: (current: number, total: number) => void): Promise { const imagePaths = this.getImagePaths(); let loadedCount = 0; const total = imagePaths.length; const promises = imagePaths.map(path => { return new Promise((resolve, [MASK] ) => { this.getAssetUrl(path) .then(url => { // 同时存入 assetCache,这样 useAsset 可以直接使用 assetCache.set(path, url); this.addImageUrl(url); loadedCount++; onProgress?.(loadedCount, total); resolve(); }) .catch( [MASK] ); }); }); await Promise.all(promises); } // 获取所有需要预加载的图片URL getPreloadImageUrls(): string[] { return this.imageUrls; } // 添加需要预加载的图片URL addImageUrl(url: string) { if (!this.imageUrls.includes(url)) { this.imageUrls.push(url); } } } export const assetManager = new AssetManager(); ",reject 57,"import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions, Response } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import {Observable} from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import { IRemind } from './remind.model'; @Injectable() export class RemindService { //private apiUrl = 'http://localhost:8080/reminders'; //private apiUrl = 'http://192.168.0.14:8080/reminders'; private apiUrl = 'http://192.168.127.12:5555/reminders'; constructor(private http: Http) {} getReminds(): Promise { var apiUrl1: string = 'api/remind'; return this.http.get(this.apiUrl) .toPromise() .then(res => res.json()) .catch(this.handleError); } addRemind(remind: IRemind): Promise { return this.post(remind); } saveRemind(remind: IRemind): Promise { return this.post(remind); } deleteRemind(remind: IRemind): Promise { return this.delete(remind); } private post(remind: IRemind): Promise { let promise: Promise; let body = JSON.stringify(remind); console.log(""post-"" + remind.remindDate); console.log( remind); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers }); promise = this.http.post(this.apiUrl, body, options) .toPromise() .then(res => res.json().data) .catch(this.handleError); console.log(promise.then(res => console.log(res ))); return promise; } private put(remind: IRemind): Promise { let body = JSON.stringify(remind); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers }); let url = `${this.apiUrl}/${remind.id}`; return this.http.put(url, body, options) .toPromise() .then(res => remind) .catch(this.handleError); } private delete(remind: IRemind): Promise { let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers }); let url = `${this.apiUrl}/${remind.id}`; return this.http.post(url, options) .toPromise() .then(res => remind) .catch(this.handleError); } private handleError( [MASK] : any): Promise { console.log('Произошла ошибка', [MASK] ); return Promise.reject( [MASK] .message || [MASK] ); } }",error 58,"import { Transaction } from '@mysten/sui/transactions' import { fullFunctionName } from '~~/helpers/network' export const prepareCreateGreetingTransaction = ( packageId: string ): Transaction => { const tx = new Transaction() tx.moveCall({ arguments: [], target: fullFunctionName(packageId, 'create'), }) return tx } export const prepareSetGreetingTransaction = ( packageId: string, objectId: string, [MASK] : string ): Transaction => { const tx = new Transaction() tx.moveCall({ arguments: [tx.object(objectId), tx.pure.string( [MASK] ), tx.object('0x8')], target: fullFunctionName(packageId, 'set_greeting'), }) return tx } export const prepareResetGreetingTransaction = ( packageId: string, objectId: string ): Transaction => { const tx = new Transaction() tx.moveCall({ arguments: [tx.object(objectId)], target: fullFunctionName(packageId, 'reset_greeting'), }) return tx } ",name 59,"import {fetchWithAuth} from ""./fetchWithAuth""; import type {AdventureCreateDto, AdventureDto, AdventurePatchDto} from ""../types/adventure""; export const AdventureService = { async list(): Promise { const res = await fetchWithAuth(""/api/adventures""); if (!res.ok) throw new Error(""Ошибка загрузки приключений""); return res.json(); }, async get(id: string): Promise { const res = await fetchWithAuth(`/api/adventures/${id}`); if (!res.ok) throw new Error(""Приключение не найдено""); return res.json(); }, async create(data: AdventureCreateDto): Promise { const res = await fetchWithAuth(""/api/adventures"", { method: ""POST"", headers: { ""Content-Type"": ""application/json"" }, body: JSON.stringify(data), }); if (!res.ok) throw new Error(""Ошибка создания приключения""); return res.json(); }, async patch(id: string, data: AdventurePatchDto): Promise { const res = await fetchWithAuth(`/api/adventures/${id}`, { method: ""PATCH"", headers: { ""Content-Type"": ""application/json"" }, body: JSON.stringify(data), }); if (!res.ok) throw new Error(""Ошибка обновления приключения""); return res.json(); }, async remove(id: string): Promise { const res = await fetchWithAuth(`/api/adventures/${id}`, { method: ""DELETE"" }); if (!res.ok) throw new Error(""Ошибка удаления приключения""); }, async uploadCover(adventureId: string, file: File): Promise { const [MASK] = new FormData(); [MASK] .append(""file"", file); const res = await fetchWithAuth(`/api/adventures/${adventureId}/cover`, { method: ""POST"", body: [MASK] , }); if (!res.ok) throw new Error(""Ошибка загрузки обложки""); // Предположим, что backend возвращает { coverUrl: ""..."" } const data = await res.json(); return data.coverUrl; } }; ",formData 60,"import { Component, OnInit } from '@angular/core'; import { Email } from './email'; import { MessageService } from 'primeng/api'; import { CriarChatService } from './criar-chat.service'; @Component({ selector: 'app-criar-chat', templateUrl: './criar-chat.component.html', styleUrls: ['./criar-chat.component.css'], providers: [MessageService] }) export class CriarChatComponent implements OnInit { private urlCriarChat: string = 'https://back-end-pessoas.herokuapp.com/chat' id: string idChat: string = '' rem: string dest: string private urlCriarListarMensage: string = 'https://back-end-pessoas.herokuapp.com/chat?id=?1&idChat=?2&rem=?3&dest=?4' private urlEnviarMensagem: string = 'https://back-end-pessoas.herokuapp.com/mensagem' contato: {} email: Email = { email_remetente: '', email_destinatario: '', mensagem: '' } chat: {} listaMensagens: Array = [] constructor(private messageService: MessageService, private criarChatService: CriarChatService) {} showSuccess() { this.messageService.add({key: 'tl', severity:'success', summary: 'Status da requisição: ', detail:'O chat foi criado!'}); } showError() { this.messageService.add({key: 'tl', severity:'error', summary: 'Status da requisição: ', detail:'Erro ao criar o chat, verifique os campos!'}); } showSuccessSend() { this.messageService.add({key: 'tl', severity:'success', summary: 'Status da requisição: ', detail:'A mensagem foi enviada!'}); } showErrorSend() { this.messageService.add({key: 'tl', severity:'error', summary: 'Status da requisição: ', detail:'Erro ao enviar a mensagem!'}); } criarUmChat = () => { this.criarChatService.criarChat(this.urlCriarChat.toString(), this.email).subscribe( resposta => { this.chat = resposta if (this.chat != {}) { this.idChat = resposta['idChat'] this.showSuccess() } }, erro => { if (erro.status == 500) { this.showError() } } ) } enviarUmaMensagem = () => { this.criarChatService.enviarMensagem(this.urlEnviarMensagem.toString(), this.email).subscribe( resposta => { if (resposta['mensagem'] != null) { this.showSuccessSend() } }, erro => { if (erro.status == 400 || erro.status == 500) { this.showErrorSend } } ) } listarMensagens = () => { var [MASK] = this.urlCriarListarMensage.replace('?1', this.id); var url2 = [MASK] .replace('?2', this.idChat); var url3 = url2.replace('?3', this.rem); var urlFinal = url3.replace('?4', this.dest); this.criarChatService.listarMensagens(urlFinal.toString()).subscribe( resposta => { this.listaMensagens = [] this.listaMensagens = resposta['mensagems'] this.listaMensagens.forEach(mensagem => { console.log('Mensagem: ', mensagem) }); } ) } ngOnInit() { this.contato = history.state this.email.email_destinatario = this.contato['email'] } } ",url1 61,"/* Copyright 2022 The Matrix.org Foundation C.I.C. 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. */ /// import { HomeserverInstance } from ""../../plugins/utils/homeserver""; import { SettingLevel } from ""../../../src/settings/SettingLevel""; describe(""Composer"", () => { let homeserver: HomeserverInstance; beforeEach(() => { cy.startHomeserver(""default"").then(( [MASK] ) => { homeserver = [MASK] ; }); }); afterEach(() => { cy.stopHomeserver(homeserver); }); describe(""CIDER"", () => { beforeEach(() => { cy.initTestUser(homeserver, ""Janet"").then(() => { cy.createRoom({ name: ""Composing Room"" }); }); cy.viewRoomByName(""Composing Room""); }); it(""sends a message when you click send or press Enter"", () => { // Type a message cy.findByRole(""textbox"", { name: ""Send a message…"" }).type(""my message 0""); // It has not been sent yet cy.contains("".mx_EventTile_body"", ""my message 0"").should(""not.exist""); // Click send cy.findByRole(""button"", { name: ""Send message"" }).click(); // It has been sent cy.get("".mx_EventTile_last .mx_EventTile_body"").within(() => { cy.findByText(""my message 0"").should(""exist""); }); // Type another and press Enter afterwards cy.findByRole(""textbox"", { name: ""Send a message…"" }).type(""my message 1{enter}""); // It was sent cy.get("".mx_EventTile_last .mx_EventTile_body"").within(() => { cy.findByText(""my message 1"").should(""exist""); }); }); it(""can write formatted text"", () => { cy.findByRole(""textbox"", { name: ""Send a message…"" }).type(""my bold{ctrl+b} message""); cy.findByRole(""button"", { name: ""Send message"" }).click(); // Note: both ""bold"" and ""message"" are bold, which is probably surprising cy.get("".mx_EventTile_body strong"").within(() => { cy.findByText(""bold message"").should(""exist""); }); }); it(""should allow user to input emoji via graphical picker"", () => { cy.getComposer(false).within(() => { cy.findByRole(""button"", { name: ""Emoji"" }).click(); }); cy.findByTestId(""mx_EmojiPicker"").within(() => { cy.contains("".mx_EmojiPicker_item"", ""😇"").click(); }); cy.get("".mx_ContextualMenu_background"").click(); // Close emoji picker cy.findByRole(""textbox"", { name: ""Send a message…"" }).type(""{enter}""); // Send message cy.get("".mx_EventTile_body"").within(() => { cy.findByText(""😇""); }); }); describe(""when Ctrl+Enter is required to send"", () => { beforeEach(() => { cy.setSettingValue(""MessageComposerInput.ctrlEnterToSend"", null, SettingLevel.ACCOUNT, true); }); it(""only sends when you press Ctrl+Enter"", () => { // Type a message and press Enter cy.findByRole(""textbox"", { name: ""Send a message…"" }).type(""my message 3{enter}""); // It has not been sent yet cy.contains("".mx_EventTile_body"", ""my message 3"").should(""not.exist""); // Press Ctrl+Enter cy.findByRole(""textbox"", { name: ""Send a message…"" }).type(""{ctrl+enter}""); // It was sent cy.get("".mx_EventTile_last .mx_EventTile_body"").within(() => { cy.findByText(""my message 3"").should(""exist""); }); }); }); }); describe(""Rich text editor"", () => { beforeEach(() => { cy.enableLabsFeature(""feature_wysiwyg_composer""); cy.initTestUser(homeserver, ""Janet"").then(() => { cy.createRoom({ name: ""Composing Room"" }); }); cy.viewRoomByName(""Composing Room""); }); it(""sends a message when you click send or press Enter"", () => { // Type a message cy.get(""div[contenteditable=true]"").type(""my message 0""); // It has not been sent yet cy.contains("".mx_EventTile_body"", ""my message 0"").should(""not.exist""); // Click send cy.findByRole(""button"", { name: ""Send message"" }).click(); // It has been sent cy.get("".mx_EventTile_last .mx_EventTile_body"").within(() => { cy.findByText(""my message 0"").should(""exist""); }); // Type another cy.get(""div[contenteditable=true]"").type(""my message 1""); // Send message cy.get(""div[contenteditable=true]"").type(""{enter}""); // It was sent cy.get("".mx_EventTile_last .mx_EventTile_body"").within(() => { cy.findByText(""my message 1"").should(""exist""); }); }); it(""sends only one message when you press Enter multiple times"", () => { // Type a message cy.get(""div[contenteditable=true]"").type(""my message 0""); // It has not been sent yet cy.contains("".mx_EventTile_body"", ""my message 0"").should(""not.exist""); // Click send cy.get(""div[contenteditable=true]"").type(""{enter}""); cy.get(""div[contenteditable=true]"").type(""{enter}""); cy.get(""div[contenteditable=true]"").type(""{enter}""); // It has been sent cy.get("".mx_EventTile_last .mx_EventTile_body"").within(() => { cy.findByText(""my message 0"").should(""exist""); }); cy.get("".mx_EventTile_last .mx_EventTile_body"").should(""have.length"", 1); }); it(""can write formatted text"", () => { cy.get(""div[contenteditable=true]"").type(""my {ctrl+b}bold{ctrl+b} message""); cy.findByRole(""button"", { name: ""Send message"" }).click(); cy.get("".mx_EventTile_body strong"").within(() => { cy.findByText(""bold"").should(""exist""); }); }); describe(""when Ctrl+Enter is required to send"", () => { beforeEach(() => { cy.setSettingValue(""MessageComposerInput.ctrlEnterToSend"", null, SettingLevel.ACCOUNT, true); }); it(""only sends when you press Ctrl+Enter"", () => { // Type a message and press Enter cy.get(""div[contenteditable=true]"").type(""my message 3""); cy.get(""div[contenteditable=true]"").type(""{enter}""); // It has not been sent yet cy.contains("".mx_EventTile_body"", ""my message 3"").should(""not.exist""); // Press Ctrl+Enter cy.get(""div[contenteditable=true]"").type(""{ctrl+enter}""); // It was sent cy.get("".mx_EventTile_last .mx_EventTile_body"").within(() => { cy.findByText(""my message 3"").should(""exist""); }); }); }); describe(""links"", () => { it(""create link with a forward selection"", () => { // Type a message cy.get(""div[contenteditable=true]"").type(""my message 0{selectAll}""); // Open link modal cy.findByRole(""button"", { name: ""Link"" }).click(); // Fill the link field cy.findByRole(""textbox"", { name: ""Link"" }).type(""https://matrix.org/""); // Click on save cy.findByRole(""button"", { name: ""Save"" }).click(); // Send the message cy.findByRole(""button"", { name: ""Send message"" }).click(); // It was sent cy.get("".mx_EventTile_body a"").within(() => { cy.findByText(""my message 0"").should(""exist""); }); cy.get("".mx_EventTile_body a"").should(""have.attr"", ""href"").and(""include"", ""https://matrix.org/""); }); }); }); }); ",data 62,"import defaults from 'lodash/defaults'; import { DataQueryRequest, DataQueryResponse, DataSourceApi, DataSourceInstanceSettings, AnnotationEvent, AnnotationQueryRequest, DataQueryError, } from '@grafana/data'; import { getBackendSrv } from '@grafana/runtime'; import { ConprofQuery, ConprofOptions, defaultQuery, ConprofDataQueryResponse, Series } from './types'; export class DataSource extends DataSourceApi { url: string; constructor(instanceSettings: DataSourceInstanceSettings) { super(instanceSettings); this.url = instanceSettings.url!; } _request(url: string, data: Record = {}) { const options = { url: this.url + url, method: 'GET', }; if (data && Object.keys(data).length) { options.url = options.url + '?' + Object.entries(data) .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`) .join('&'); } return getBackendSrv().datasourceRequest(options); } handleErrors = (err: any, target: ConprofQuery) => { const error: DataQueryError = { message: (err && err.statusText) || 'Unknown error during query transaction. Please check JS console logs.', refId: target.refId, }; if (err.data) { if (typeof err.data === 'string') { error.message = err.data; } else if (err.data.error) { error.message = this.safeStringifyValue(err.data.error); } } else if (err.message) { error.message = err.message; } else if (typeof err === 'string') { error.message = err; } error.status = err.status; error.statusText = err.statusText; return error; }; safeStringifyValue = (value: any, [MASK] ?: number) => { if (!value) { return ''; } try { return JSON.stringify(value, null, [MASK] ); } catch (error) { console.error(error); } return ''; }; performTimeSeriesQuery(query: ConprofQuery) { if (query.start > query.end) { throw { message: 'Invalid time range' }; } const url = '/api/v1/query_range'; const data: any = { query: query.expr, from: query.start, to: query.end, }; return this._request(url, data).catch((err: any) => { throw this.handleErrors(err, query); }); } async query(options: DataQueryRequest): Promise { return Promise.resolve({ data: [] }); } async annotationQuery(options: AnnotationQueryRequest): Promise { const annotation = options.annotation; const { expr = '' } = annotation; if (!expr) { return Promise.resolve([]); } const query = defaults(options.annotation, defaultQuery); query.start = options.range.from.valueOf(); query.end = options.range.to.valueOf(); const res: any = await this.performTimeSeriesQuery(query); const response: ConprofDataQueryResponse = res.data; let events: AnnotationEvent[] = []; response.data.map((series: Series) => { let tags: string[] = []; for (let key in series.labels) { tags.push(`${key}:${series.labels[key]}`); } series.timestamps.forEach((timestamp: number) => { const labels = `{${Object.entries(series.labels) .map(([labelName, labelValue]) => `${labelName}=""${labelValue}""`) .join(',')}}`; const encodedLabels = btoa(labels); // TODO(yeya24): support more APIs when ready // const flameGraphURL = `${this.defaultUrl}/api/v1/query?report=flamegraph&time=${timestamp}&query=${query.expr}`; // const topURL = `${this.defaultUrl}/api/v1/query?report=top&time=${timestamp}&query=${query.expr}`; events.push({ title: `${series.labels['__name__']}`, time: timestamp, text: ` `, tags: tags, }); }); }); return events; } // Implement a health check for your data source. async testDatasource() { const result = await this._request('/-/ready'); if (!result) { return { status: 'error', message: 'Cannot connect to Data source' }; } return result.status === 200 ? { status: 'success', message: 'Data source is working' } : { status: 'error', message: result.error }; } } ",space 63,"import { TreeImage, GpsCoordinate } from './types'; import ExifReader from 'exifreader'; // Result types for ROP type Result = Success | Failure; type Success = { success: true; data: T }; type Failure = { success: false; error: E }; // Collection result for handling multiple operations type CollectionResult = { successes: T[]; failures: E[]; }; interface GpsResolutionError { type: 'gps_extraction'; imageName: string; message: string; } interface DiameterCalculationError { type: 'diameter_calculation'; message: string; } // Union type for all possible image processing errors type ImageProcessingError = | GpsResolutionError | DiameterCalculationError; function extractGpsFromImage(contents: Buffer, [MASK] : string): Result { try { // Parse EXIF data from the image buffer const tags = ExifReader.load(contents); // Check if GPS data exists if (!tags.GPSLatitude || !tags.GPSLongitude) { return failure({ type: 'gps_extraction', imageName: [MASK] , message: 'No GPS coordinates found in image EXIF data' }); } // Extract latitude let latitude: number; if (typeof tags.GPSLatitude.description === 'number') { latitude = tags.GPSLatitude.description; } else if (typeof tags.GPSLatitude.description === 'string') { latitude = parseFloat(tags.GPSLatitude.description); } else { return failure({ type: 'gps_extraction', imageName: [MASK] , message: 'Invalid GPS latitude format in EXIF data' }); } // Extract longitude let longitude: number; if (typeof tags.GPSLongitude.description === 'number') { longitude = tags.GPSLongitude.description; } else if (typeof tags.GPSLongitude.description === 'string') { longitude = parseFloat(tags.GPSLongitude.description); } else { return failure({ type: 'gps_extraction', imageName: [MASK] , message: 'Invalid GPS longitude format in EXIF data' }); } // Handle GPS direction references (N/S for latitude, E/W for longitude) if (tags.GPSLatitudeRef && (tags.GPSLatitudeRef.description === 'S' || tags.GPSLatitudeRef.description === 'South latitude')) { latitude = -latitude; } if (tags.GPSLongitudeRef && (tags.GPSLongitudeRef.description === 'W' || tags.GPSLongitudeRef.description === 'West longitude')) { longitude = -longitude; } // Validate coordinates are within valid ranges if (latitude < -90 || latitude > 90) { return failure({ type: 'gps_extraction', imageName: [MASK] , message: `Invalid latitude value: ${latitude}. Must be between -90 and 90.` }); } if (longitude < -180 || longitude > 180) { return failure({ type: 'gps_extraction', imageName: [MASK] , message: `Invalid longitude value: ${longitude}. Must be between -180 and 180.` }); } console.log(`Extracted GPS coordinates from image: ${ [MASK] } - Latitude: ${latitude}, Longitude: ${longitude}`); return success({ latitude, longitude }); } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error'; return failure({ type: 'gps_extraction', imageName: [MASK] , message: `Failed to parse EXIF data: ${errorMessage}` }); } } async function calculateDiameter( subject: string, body: string, env: { AI: any } ): Promise> { try { // Create a prompt to extract diameter information from email content const prompt = ` You are analyzing an email about tree measurements. Extract the diameter measurement for trees mentioned in the email. Email Subject: ${subject} Email Body: ${body} Please extract the diameter measurement in inches. Look for: - Explicit diameter measurements (e.g., ""12 inch diameter"", ""diameter: 10 inches"", ""30cm diameter"") - DBH (Diameter at Breast Height) measurements - Circumference measurements that can be converted to diameter - Any numerical values followed by units that could indicate tree diameter If you find measurements in other units, convert them to inches: - Centimeters to inches: divide by 2.54 - Feet to inches: multiply by 12 - If you find a circumference measurement, convert it to diameter using: diameter = circumference / π Return only the numeric value in inches as a number. If no diameter information is found, return ""NOT_FOUND"". Examples: - ""Tree diameter is 12 inches"" → 12 - ""DBH: 10 inches"" → 10 - ""diameter: 30cm"" → 11.8 (30 ÷ 2.54) - ""Circumference 37.7 inches"" → 12 (37.7 ÷ π) - ""2 foot diameter"" → 24 (2 × 12) - ""No measurements provided"" → NOT_FOUND `; const response = await env.AI.run(""@cf/meta/llama-3.1-8b-instruct"", { prompt: prompt, }); console.log(`AI response for diameter extraction:`, response); // Parse the AI response let responseText: string; if (typeof response === 'string') { responseText = response; } else if (response && typeof response === 'object' && 'response' in response) { responseText = response.response; } else { return failure({ type: 'diameter_calculation', message: 'Unexpected AI response format' }); } responseText = responseText.trim(); if (responseText === 'NOT_FOUND') { return failure({ type: 'diameter_calculation', message: 'No diameter measurement found in email content' }); } // Try to parse the numeric value const diameterValue = parseFloat(responseText); if (isNaN(diameterValue) || diameterValue <= 0) { return failure({ type: 'diameter_calculation', message: `Invalid diameter value extracted: ""${responseText}""` }); } // Validate reasonable diameter range (0.5 inches to 400 inches) if (diameterValue < 0.5 || diameterValue > 400) { return failure({ type: 'diameter_calculation', message: `Diameter value ${diameterValue} inches is outside reasonable range (0.5-400 inches)` }); } console.log(`Successfully extracted diameter from email: ${diameterValue} inches`); return success(diameterValue); } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error'; return failure({ type: 'diameter_calculation', message: `Failed to calculate diameter using AI: ${errorMessage}` }); } } // Helper functions for Result type function success(data: T): Success { return { success: true, data }; } function failure(error: E): Failure { return { success: false, error }; } // Export everything export type { Result, Success, Failure, CollectionResult, GpsResolutionError, DiameterCalculationError, ImageProcessingError, }; export { extractGpsFromImage, calculateDiameter, }; ",name 64,"export enum FieldMaskType { Exclude = 'exclude', Include = 'include', } export type FieldMaskConvertible = Iterable | Record | FieldMask; export class FieldMask { private _entries: Set = new Set; constructor(public type = FieldMaskType.Include) { } static exclude(excluded: Iterable): FieldMask { const mask = new FieldMask(FieldMaskType.Exclude); mask.add(...excluded); return mask; } static include(included: Iterable): FieldMask { const mask = new FieldMask(FieldMaskType.Include); mask.add(...included); return mask; } static from(from: FieldMaskConvertible): FieldMask { if (from instanceof FieldMask) { return from; } else if (Array.isArray(from)) { return FieldMask.include(from); } else { let maskType = undefined; for (const v of Object.values(from)) { if (maskType === undefined) { maskType = v ? FieldMaskType.Include : FieldMaskType.Exclude; } else if ((maskType === FieldMaskType.Exclude && v !== 0) || (maskType === FieldMaskType.Include && v !== 1)) { throw new Error('Invalid field mask object'); } } maskType = maskType || FieldMaskType.Exclude; const mask = new FieldMask(maskType); mask.add(...Object.keys(from)); return mask; } } add(...fields: string[]): void { fields.forEach(f => this._entries.add(f)); } get(): Record { const result = {} as Record; this._entries.forEach(f => { switch (this.type) { case FieldMaskType.Exclude: result[f] = 0; break; case FieldMaskType.Include: result[f] = 1; break; } }); return result; } includes(field: string): boolean { switch (this.type) { case FieldMaskType.Exclude: return !this._entries.has(field); case FieldMaskType.Include: return this._entries.has(field); } } excludes(field: string): boolean { switch (this.type) { case FieldMaskType.Exclude: return this._entries.has(field); case FieldMaskType.Include: return !this._entries.has(field); } } equals(other: FieldMaskConvertible): boolean { const otherMask = FieldMask.from(other); if (this.type !== otherMask.type) return false; for (const field of this._entries) { if (!otherMask._entries.has(field)) return false; } for (const field of otherMask._entries) { if (!this._entries.has(field)) return false; } return true; } negate(): FieldMask { switch (this.type) { case FieldMaskType.Exclude: return FieldMask.include(this._entries); case FieldMaskType.Include: return FieldMask.exclude(this._entries); } } join(otherFrom: FieldMaskConvertible): FieldMask { const entries = [...this._entries]; const other = FieldMask.from(otherFrom); switch (this.type) { case FieldMaskType.Exclude: return FieldMask.exclude(entries.filter(f => !other.includes(f))); case FieldMaskType.Include: const includeMask = FieldMask.include(entries); if (other.type === FieldMaskType.Include) includeMask.add(...other._entries); return includeMask; } } intersect(otherFrom: FieldMaskConvertible): FieldMask { const entries = [...this._entries]; const other = FieldMask.from(otherFrom); switch (this.type) { case FieldMaskType.Exclude: const [MASK] = FieldMask.exclude(entries); if (other.type === FieldMaskType.Exclude) [MASK] .add(...other._entries); return [MASK] ; case FieldMaskType.Include: return FieldMask.include(entries.filter(f => other.includes(f))); } } apply>(o: T): Record { const result: Record = {}; switch (this.type) { case FieldMaskType.Exclude: for (const [k, v] of Object.entries(o)) { if (!this._entries.has(k)) result[k] = v; } break; case FieldMaskType.Include: for (const [k, v] of Object.entries(o)) { if (this._entries.has(k)) result[k] = v; } break; } return result; } }",excludeMask 65,"import weaviate, { WeaviateClient, generateUuid5 } from 'weaviate-ts-client'; // @ts-ignore - let me be happy export const client: WeaviateClient = weaviate.client({ scheme: 'http', host: 'localhost:8080', }); export async function addImage({ image, description }: { image: Blob, description: string }) { const res = await client.data.creator().withClassName(""Image"").withProperties({ image, description }).withId(generateUuid5(image.toString())).do(); return res } export async function addGenerationBatch( [MASK] : { image: Blob, description: string, url: string }[], { generation, baseImageId }: { generation?: number, baseImageId: string }) { // Create batch let batcher = client.batch.objectsBatcher(); for (const dataObj of [MASK] ) { const obj = client.data.creator() .withClassName(""GeneratedImage"") .withProperties({ image: dataObj.image, description: dataObj.description, generation, url: dataObj.url }) .withId(generateUuid5(dataObj.image.toString())) .payload() const ref = client.data .referenceCreator() .withClassName('GeneratedImage') .withId(generateUuid5(dataObj.image.toString())) .withReferenceProperty('baseImage') .withReference( client.data .referencePayloadBuilder() .withClassName('Image') .withId(baseImageId) .payload() ).payload() batcher = batcher.withObjects(obj, ref) } // Flush return batcher.do(); } export async function getRankedImages(id: string) { const originalVec = await client.data .getterById() .withClassName('Image') .withId(id) .withVector() .do(); const res = await client.graphql .get() .withNearVector({ // @ts-ignore - typings vector: originalVec?.vector, }) .withClassName('GeneratedImage') .withFields('description generation url _additional { certainty distance }') .do(); return res } // UNCOMMENT BELOW: // (async () => { // console.info(""Creating classes"") // await client.schema.classCreator().withClass({ // ""class"": ""Image"", // ""vectorizer"": ""multi2vec-clip"", // ""moduleConfig"": { // ""multi2vec-clip"": { // ""textFields"": [""description""], // ""imageFields"": [""image""], // } // }, // ""properties"": [ // { // ""name"": ""image"", // ""dataType"": [""blob""], // }, // { // ""name"": ""description"", // ""dataType"": [""text""], // ""description"": ""Text description of the image. Can be a prompt that generates this image or it's img2text description."", // }, // ], // }).do().catch((e) => console.info(""Image class already exists"")); // await client.schema.classCreator().withClass({ // ""class"": ""GeneratedImage"", // ""vectorizer"": ""multi2vec-clip"", // ""moduleConfig"": { // ""multi2vec-clip"": { // ""textFields"": [""description""], // ""imageFields"": [""image""], // }, // ""ref2vec-centroid"": { // ""referenceProperties"": [""hasParagraphs""], // ""method"": ""mean"" // } // }, // ""properties"": [ // { // ""name"": ""image"", // ""dataType"": [""blob""], // }, // { // ""name"": ""description"", // ""dataType"": [""text""], // ""description"": ""Text description of the image. Can be a prompt that generates this image or it's img2text description."", // }, // { // ""name"": ""generation"", // ""dataType"": [""number""], // ""description"": ""How many generations this image is from the original image."", // }, // { // ""name"": ""baseImage"", // ""dataType"": [""Image""], // ""description"": ""The original image and prompt that were used to generate this image."", // }, // { // ""name"": ""url"", // ""dataType"": [""string""], // ""description"": ""The url of the image."", // } // ], // }).do().catch((e) => console.info(""GeneratedImage class already exists"")); // console.info(""Successfully created classes!"") // })(); ",dataObjs 66,"import { parse } from 'ts-command-line-args' import { Map, Set } from 'immutable' import type { DataType, TaskProvider } from ""@epfml/discojs""; import { defaultTasks } from '@epfml/discojs' interface BenchmarkArguments { provider: TaskProvider numberOfUsers: number epochs: number roundDuration: number batchSize: number save: boolean host: URL } type BenchmarkUnsafeArguments = Omit & { task: string help?: boolean } const argExample = 'e.g. npm start -- -u 2 -e 3 # runs 2 users for 3 epochs' const unsafeArgs = parse( { task: { type: String, alias: 't', description: 'Task: tinder_dog, titanic, simple_face, cifar10 or lus_covid', defaultValue: 'tinder_dog' }, numberOfUsers: { type: Number, alias: 'u', description: 'Number of users', defaultValue: 2 }, epochs: { type: Number, alias: 'e', description: 'Number of epochs', defaultValue: 10 }, roundDuration: { type: Number, alias: 'r', description: 'Round duration (in epochs)', defaultValue: 2 }, batchSize: { type: Number, alias: 'b', description: 'Training batch size', defaultValue: 10 }, save: { type: Boolean, alias: 's', description: 'Save logs of benchmark', defaultValue: false }, host: { type: ( [MASK] : string) => new URL( [MASK] ), typeLabel: ""URL"", description: ""Host to connect to"", defaultValue: new URL(""http://localhost:8080""), }, help: { type: Boolean, optional: true, alias: 'h', description: 'Prints this usage guide' } }, { helpArg: 'help', headerContentSections: [{ header: 'DISCO CLI', content: 'npm start -- [Options]\n' + argExample }] } ) const supportedTasks = Map( Set.of | TaskProvider<""tabular"">>( defaultTasks.cifar10, defaultTasks.lusCovid, defaultTasks.simpleFace, defaultTasks.titanic, defaultTasks.tinderDog, ).map((t) => [t.getTask().id, t]), ); const provider = supportedTasks.get(unsafeArgs.task); if (provider === undefined) { throw Error(`${unsafeArgs.task} not implemented.`) } export const args: BenchmarkArguments = { ...unsafeArgs, provider: { getTask() { const task = provider.getTask(); // Override training information task.trainingInformation.batchSize = unsafeArgs.batchSize; task.trainingInformation.roundDuration = unsafeArgs.roundDuration; task.trainingInformation.epochs = unsafeArgs.epochs; // For DP // TASK.trainingInformation.clippingRadius = 10000000 // TASK.trainingInformation.noiseScale = 0 return task; }, getModel: () => provider.getModel(), }, };",raw 67,"/* * Power BI Visual CLI * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the """"Software""""), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ module powerbi.extensibility.visual { ""use strict""; export class Visual implements IVisual { private svg: d3.Selection; private chartContainer: d3.Selection; private colorPalette: IColorPalette; private host: IVisualHost; private selectionManager: ISelectionManager; private pie: Pie; private opacity: number = 100; private static CategoryColorsPropertyIdentifiers: DataViewObjectPropertyIdentifier = { objectName: ""categoryColors"", propertyName: ""fill"" } private static ChartOpacityPropertyIdentifiers: DataViewObjectPropertyIdentifier = { objectName: ""chartOpacity"", propertyName: ""opacity"" } constructor(options: VisualConstructorOptions) { this.svg = d3.select(options.element).append('svg'); this.chartContainer = this.svg.append('g'); this.host = options.host; this.colorPalette = this.host.colorPalette; this.selectionManager = this.host.createSelectionManager(); } public update(options: VisualUpdateOptions): void { if (options.dataViews.length > 0) { this.pie = this.dataExtraction(options.dataViews[0]); this.updateSettings(options.dataViews[0]); } else { return; } this.generateVisual(this.pie, options.viewport); } private updateSettings(dataView: DataView): void { let metadata = dataView.metadata; let metadataObjects = metadata.objects; if (metadataObjects) { let chartOpacity = metadataObjects[Visual.ChartOpacityPropertyIdentifiers.objectName]; this.opacity = chartOpacity[Visual.ChartOpacityPropertyIdentifiers.propertyName] as number; } let categories = dataView.categorical.categories; let categoryObjects = categories[0].objects; if (categoryObjects) { for (let i = 0; i < categoryObjects.length; i++) { if (categoryObjects[i]) { let chartColorObject = categoryObjects[i][Visual.CategoryColorsPropertyIdentifiers.objectName]; let chartColorProperty = chartColorObject[Visual.CategoryColorsPropertyIdentifiers.propertyName]; let color = (chartColorProperty as any).solid.color; this.pie.slices[i].color = color; } } } } private generateVisual(data: Pie, viewport: IViewport): void { //making pie chart full size of visual viewport let width = viewport.width; let height = viewport.height; let [MASK] = Math.min(width, height) / 2; //defining the vector element and centering the chart this.svg.attr('width', width) .attr('height', height); this.chartContainer.attr('transform', 'translate(' + (width / 2) + ',' + (height / 2) + ')'); //defining the circle let arc = d3.svg.arc() .innerRadius(0) .outerRadius( [MASK] ); //trying casting to any to fix compilation error let angles = d3.layout.pie() .value(function(d) { return d.measure }) .sort(null); //removing the old pie chart slices this.chartContainer.selectAll(""*"").remove(); let selectionManager = this.selectionManager; //adding the new slices let path = this.chartContainer.selectAll('path') .data(angles(data.slices)) .enter() .append('path') .attr('d', arc) .attr('fill', function(d) { return (d.data as any).color }) .on('click', function(d) { selectionManager.select((d.data as any).selectionID); d3.select(this).attr(""fill"", ""#F0F0F0""); }); this.chartContainer.attr(""opacity"", this.opacity / 100); } /* * This function extracts the data from the given DataView and passes it into the data model defined in * dataInterfaces.ts */ private dataExtraction(dataView: DataView): Pie { let categoryColumn = dataView.categorical.categories[0]; let categoryValues = categoryColumn.values; let valueColumn = dataView.categorical.values[0]; let valueValues = valueColumn.values; if (categoryValues.length < 1 || valueValues.length !== categoryValues.length) { return { slices: [], sumOfMeasures: 0 }; } let pieSlices = []; let sumOfMeasures = 0; for (let i = 0; i < categoryValues.length; i++) { let category = categoryValues[i].valueOf() as string | number; let measure = valueValues[i].valueOf() as number; let color = this.colorPalette.getColor(category as string).value; sumOfMeasures += measure; let pieSlice = { category, measure, color, selectionID: this.host.createSelectionIdBuilder() .withCategory(categoryColumn, i) .createSelectionId() } pieSlices.push(pieSlice); } return { slices: pieSlices, sumOfMeasures: sumOfMeasures } } /** * This function gets called for each of the objects defined in the capabilities files and allows you to select which of the * objects and properties you want to expose to the users in the property pane. * */ public enumerateObjectInstances(options: EnumerateVisualObjectInstancesOptions): VisualObjectInstance[] | VisualObjectInstanceEnumerationObject { let instanceEnumeration: VisualObjectInstanceEnumeration = []; if (options.objectName === Visual.ChartOpacityPropertyIdentifiers.objectName) { this.enumerateChartOpacity(instanceEnumeration); } else if (options.objectName === Visual.CategoryColorsPropertyIdentifiers.objectName) { this.enumerateCategoryProperties(instanceEnumeration); } return instanceEnumeration; } private enumerateCategoryProperties(instanceEnumeration: VisualObjectInstance[]): void { let slices = this.pie.slices; if (!slices || slices.length < 1) { return; } slices.forEach((slice: PieSlice) => { let selectionID: ISelectionId = slice.selectionID; let displayName: string = """" + slice.category; instanceEnumeration.push({ displayName, objectName: Visual.CategoryColorsPropertyIdentifiers.objectName, selector: (selectionID as powerbi.visuals.ISelectionId).getSelector(), properties: { fill: { solid: { color: slice.color } } } }) }) } private enumerateChartOpacity(instanceEnumeration: VisualObjectInstance[]): void { instanceEnumeration.push({ displayName: ""Opacity"", objectName: Visual.ChartOpacityPropertyIdentifiers.objectName, selector: null, properties: { opacity: { numeric: this.opacity } }, validValues: { opacity: { numberRange: { min: 10, max: 100 } } } }) } } } ",radius 68,"import { Router } from 'express'; import { getRepository, getCustomRepository, getConnection } from 'typeorm'; import Product from '../models/Product'; import ProductRepository from '../repositories/ProductRepository'; const productRouter = Router(); productRouter.post('/', async (request, response) => { try { const repo = getRepository(Product); const res = await repo.save(request.body); await getConnection().queryResultCache?.remove(['listProduct']) return response.status(201).json(res); } catch (err) { console.log('err.message :>> ', err.message); } }); productRouter.get('/', async (request, response) => { response.json(await getRepository(Product).find({cache:{id:'listProduct', milliseconds: 10000}})); }); productRouter.get('/:description', async (request, response) => { const [MASK] = getCustomRepository(ProductRepository); const res = await [MASK] .findByDescription(request.params.name); response.json(res); }); export default productRouter; ",repository 69,"declare var CameraPreview : any; interface Screen { orientation: any; } module StressBlasterApp { ""use strict""; class fireAnim { div: HTMLElement; snd: any; constructor (pgX : number, pgY : number) { this.div = document.createElement('div'); this.div.classList.add('image-wrapper'); this.div.style.left = pgX + 'px'; this.div.style.top = pgY + 'px'; this.div.innerHTML = ''; document.body.appendChild(this.div); this.snd = new Audio('snd/explosion.mp3'); setTimeout(this.startFade.bind(this), 1000); this.snd.play(); } startFade():void { this.div.classList.add('fade-out'); setTimeout(this.finishFade.bind(this), 1000); this.snd = null; } finishFade():void { this.div.remove(); } } class shotAnim { div: HTMLElement; snd: any; constructor (pgX : number, pgY : number) { this.div = document.createElement('div'); this.div.classList.add('image-wrapper'); this.div.style.left = pgX + 'px'; this.div.style.top = pgY + 'px'; this.div.innerHTML = ''; document.body.appendChild(this.div); this.snd = new Audio('snd/gunshot.mp3'); setTimeout(this.startFade.bind(this), 1000); this.snd.play(); } startFade():void { this.div.classList.add('fade-out'); setTimeout(this.finishFade.bind(this), 1000); this.snd = null; } finishFade():void { this.div.remove(); } } class mushAnim { div: HTMLElement; snd: any; counter: number; constructor (pgX : number, pgY : number) { this.div = document.createElement('div'); this.div.classList.add('image-wrapper'); this.div.style.left = pgX + 'px'; this.div.style.top = (pgY-60) + 'px'; this.counter = 0; document.body.appendChild(this.div); this.snd = new Audio('snd/blast.mp3'); this.snd.play(); this.animate(); } animate():void { ++this.counter; this.div.innerHTML = ''; if (this.counter == 25) { setTimeout(this.stop.bind(this), 100); } else { setTimeout(this.animate.bind(this), 100); } } stop():void { this.div.remove(); this.snd = null; } } class bloodAnim { div: HTMLElement; snd: any; counter: number; constructor (pgX : number, pgY : number) { this.div = document.createElement('div'); this.div.classList.add('image-wrapper'); this.div.style.left = pgX + 'px'; this.div.style.top = pgY + 'px'; this.counter = 0; document.body.appendChild(this.div); this.snd = new Audio('snd/headchop.mp3'); this.snd.play(); this.animate(); } animate():void { ++this.counter; this.div.innerHTML = ''; if (this.counter == 9) { setTimeout(this.stop.bind(this), 150); } else { setTimeout(this.animate.bind(this), 150); } } stop():void { this.div.remove(); this.snd = null; } } const ICO = 0; const FACTORY = 1; export module Application { var weapon : number; var arsenal = [ [ ""explode-ico.png"", function(x,y) { return new fireAnim(x,y); } ], [ ""mushroom-ico.png"", function(x,y) { return new mushAnim(x,y); } ], [ ""blood-ico.png"", function(x,y) { return new bloodAnim(x,y); } ], [ ""gun-ico.png"", function(x,y) { return new shotAnim(x,y); } ], [ null, null ] ]; export function initialize() { document.addEventListener('deviceready', onDeviceReady, false); weapon = 0; } function stopCamera() { CameraPreview.stopCamera(); } function rotateIt() { stopCamera(); startCamera(); } function switchCamera(e : Event){ console.log('SWITCHING CAMERAS********************'); CameraPreview.switchCamera(); e.stopPropagation(); var snd = new Audio('snd/sw_camera.mp3'); snd.play(); setTimeout(function() { snd = null; },1000); } function switchWeapon(e : Event){ console.log('SWITCHING WEAPON********************'); weapon = weapon + 1; if (arsenal[weapon][ICO] == null) weapon = 0; var [MASK] : any = document.getElementById('switchWeaponButton'); [MASK] .src = ""img/"" + arsenal[weapon][ICO]; e.stopPropagation(); var snd = new Audio('snd/sw_tool.mp3'); snd.play(); setTimeout(function() { snd = null; },1000); } function shootIt(e : MouseEvent) { var factory : any = arsenal[weapon][FACTORY]; factory(e.pageX,e.pageY); } function startCamera() { console.log('START CAMERA ****************************************'); console.log('Width: ' + window.screen.width); console.log('Width: ' + window.screen.height); console.log('Orientation is ' + screen.orientation.type); console.log('START CAMERA ****************************************'); CameraPreview.startCamera({x: 0, y: 0, width: window.screen.width, height: window.screen.height, camera: ""back"", tapPhoto: false, previewDrag: false, toBack: true}); } function onDeviceReady() { // Handle the Cordova pause and resume events document.addEventListener('pause', onPause, false); document.addEventListener('resume', onResume, false); startCamera(); document.getElementById('switchCameraButton').addEventListener('click', switchCamera.bind(this), false); document.getElementById('switchWeaponButton').addEventListener('click', switchWeapon.bind(this), false); document.addEventListener('click', shootIt.bind(this), false); window.addEventListener('orientationchange', rotateIt.bind(this), false); } function onPause() { // TODO: This application has been suspended. Save application state here. console.log('************* PAUSE APPLICATION *****************'); } function onResume() { // TODO: This application has been reactivated. Restore application state here. console.log('************* RESUME APPLICATION *****************'); } } window.onload = function () { Application.initialize(); } } ",button 70,"/** * These interfaces make it easier to ensure merging standards. */ export interface IMergeable { mergeable: (other: IMergeable) => boolean; merge: (other: IMergeable) => void; } export const MergeProperties = (property1: any, property2: any): any => { if (typeof property1 !== typeof property2) { console.log(property1 + "" and "" + property2 + "" have a type mismatch, since "" + typeof property1 + "" is not "" + typeof property2); return property1; } // Merge arrays. if (property1 instanceof Array) { const addToArray = ( [MASK] : any) => { for (const value of mergedArray) { if (value === [MASK] ) { return; } } mergedArray.push( [MASK] ); }; const mergedArray = Array.from(property1); for (const value of property2) { addToArray(value); } } if (property1) { if (property2) { if (property1 !== property1) { console.log(""Conflicting values between "" + property1 + "" and "" + property2); } return property1; } else { return property1; } } else { return property2; } }; ",toAdd 71,"// The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below import * as vscode from 'vscode'; // This method is called when your extension is activated // Your extension is activated the very first time the command is executed export function activate(context: vscode.ExtensionContext) { // Regular expression to match HSL values without hsl() wrapper const hslRegex = /(\d{1,3})\s*([\d.]+)%\s*([\d.]+)%/g; // Register color provider for CSS const disposable = vscode.languages.registerColorProvider('css', { provideDocumentColors( [MASK] : vscode.TextDocument): vscode.ProviderResult { const text = [MASK] .getText(); const colors: vscode.ColorInformation[] = []; let match; while ((match = hslRegex.exec(text)) !== null) { console.log(match); const colorRange = new vscode.Range( [MASK] .positionAt(match.index), [MASK] .positionAt(match.index + match[0].length) ); const hue = parseInt(match[1], 10); const saturation = parseFloat(match[2]) / 100; const lightness = parseFloat(match[3]) / 100; // Convert HSL to RGB for the color picker const color = hslToRgb(hue, saturation, lightness); const colorInfo = new vscode.ColorInformation(colorRange, color); colors.push(colorInfo); } return colors; }, provideColorPresentations(color: vscode.Color, context): vscode.ProviderResult { const { red, green, blue } = color; const hslArr = rgb2hsl(red, green, blue); const hsl = { h: Math.round(hslArr[0] * 10) / 10, s: Math.round(hslArr[1] * 1000) / 10, l: Math.round(hslArr[2] * 1000) / 10 }; const presentation = new vscode.ColorPresentation(`${hsl.h} ${hsl.s}% ${hsl.l}%`); return [presentation]; } }); context.subscriptions.push(disposable); } function hslToRgb(h: number, s: number, l: number): vscode.Color { let r, g, b; if (s === 0) { r = g = b = l; // achromatic } else { const q = l < 0.5 ? l * (1 + s) : l + s - l * s; const p = 2 * l - q; r = hueToRgb(p, q, h + 1 / 3); g = hueToRgb(p, q, h); b = hueToRgb(p, q, h - 1 / 3); } return new vscode.Color(r, g, b, 1.0); } function hueToRgb(p: number, q: number, t: number) { if (t < 0) { t += 1; } if (t > 1) { t -= 1; } if (t < 1 / 6) { return p + (q - p) * 6 * t; } if (t < 1 / 2) { return q; } if (t < 2 / 3) { return p + (q - p) * (2 / 3 - t) * 6; } return p; } function rgb2hsl(r: number, g: number, b: number) { let v = Math.max(r, g, b), c = v - Math.min(r, g, b), f = (1 - Math.abs(v + v - c - 1)); let h = c && ((v === r) ? (g - b) / c : ((v === g) ? 2 + (b - r) / c : 4 + (r - g) / c)); return [60 * (h < 0 ? h + 6 : h), f ? c / f : 0, (v + v - c) / 2]; } export function deactivate() { }",document 72,"/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ import path from ""path""; import { existsSync } from ""fs""; import { mkdir, writeFile, rm } from ""node:fs/promises""; import { handler } from ""../index""; const __assetDirectoryPath = path.join(__dirname, ""mock-dir""); const __outputPath = path.join(__dirname, ""mock-dir-output""); describe(""Handler"", () => { beforeAll(async function Arrange() { await rm(__assetDirectoryPath, { recursive: true, force: true }); await rm(__outputPath, { recursive: true, force: true }); await mkdir(__assetDirectoryPath); await mkdir(__outputPath); }); it(""should fail in absence of path inputs "", async function () { expect.assertions(2); await expect(handler("""", """")).rejects.toThrowError(""undefined input path""); await expect(handler(undefined, undefined)).rejects.toThrowError(""undefined input path""); }); it(""should fail for invalid cdk asset path"", async function () { expect.assertions(1); await expect(handler(""invalidPath"", __outputPath)).rejects.toThrowError(/(ENOENT).+(invalidPath)/g); }); it(""should succeed if cdk assets not found"", async function () { await expect(handler(__assetDirectoryPath, ""invalidPath"")).resolves.toBeUndefined(); }); it(""should fail for invalid output path"", async function () { // Arrange expect.assertions(1); const mockAssetPath = path.join(__assetDirectoryPath, ""./asset.cdkAsset.zip""); await writeFile(mockAssetPath, ""NoOp""); // Act, Assert await expect(handler(__assetDirectoryPath, ""invalidPath"")).rejects.toThrowError(/(ENOENT).+(invalidPath)/g); // Cleanup await rm(mockAssetPath); }); it(""should successfully stage zip for valid paths"", async function () { const [MASK] = ""asset.cdkAsset.zip""; const mockAssetPath = path.join(__assetDirectoryPath, [MASK] ); await writeFile(mockAssetPath, ""NoOp""); await expect(handler(__assetDirectoryPath, __outputPath)).resolves.toBeUndefined(); expect(existsSync(path.join(__outputPath, [MASK] .split(""asset."").pop()!))).toBe(true); }); afterAll(async function Cleanup() { await rm(__assetDirectoryPath, { recursive: true, force: true }); await rm(__outputPath, { recursive: true, force: true }); }); }); ",zipName 73,"import * as vscode from ""vscode""; import * as child_process from ""child_process""; import * as fs from ""fs""; import * as path from ""path""; import KeilProject from ""./project""; export function activate(context: vscode.ExtensionContext) { const subscriber = context.subscriptions; const channel = vscode.window.createOutputChannel(""ehong-dev""); channel.appendLine(""ehong dev plugin activated!""); channel.show(); let project = new KeilProject(channel); var workspaceFolders = vscode.workspace.workspaceFolders; if (workspaceFolders && workspaceFolders.length > 0) { project.load(workspaceFolders[0].uri.fsPath); } const prevent = async ( [MASK] : () => Promise) => { if (project.running) { vscode.window.showWarningMessage(""任务正在运行, 请稍后...""); return; } project.running = true; try { await [MASK] .call(project); } finally { project.running = false; } }; /* 监控 ehong.json 文件 的保存事件 */ subscriber.push( vscode.workspace.onDidSaveTextDocument(async (event) => { if (event.fileName.endsWith(""ehong.json"")) { let workspace = vscode.workspace.getWorkspaceFolder(event.uri); if (workspace) { let work_dir = path.resolve(event.uri.fsPath, ""..""); if (project.work_dir === work_dir) { // 重新加载 project.load(work_dir); } } } }) ); /* 注册 编译项目 命令 */ subscriber.push( vscode.commands.registerCommand(""ehong-dev.project.build"", () => prevent(project.build) ) ); /* 注册 重新编译项目 命令 */ subscriber.push( vscode.commands.registerCommand(""ehong-dev.project.rebuild"", () => prevent(project.rebuild) ) ); /* 注册 清理项目 命令 */ subscriber.push( vscode.commands.registerCommand(""ehong-dev.project.clean"", () => prevent(project.clean) ) ); } // This method is called when your extension is deactivated export function deactivate() {} function get_ehong_config( workspace: vscode.WorkspaceFolder | undefined ): string | undefined { if (workspace) { let config_file = path.normalize(workspace.uri.fsPath + ""/ehong.json""); if (fs.existsSync(config_file)) { return config_file; } } } function communicateWithExternalProcess( channel: vscode.OutputChannel, exe_path: string, eh_configs: string[] ) { let uv4_path = vscode.workspace.getConfiguration(""ehong"").get(""Uv4Path"") || """"; const child = child_process.spawn(exe_path, [ ""--uv4-path"", uv4_path, ""--configs"", eh_configs.join("" ""), ]); child.stdout.on(""data"", (data) => { let s: string = data.toString(); channel.append(s); if (s.startsWith(""TargetName: "")) { s = s.slice(""TargetName: "".length); var v = s.indexOf(""\r\n""); var v = s.indexOf(""\r\n""); if (v !== -1) { s = s.slice(0, v); } console.log(`TargetName: ${s}`); } console.log(); }); child.stderr.on(""data"", (data) => { channel.append(data.toString()); }); child.on(""close"", (code) => { channel.append(`External process exited with code ${code}`); let command = `${exe_path} --uv4-path ${uv4_path} --configs ${eh_configs.join( "" "" )}`; child_process .exec( ""C:/Keil_v5/UV4/UV4.exe -r D:/work/6226master/applications/ble_app_findmy/keil/ble_app_findmy.uvprojx -j0 -t ble_app_findmy -o test_uv4.txt"" ) .once(""exit"", () => { // setTimeout(() => clearInterval(timer), 100); console.log(""exe exited""); // res(); }); // const task = new vscode.Task( // { type: ""keil-task"" }, // vscode.TaskScope.Global, // ""build_task"", // ""shell"" // ); // // // task.execution = new vscode.ShellExecution( // // cmdPrefixSuffix + commandLine + cmdPrefixSuffix // ""C:/Keil_v5/UV4/UV4.exe -r applications/ble_app_findmy/keil/ble_app_findmy.uvprojx -j0 -t ble_app_findmy"" // ); // task.isBackground = false; // // task.problemMatchers = this.getProblemMatcher(); // task.presentationOptions = { // echo: false, // focus: false, // clear: true, // }; // vscode.tasks.executeTask(task); }); } ",action 74,"import { InteractionType, InteractionResponseType, InteractionResponseFlags, verifyKey, } from 'discord-interactions' export async function handleRequest(request: Request): Promise { const signature = request.headers.get('X-Signature-Ed25519')! const timestamp = request.headers.get('X-Signature-Timestamp')! const body = await request.clone().arrayBuffer() //prettier-ignore const [MASK] = verifyKey(body, signature, timestamp, 'your-public-key') if (! [MASK] ) { return new Response('bad request', { status: 401 }) } const interaction = await request.json() if (interaction.type === InteractionType.PING) { return respond({ type: InteractionType.PING, }) } return respond({ type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE, data: { flags: InteractionResponseFlags.EPHEMERAL, content: 'this is coming from a cloudflare worker!!', }, }) } const respond = (body: object) => new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status: 200, }) ",isValid 75,"/* * Copyright (c) 2022 Huawei Device 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. */ interface ReceiveObject{ obj : Object; spaces ?: string | number; } interface NativeConvertXml { new() : NativeConvertXml; convert(strXml : string, options ?: Object) : ReceiveObject; } interface ConvertXML { ConvertXml : NativeConvertXml; } declare function requireInternal(s : string) : ConvertXML; const convertXml = requireInternal('ConvertXML'); class ConvertXML { convertxmlclass : NativeConvertXml; constructor() { this.convertxmlclass = new convertXml.ConvertXml(); } convert(strXml : string, options ?: Object) { strXml = DealXml(strXml); let [MASK] = this.convertxmlclass.convert(strXml, options); let strEnd : string = ''; if ( [MASK] .hasOwnProperty('spaces')) { let space : string | number | undefined = [MASK] .spaces; delete [MASK] .spaces; } return [MASK] ; } } function DealXml(strXml : string) { let idx : number = 0; let idxSec : number = 0; let idxThir : number = 0; let idxCData : number = 0; let idxCDataSec : number = 0; while ((idx = strXml.indexOf(']]>', idxSec)) !== -1) { idxThir = strXml.indexOf('<', idx); strXml = DealPriorReplace(strXml, idx, idxThir); if (strXml.indexOf('<', idx) !== -1) { idxCData = strXml.indexOf('', idxCData); strXml = DealLaterReplace(strXml, idx, idxThir); idxCDataSec = idxSec; } } else { break; } } return strXml; } function DealPriorReplace(strXml : string, idx : number, idxThir : number) { let i : number = idx + 1; for (; i < idxThir ; i++) { let cXml : string = strXml.charAt(i); if (cXml !== '\n' && cXml !== '\v' && cXml !== '\t' && cXml !== ' ') { break; } } let j : number = idx + 1; for (; j < strXml.indexOf('<', idx) ; j++) { let cXml : string = strXml.charAt(j); if (i !== idxThir) { switch (cXml) { case '\n': strXml = strXml.substring(0, j) + '\\n' + strXml.substring(j + 1); break; case '\v': strXml = strXml.substring(0, j) + '\\v' + strXml.substring(j + 1); break; case '\t': strXml = strXml.substring(0, j) + '\\t' + strXml.substring(j + 1); break; default: break; } } else { strXml = strXml.substring(0, j) + strXml.substring(j + 1); --j; } } return strXml; } function DealLaterReplace(strXml : string, idx : number, idxThir : number) { let i : number = idx + 1; for (; i < idxThir ; i++) { let cXml : string = strXml.charAt(i) switch (cXml) { case '\n': strXml = strXml.substring(0, i) + '\\n' + strXml.substring(i + 1); break; case '\v': strXml = strXml.substring(0, i) + '\\v' + strXml.substring(i + 1); break; case '\t': strXml = strXml.substring(0, i) + '\\t' + strXml.substring(i + 1); break; default: break; } } return strXml; } export default { ConvertXML : ConvertXML }",converted 76,"/* * Copyright 2023 Collate. * 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. */ import { mergeAttributes, Node, nodeInputRule } from '@tiptap/core'; import { ReactNodeViewRenderer } from '@tiptap/react'; import { IMAGE_INPUT_REGEX } from '../../../../constants/BlockEditor.constants'; import ImageComponent from './component'; export interface ImageOptions { inline: boolean; allowBase64: boolean; HTMLAttributes: Record; } declare module '@tiptap/core' { interface Commands { image: { /** * Add an image */ setImage: (options: { src: string; alt?: string; title?: string; }) => ReturnType; }; } } export const Image = Node.create({ name: 'image', selectable: false, draggable: true, addOptions() { return { inline: false, allowBase64: false, HTMLAttributes: {}, }; }, inline() { return this.options.inline; }, group() { return this.options.inline ? 'inline' : 'block'; }, addAttributes() { return { src: { default: null, parseHTML: (element) => element.getAttribute('src')?.toString(), renderHTML: (attributes) => { if (!attributes.src) { return {}; } return { src: attributes.src, }; }, }, alt: { default: null, parseHTML: (element) => element.getAttribute('alt')?.toString(), renderHTML: (attributes) => { if (!attributes.alt) { return {}; } return { alt: attributes.alt, }; }, }, title: { default: null, parseHTML: (element) => element.getAttribute('title')?.toString(), renderHTML: (attributes) => { if (!attributes.title) { return {}; } return { title: attributes.title, }; }, }, }; }, parseHTML() { return [ { tag: this.options.allowBase64 ? 'img[src]' : 'img[src]:not([src^=""data:""])', }, ]; }, renderHTML({ HTMLAttributes }) { return [ 'img', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), ]; }, addNodeView() { return ReactNodeViewRenderer(ImageComponent); }, addCommands() { return { setImage: (options) => ({ commands }) => { return commands.insertContent({ type: this.name, attrs: options, }); }, }; }, addInputRules() { return [ nodeInputRule({ find: IMAGE_INPUT_REGEX, type: this.type, getAttributes: ( [MASK] ) => { const [, , alt, src, title] = [MASK] ; return { src, alt, title }; }, }), ]; }, }); ",match 77,"import React from ""react""; import {createGestureRecognizer} from ""./GestureService.ts""; import {GestureRecognizer} from ""@mediapipe/tasks-vision""; type Context = CanvasRenderingContext2D; interface BoardState { ctx: Context; stream: MediaStream; video: HTMLVideoElement; board: HTMLCanvasElement; lastVideoTime: number; } function validBoardState(ctx: Context | null, stream: MediaStream | null, video: HTMLVideoElement | null, board: HTMLCanvasElement | null): boolean { const validCtx = ctx !== null; const validStream = stream !== null; const validVideo = video !== null; const validBoard = board !== null; if (!validCtx) { console.error('Context in board state is null'); } if (!validStream) { console.error('Stream in board state is null'); } if (!validVideo) { console.error('Video in board state is null'); } if (!validBoard) { console.error('Board in board state is null'); } return validCtx && validStream && validVideo && validBoard; } // initialize the media stream and the whiteboard returning the state export async function initBoardState( [MASK] : React.RefObject, boardRef: React.RefObject, width: number, height: number): Promise { const video: HTMLVideoElement | null = [MASK] .current; const board: HTMLCanvasElement | null = boardRef.current; let ctx: Context | null = null; let stream: MediaStream | null = null; if (video && board) { stream = await initMedia(video); ctx = initBoard(board, width, height); } else { return Promise.reject('Invalid video or board element'); } return new Promise((resolve, reject) => { if (validBoardState(ctx, stream, video, board)) { resolve({ ctx: ctx as Context, stream: stream as MediaStream, video: video as HTMLVideoElement, board: board as HTMLCanvasElement, lastVideoTime: -1 }); } else { reject('Invalid board state'); } }); } // get user permissions to access camera // set the video element to the stream async function initMedia(video: HTMLVideoElement): Promise { const constraints: MediaStreamConstraints = { video: true, audio: false } const stream = await navigator.mediaDevices.getUserMedia(constraints); video.srcObject = stream; return stream; } // initialize the whiteboard function initBoard(board: HTMLCanvasElement, width: number, height: number): Context | null { const ctx = board.getContext('2d'); if (ctx) { board.width = width; board.height = height; ctx.fillStyle = 'white'; ctx.fillRect(0, 0, width, height); return ctx; } else { return null; } } export async function main(boardState: BoardState): Promise { const gestureRecognizer = await createGestureRecognizer(); setInterval(() => { loop(boardState, gestureRecognizer); }, 100); } async function loop(boardState: BoardState, gestureRecognizer: GestureRecognizer): Promise { let results = null; if (boardState.video.currentTime !== boardState.lastVideoTime) { boardState.lastVideoTime = boardState.video.currentTime; // get time in ms const nowMS: number = Date.now(); // get the results from the gesture recognizer results = gestureRecognizer.recognizeForVideo(boardState.video, nowMS); } if (results) { console.log(results); } else { console.log('No results'); } }",videoRef 78,"import { ethers } from ""hardhat""; import { Signer } from ""ethers""; import { getStorageAt, getProof, getBlockByNumber, getBlockHashByNumber, BlockHash } from ""../../library/source/demo""; import * as OracleSdk from '@keydonix/uniswap-oracle-sdk'; describe(""Token"", function () { let accounts: Signer[]; beforeEach(async function () { accounts = await ethers.getSigners(); }); it(""should do something right"", async function () { // Do something with the accounts const SushiOracle = await ethers.getContractFactory(""SushiOracle""); const sushiOracle = await SushiOracle.deploy(); await sushiOracle.deployed(); const JSON_RPC = 'https://eth-mainnet.alchemyapi.io/v2/akJ4Iz9CBxJ6HduDFaNUwwg1igCzQmDk' const provider = new ethers.providers.JsonRpcProvider(JSON_RPC) const address = BigInt(""0xbb2b8038a1640196fbe3e38816f3e67cba72d940"") const token0 = BigInt(""0x"") const [MASK] = BigInt(""12680299"") const proof = await OracleSdk.getProof(getStorageAt, getProof, getBlockByNumber, address, token0, [MASK] ) const block = await getBlockHashByNumber( [MASK] ) // const result = await sushiOracle.getPriceRaw(ethers.utils.hexValue(address), true, proof, ethers.utils.hexValue(block.hash)) const result = await sushiOracle.prepareAccountDetailsBytes(ethers.utils.hexValue(address), proof, ethers.utils.hexValue(block.hash)) console.log(result) }); }); ",blockNumber 79,"// Air quality dashboard import * as VIAM from ""@viamrobotics/sdk""; import { BSON } from ""bson""; async function main() { const opts: VIAM.ViamClientOptions = { credential: { type: ""api-key"", // Key with location operator permissions // Replace (including angle brackets) payload: """", // Replace (including angle brackets) authEntity: """", }, }; const orgID: string = """"; // Replace const locationID: string = """"; // Replace // Instantiate data_client and get all // data tagged with ""air-quality"" from your location const client = await VIAM.createViamClient(opts); const [MASK] = client.dataClient; const query = { $match: { tags: ""air-quality"", location_id: locationID, organization_id: orgID, }, }; const match = { $group: { _id: ""$robot_id"" } }; // Get a list of all the IDs of machines that have collected air quality data const BSONQueryForMachineIDList = [ BSON.serialize(query), BSON.serialize(match), ]; let machineIDs: any = await [MASK] ?.tabularDataByMQL( orgID, BSONQueryForMachineIDList, ); // Get all the air quality data const BSONQueryForData = [BSON.serialize(query)]; let thedata: any = await [MASK] ?.tabularDataByMQL( orgID, BSONQueryForData, ); // Instantiate the HTML block that will be returned // once everything is appended to it let htmlblock: HTMLElement = document.createElement(""div""); // Display the relevant data from each machine to the dashboard for (const mach of machineIDs) { let insideDiv: HTMLElement = document.createElement(""div""); let avgPM: number = await getLastFewAv(thedata, mach._id); // Color-code the dashboard based on air quality category let level: string = ""blue""; switch (true) { case avgPM < 12.1: { level = ""good""; break; } case avgPM < 35.5: { level = ""moderate""; break; } case avgPM < 55.5: { level = ""unhealthy-sensitive""; break; } case avgPM < 150.5: { level = ""unhealthy""; break; } case avgPM < 250.5: { level = ""very-unhealthy""; break; } case avgPM >= 250.5: { level = ""hazardous""; break; } } // Create the HTML output for this machine insideDiv.className = ""inner-div "" + level; insideDiv.innerHTML = ""

"" + mach._id + "": "" + avgPM.toFixed(2).toString() + "" μg/m3

""; htmlblock.appendChild(insideDiv); } // Output a block of HTML with color-coded boxes for each machine return document.getElementById(""insert-readings"").replaceWith(htmlblock); } // Get the average of the last five readings from a given sensor async function getLastFewAv(alltheData: any[], machineID: string) { // Get just the data from this machine let thedata = new Array(); for (const entry of alltheData) { if (entry.robot_id == machineID) { thedata.push({ PM25: entry.data.readings[""pm_2.5""], time: entry.time_received, }); } } // Sort the air quality data from this machine // by timestamp thedata = thedata.sort(function (a, b) { let x = a.time.toString(); let y = b.time.toString(); if (x < y) { return -1; } if (x > y) { return 1; } return 0; }); // Add up the last 5 readings collected. // If there are fewer than 5 readings, add all of them. let x = 5; // The number of readings to average over if (x > thedata.length) { x = thedata.length; } let total = 0; for (let i = 1; i <= x; i++) { const reading: number = thedata[thedata.length - i].PM25; total += reading; } // Return the average of the last few readings return total / x; } main().catch((error) => { console.error(""encountered an error:"", error); }); ",myDataClient 80,"import * as forge from ""node-forge""; import * as fs from ""node:fs""; export default class SelfSigned { public static setupSelfSigned(sslMode = ""./"") { const certPath = ""./generated-cert-1""; if(fs.existsSync(certPath)) { return JSON.parse(fs.readFileSync(certPath, { encoding: ""utf8"", flag: ""r"" })); } let key; let cert; const pki = forge.default.pki; // generate a key pair or use one you have already const [MASK] = pki.rsa.generateKeyPair(2048); // create a new certificate const crt = pki.createCertificate(); // fill the required fields crt.publicKey = [MASK] .publicKey; crt.serialNumber = '01'; crt.validity.notBefore = new Date(); crt.validity.notAfter = new Date(); crt.validity.notAfter.setFullYear(crt.validity.notBefore.getFullYear() + 40); // use your own attributes here, or supply a csr (check the docs) const attrs = [ { name: 'commonName', value: 'dev.socialmail.in' }, { name: 'countryName', value: 'IN' }, { shortName: 'ST', value: 'Maharashtra' }, { name: 'localityName', value: 'Navi Mumbai' }, { name: 'organizationName', value: 'NeuroSpeech Technologies Pvt Ltd' }, { shortName: 'OU', value: 'Test' } ]; // here we set subject and issuer as the same one crt.setSubject(attrs); crt.setIssuer(attrs); // the actual certificate signing crt.sign( [MASK] .privateKey); // now convert the Forge certificate to PEM format cert = pki.certificateToPem(crt); key = pki.privateKeyToPem( [MASK] .privateKey); const json = { key, cert }; fs.writeFileSync(certPath, JSON.stringify(json), ""utf8""); return json; } }",keys 81,"import { DynamoDBClientConfig } from '@aws-sdk/client-dynamodb'; import { APIGatewayEvent, APIGatewayProxyHandler, Context } from 'aws-lambda'; import 'source-map-support/register.js' import { deleteAlarm } from '@shared/core/usecase/alarm-service.mjs'; import { ArgumentError } from '@shared/core/entity/argument-error.mjs'; import { DynamoDBAlarmRepository } from '@shared/core/infra/dynamodb-alarm-repository.mjs'; type RequestBody= { device_token: string; } export const handler: APIGatewayProxyHandler = async ( [MASK] : APIGatewayEvent, _context: Context) => { try { const dynamoDBConfig: DynamoDBClientConfig = { region: 'ap-northeast-1' }; const alarmRepository = new DynamoDBAlarmRepository(dynamoDBConfig, process.env.ALARM_TABLE_NAME!); const params = [MASK] .body ? JSON.parse( [MASK] .body) : {}; const { device_token }: RequestBody = params; await deleteAlarm( alarmRepository, device_token ); return { statusCode: 200, body: JSON.stringify({ message: 'アラームを更新しました。' }), }; } catch (error: any) { if(error instanceof ArgumentError) { return { statusCode: 400, body: JSON.stringify({ message: 'アラームの更新に失敗しました。', error: error.message || '不明なエラーが発生しました', }), }; } return { statusCode: 500, body: JSON.stringify({ message: 'アラームの更新に失敗しました。', error: error.message || '不明なエラーが発生しました', }), }; } };",event 82,"import { ROLES } from ""src/components/RoleSelect""; import { withAnyRole } from ""src/lib/auth""; import { createApiClient } from ""src/lib/oasst_client_factory""; import prisma from ""src/lib/prismadb""; /** * Update's the user's data in the database. Accessible only to admins. */ const handler = withAnyRole([""admin"", ""moderator""], async (req, res, token) => { const { id, user_id, notes, role, show_on_leaderboard } = req.body; // mod can't update user role to mod or admin if (token.role === ROLES.MODERATOR && (role === ROLES.MODERATOR || role === ROLES.ADMIN)) { return res.status(403).json({}); } const [MASK] = await createApiClient(token); await prisma.user.update({ where: { id }, data: { role }, }); // Tell the backend the user's enabled or not enabled status. await [MASK] .set_user_status(user_id, role !== ""banned"", notes, show_on_leaderboard); res.status(200).json({}); }); export default handler; ",oasstApiClient 83,"interface HtmlClassChangerOptions { baseClass: string, list: { selector: string, class: string }[] } export class HtmlClassChanger { private html: HTMLElement; constructor(private readonly config: HtmlClassChangerOptions) { this.html = document.querySelector('html'); this.setUp(); } private setUp() { this.config.list.forEach((conf, index: number) => { new Waypoint({ element: document.querySelector(conf.selector), offset: 200, handler: ( [MASK] : string) => { if ( [MASK] == 'up') { this.html.classList.remove(conf.class); const prevClass = this.getPreviousClass(index); if (prevClass) { this.html.classList.add(prevClass); } } else { const prevClass = this.getPreviousClass(index); if (prevClass) { this.html.classList.remove(prevClass); } this.html.classList.add(conf.class); } } }); }); } private getPreviousClass(from: number) { if (from == 0) { return this.config.baseClass; } else { return this.config.list[from - 1].class; } } } ",dir 84,"import { NavController, NavParams, Platform } from 'ionic-angular'; import {Component} from '@angular/core'; import { HomePage } from '../home/home'; @Component({ selector: 'page-currency', templateUrl: 'currency.html', }) export class CurrencyPage{ tileWidth: number = 50; constructor(public nc:NavController, public np:NavParams, public [MASK] : Platform){ // elkéred a width-et, kiszámolod egy rész szélességét var w= [MASK] .width(); this.tileWidth = this.calculateDaTileSizeMahNigga(w); } dollar(){ this.nc.push(HomePage,{id: '?base=USD'}); } euro(){ this.nc.push(HomePage,{id: '?base=EUR'}); } rubel(){ this.nc.push(HomePage,{id: '?base=RUB'}); } yen(){ this.nc.push(HomePage,{id: '?base=JPY'}); } forint(){ this.nc.push(HomePage,{id: '?base=HUF'}); } pound(){ this.nc.push(HomePage,{id: '?base=GBP'}); } calculateDaTileSizeMahNigga(w) : number{ let thisDaResult_Yo = ((w-32)/2)-23.5; console.log(thisDaResult_Yo); return thisDaResult_Yo; } }",platform 85,"import { createAsyncThunk, createSlice } from ""@reduxjs/toolkit""; import { deleteUserDataService } from ""../../services/login""; import errorHandler from ""../../utils/error-handler""; interface IDeleteUserState { isDeleted?: boolean; loading: boolean; error?: any; } const initialState: IDeleteUserState = { isDeleted: false, loading: false, error: undefined, }; export const deleteUser = createAsyncThunk( ""User/deleteUser"", async ( [MASK] :string) => { try { const response = await deleteUserDataService( [MASK] ); return response.data; } catch (_error: any) { const errorMessage = errorHandler(_error); throw new Error(errorMessage); } } ); const slice = createSlice({ name: ""deleteUser"", initialState, reducers: { }, extraReducers(builder): void { builder.addCase(deleteUser.pending, (state) => { state.loading = true; state.isDeleted = false; state.error = undefined; }); builder.addCase(deleteUser.fulfilled, (state) => { state.loading = false; state.isDeleted = true; }); builder.addCase(deleteUser.rejected, (state, action: any) => { state.loading = false; state.isDeleted = false; const errorMessage = JSON.parse(action.error.message); state.error = errorMessage; }); }, }); export default slice.reducer; ",userName 86,"import * as oa from ""./openApi"" import * as oaPlus from ""./openApiPlus"" import * as sm from ""@ts-common/string-map"" import * as _ from ""@ts-common/iterator"" import * as ps from ""@ts-common/property-set"" import { Json, stringify } from ""@ts-common/json"" type OptionalProperties = { readonly [K in keyof T]+?: T[K] } function isJsonReference(v: oa.JsonReference|T): v is oa.JsonReference { const o: OptionalProperties = v return o.$ref !== undefined } /** * Returns an enum of the given parameter. * @param parameter an OpenAPI parameter * * TODO: the given parameter can have a `$ref` or a `schema`. The `schema` may have a `$ref` as well. */ function getParameterEnum(parameter: oa.Parameter): ReadonlyArray|undefined { if (parameter.in === ""body"") { // TODO: we may need to get it from `schema`. return undefined } // TODO: we may need to get it from `schema` as well. return parameter.enum } interface Context { readonly source: oaPlus.Main readonly discriminatorName?: string readonly discriminatorValue?: string } interface Tracked { readonly value: T readonly name: string } function tracked(source: oaPlus.Main, k: K): Tracked { return { value: source[k], name: k } } function resolve( t: Tracked|undefined>, ref: oa.JsonReference ): T|undefined { const value = t.value if (value === undefined) { // error return undefined } const split = ref.$ref.split(""/"") // tslint:disable-next-line:no-magic-numbers if (split.length !== 3) { // error return undefined } if (split[0] !== ""#"") { // error return undefined } if (split[1] !== t.name) { // error return undefined } // tslint:disable-next-line:no-magic-numbers return value[split[2]] } function getDiscriminatorParameter(discriminatorValue: string, parameter: oa.Parameter) { if (parameter.in === ""body"") { // TODO: should we fix schema to support `enum`? return parameter } else { return ps.copyCreate(parameter, { enum: () => [discriminatorValue] }) } } type ParameterArray = ReadonlyArray|undefined type Optional = { readonly value: T }|undefined function optional(value: T): Optional { return { value } } function getOptionalParameter( { discriminatorName, discriminatorValue }: Context, parameter: oa.Parameter ): oa.Parameter|undefined { const pName = parameter.name if (discriminatorValue !== undefined && pName === discriminatorName) { const pEnum = getParameterEnum(parameter) if (pEnum !== undefined) { if (_.find(pEnum, v => v === discriminatorValue) === undefined) { // the operation is not compatible with the given discriminator value. return undefined } return getDiscriminatorParameter(discriminatorValue, parameter) } // the discriminator parameter is not an enumeration // TODO: we may have an error/warning in this case // TODO: narrow the parameter } return parameter } type ParameterOrRef = oa.Parameter|oa.JsonReference function getOptionalParameterOrRef( discriminator: Context, parameter: ParameterOrRef ): ParameterOrRef|undefined { if (isJsonReference(parameter)) { const t = tracked(discriminator.source, ""parameters"") const p = resolve(t, parameter) if (p === undefined) { // can't resolve the parameter. return undefined } const op = getOptionalParameter(discriminator, p) // TODO: extract parameter from reference. We need to return `undefined` only if the // referenced parameter has no possible values return op === undefined ? undefined : parameter } return getOptionalParameter(discriminator, parameter) } // Parameter Objects // See also https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md function getOptionalParameters( discriminator: Context, parameters: ParameterArray ): Optional { if (parameters === undefined) { // no parameters return optional(parameters) } const result: ParameterOrRef[] = [] for (const p of parameters) { const op = getOptionalParameterOrRef(discriminator, p) if (op === undefined) { return undefined } result.push(op) } return optional(result) } function getOperation( discriminator: Context, operation: oa.Operation ): oa.Operation|undefined { const optionalParameters = getOptionalParameters(discriminator, operation.parameters) if (optionalParameters === undefined) { return undefined } const copy = ps.copyProperty(operation) return ps.create({ tags: copy, summary: copy, description: copy, externalDocs: copy, operationId: copy, produces: copy, consumes: copy, parameters: () => optionalParameters.value, responses: copy, schemes: copy, deprecated: copy, security: copy }) } function convertOperations( discriminator: Context, operations: oaPlus.Operations, ): oa.Operation|undefined { const operationArray = _.isArray(operations) ? operations : [operations] const result = _.toArray(_.filterMap(operationArray, o => getOperation(discriminator, o))) // TODO: if result.length > 1 then we have more than one operation for the given discriminator // value. return result.length === 0 ? undefined : result[0] } type Method = ""get""|""put""|""post""|""delete""|""options""|""head""|""patch"" function convertPathItem( discriminator: Context, pathItem: oaPlus.PathItem ): oa.PathItem|undefined { const parameters = getOptionalParameters(discriminator, pathItem.parameters) if (parameters === undefined) { return undefined } // TODO: resolve `pathItem.$ref`. const operationFactory = (key: Method) => { const operations = pathItem[key] return operations === undefined ? undefined : convertOperations(discriminator, operations) } const copy = ps.copyProperty(pathItem) return ps.create({ $ref: copy, get: operationFactory, put: operationFactory, post: operationFactory, delete: operationFactory, options: operationFactory, head: operationFactory, patch: operationFactory, parameters: () => parameters.value }) } function convertPath(discriminator: Context, paths: oaPlus.Paths): oa.Paths { const entries = sm.entries(paths) const result = _.map( entries, ([path, pathItem]) => sm.entry(path, convertPathItem(discriminator, pathItem))) return sm.stringMap(result) } function convertParameterDefinitions( discriminator: Context, source: oa.ParameterDefinitions|undefined ): oa.ParameterDefinitions|undefined { if (source === undefined) { return undefined } const entries = sm.entries(source) const result = _.filterMap(entries, ([name, def]) => { const defResult = getOptionalParameter(discriminator, def) return defResult === undefined ? undefined : sm.entry(name, defResult) }) return sm.stringMap(result) } function convertOpenApi(context: Context): oa.Main { const source = context.source const copy = ps.copyProperty(source) return ps.create({ swagger: () => ""2.0"", info: copy, host: copy, basePath: copy, schemes: copy, consumes: copy, produces: copy, paths: () => convertPath(context, source.paths), definitions: copy, parameters: () => convertParameterDefinitions(context, source.parameters), responses: copy, security: copy, securityDefinitions: copy, tags: copy, externalDocs: copy }) } export function mergeEnum( a: ReadonlyArray, b: ReadonlyArray ): ReadonlyArray { const c = _.concat(a, b) const f = _.map(c, v => sm.entry(stringify(v), true)) const m = sm.stringMap(f) const result = _.map(sm.entries(m), ([n]) => n) return _.toArray(result) } export function convert(source: oaPlus.Main, discriminator: string): sm.StringMap { const parameters = source.parameters if (parameters === undefined) { return { default: convertOpenApi({ source }) } } const discriminatorParameters = _.filter(sm.values(parameters), p => p.name === discriminator) const [MASK] = _.filterMap(discriminatorParameters, getParameterEnum) const discriminatorEnum = _.reduce( [MASK] , mergeEnum) if (discriminatorEnum === undefined) { return { default: convertOpenApi({ source }) } } else { const entries = _.map( discriminatorEnum, value => sm.entry( stringify(value), convertOpenApi({ source, discriminatorName: discriminator, discriminatorValue: stringify(value) }) ) ) return sm.stringMap(entries) } } ",discriminatorEnums 87,"/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you 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. */ import { expect } from 'chai'; import { describe, it } from 'mocha'; import {Lang} from ""../../main/typescript/Lang""; import equalsIgnoreCase = Lang.equalsIgnoreCase; import assertType = Lang.assertType; import isFunc = Lang.isFunc; import isString = Lang.isString; import trim = Lang.trim; import strToArray = Lang.strToArray; import objToArray = Lang.objToArray; const jsdom = require(""jsdom""); const { JSDOM } = jsdom; const dom = new JSDOM(` Title
`) export const window = dom.window; class Probe { constructor() { } val1 = 1; val2 = 2; val3 = 3; } describe('Lang tests', () => { it('initializable', () => { const lang = Lang; expect(lang).to.exist; }); it('strToArray working', () => { const lang = Lang; let arr = strToArray(""hello.world.from.me"", /\./gi); expect(arr).to.exist; expect(arr.length).to.eq(4); expect(arr[3]).to.eq(""me""); }); it('trim working', () => { const lang = Lang; let origStr = "" hello world from me ""; let trimmed = trim(origStr); expect(trimmed).to.exist; expect(trimmed).to.eq(""hello world from me""); }); it('isString working', () => { const lang = Lang; expect(isString("" "")).to.be.true; expect(isString('')).to.be.true; expect(isString(null)).to.be.false; expect(isString(undefined)).to.be.false; expect(isString(function() {return true;})).to.be.false; expect(isString(new Probe())).to.be.false; }); it('isFunc working', () => { const lang = Lang; expect(isFunc(() => {})).to.be.true; expect(isFunc(function() {return true;})).to.be.true; expect(isFunc(""blarg"")).to.be.false; expect(isFunc(new Probe())).to.be.false; }); it('objToArray working', () => { const lang = Lang; let [MASK] = new Probe(); let resultArr = objToArray( [MASK] ); expect(assertType(resultArr, Array)).to.be.true; expect(resultArr.length).to.eq(0); [MASK] = window.document.body.querySelectorAll(""div""); resultArr = objToArray( [MASK] ); expect(resultArr.length).to.eq(4); expect(assertType(resultArr, Array)).to.be.true; }); it('equals ignore case test', () => { const lang = Lang; expect(equalsIgnoreCase(null, null)).to.be.true; expect(equalsIgnoreCase("""", """")).to.be.true; expect(equalsIgnoreCase(""null"", ""NuLL"")).to.be.true; expect(equalsIgnoreCase(""null "", ""NuLL"")).to.be.false; expect(equalsIgnoreCase(""null"", ""NuLL2"")).to.be.false; }); }); ",obj_probe 88,"import BaseController from ""./BaseController""; import {Route$PatternMatchedEvent} from ""sap/ui/core/routing/Route""; import JSONModel from ""sap/ui/model/json/JSONModel""; import Popover from ""sap/m/Popover""; import Fragment from ""sap/ui/core/Fragment""; import Input from ""sap/m/Input""; import {Button$PressEvent} from ""sap/m/Button""; import {Constants} from ""com/dhrubajyoti2006/openaiassistant/utils/Constants""; interface OpenAIToolCall { id: string, type: string, function: { name: string, arguments: string } } /** * @namespace com.dhrubajyoti2006.openaiassistant.controller */ export default class Detail extends BaseController { assistant_id: string; assistant: Object; run_id: string; _oPopover: Popover; currentRunStatus: string; public onInit(): void { this.getRouter().getRoute(""detail"") .attachPatternMatched((evt: Route$PatternMatchedEvent) => this._onRouteMatched(evt), this); this.setModel(new JSONModel({ ""mainModel"": [], }), ""mainModel""); } private getMainModel() { return this.getModel(""mainModel"") as JSONModel; } private setThreadId(thread_id: string) { (this.getModel(""mainModel"") as JSONModel).setProperty(""/thread_id"", thread_id); } private getThreadId(): string { return (this.getModel(""mainModel"") as JSONModel).getProperty(""/thread_id""); } public _onRouteMatched(oEvent: Route$PatternMatchedEvent) { const [MASK] = oEvent.getParameter(""arguments""); this.assistant_id = [MASK] [""assistant_id""]; // ToDo: This will later be implemented with promise.all() this.getAssistant(this.assistant_id); this.fileList(); } private updateFileListForAssistant() { if (this.assistant && this.assistant.file_ids && this.assistant.file_ids.length && (this.getModel(""mainModel"") as JSONModel).getProperty(""/allFilesList"") && (this.getModel(""mainModel"") as JSONModel).getProperty(""/allFilesList"").length) { const allFiles = (this.getModel(""mainModel"") as JSONModel).getProperty(""/allFilesList""); let files = allFiles.filter((item) => { return this.assistant.file_ids.includes(item.id); }); (this.getModel(""mainModel"") as JSONModel).setProperty(""/files"", files); } } public getAssistant(assistant_id: string): void { fetch(`${Constants.apiUrl}/getAssistant/${assistant_id}`) .then(response => response.text()) .then(data => { this.assistant = JSON.parse(data); this.updateFileListForAssistant() }) .catch(error => { console.error(""Error fetching data:"", error); // Handle any errors here }); } public onPressAddButton() { fetch(Constants.apiUrl + ""/createThread"") .then(response => response.text()) .then(data => { this.setThreadId(JSON.parse(data).id); }) .catch(error => { console.error(""Error fetching data:"", error); // Handle any errors here }); } public onPressFiles(oEvent: Button$PressEvent) { var oView = this.getView(); if (!this._oPopover) { const oFragmentController = { onCloseDialog: () => { this._oPopover.close(); } } Fragment.load({ id: oView.getId(), name: ""com.dhrubajyoti2006.openaiassistant.view.fragments.FilesPopover"", controller: oFragmentController }).then((oPopover: Popover) => { this._oPopover = oPopover; oView.addDependent(this._oPopover); this._oPopover.openBy(oEvent.getSource()); }); } else { this._oPopover.openBy(oEvent.getSource()); } } public deleteThread(thread_id: string): void { fetch(`${Constants.apiUrl}/deleteAssistant/${thread_id}`, { method: ""DELETE"" }) .then(response => response.text()) .then(data => { this.setThreadId(undefined); }) .catch(error => { console.error(""Error deleting data:"", error); // Handle any errors here }); } private onPressSend() { const content = (this.getView().byId(""idMessage"") as Input).getValue(); const thread_id = (this.getModel(""mainModel"") as JSONModel).getProperty(""/thread_id""); fetch(Constants.apiUrl + ""/createMessage"", { method: ""POST"", headers: { ""Content-Type"": ""application/json"" }, body: JSON.stringify({thread_id: thread_id, content: content}) }) .then(response => { if (!response.ok) { throw new Error(""Network response was not ok""); } return response.json(); // Assuming the response is JSON }) .then(data => { console.log(""Message created successfully"", data); (this.getView().byId(""idMessage"") as Input).setValue(""""); this.createRun(this.assistant_id, thread_id); }) .catch(error => { console.error(""Error creating message:"", error); }); } public createRun(assistant_id: string, thread_id: string): void { fetch(Constants.apiUrl + ""/createRun"", { method: ""POST"", headers: { ""Content-Type"": ""application/json"" }, body: JSON.stringify({assistant_id: assistant_id, thread_id: thread_id}) }) .then(response => { if (!response.ok) { throw new Error(""Network response was not ok""); } return response.json(); // Assuming the response is JSON }) .then(data => { this.run_id = data.id; this.currentRunStatus = ""started""; // this.startRunCheck(); console.log(""Message created successfully"", data); // Handle success, maybe update UI or clear form }) .catch(error => { console.error(""Error creating message:"", error); // Handle any errors here, maybe show user feedback }); } private onPressRefreshButton() { this.retrieveRun(this.getThreadId(), this.run_id); } private getWeather(location: string, unit: string) { return `This is the Temperature of ${location}: 25 degree ${unit}` } public handleFunctionToolCall(id: string, functionName: string, functionArguments: string) { const parsedArguments = JSON.parse(functionArguments); let returnValue = """"; if (functionName == ""get_weather"") { returnValue = this.getWeather(parsedArguments.location, parsedArguments.unit); } else { returnValue = ""Unable to find the functional name""; } return { tool_call_id: id, output: returnValue } } public handleToolCalls(tool_calls: Array) { let toolOutputs: Array = []; for (let i = 0; i < tool_calls.length; i++) { const tool_call = tool_calls[i]; if (tool_call.type == ""function"") { const functionResponse = this.handleFunctionToolCall(tool_call.id, tool_call.function.name, tool_call.function.arguments); toolOutputs.push(functionResponse); } } return toolOutputs; } public submitToolOutput(thread_id: string, run_id: string, toolOutputs: Array) { fetch(`${Constants.apiUrl}/submitToolOutputs/${thread_id}/${run_id}`, { method: ""POST"", headers: { ""Content-Type"": ""application/json"" }, body: JSON.stringify(toolOutputs) }) .then(response => response.text()) .then(data => { console.log(JSON.parse(data)); }) .catch(error => { console.error(""Error fetching data:"", error); // Handle any errors here }); } public retrieveRun(thread_id: string, run_id: string) { fetch(`${Constants.apiUrl}/retrieveRun/${thread_id}/${run_id}`) .then(response => response.text()) .then(data => { const response = JSON.parse(data); if (response?.required_action?.submit_tool_outputs?.tool_calls) { const tools_calls = response.required_action.submit_tool_outputs.tool_calls; const toolOutputs = this.handleToolCalls(tools_calls); this.submitToolOutput(thread_id, run_id, toolOutputs); } this.currentRunStatus = response.status; if (response.status === ""completed"") { this.messageList(this.getThreadId()); } }) .catch(error => { console.error(""Error fetching data:"", error); // Handle any errors here }); } public messageList(thread_id: string): void { fetch(`${Constants.apiUrl}/messageList/${thread_id}`) .then(response => response.text()) .then(data => { this.getMainModel().setProperty(""/messages"", JSON.parse(data).data.reverse()); }) .catch(error => { console.error(""Error fetching data:"", error); // Handle any errors here }); } public fileList(): void { fetch(Constants.apiUrl + ""/fileList"") .then(response => response.text()) .then(data => { (this.getModel(""mainModel"") as JSONModel).setProperty(""/allFilesList"", JSON.parse(data).data); this.updateFileListForAssistant(); }) .catch(error => { console.error(""Error fetching data:"", error); // Handle any errors here }); } // ToDo: To have a better solution later with something like signalR or so private startRunCheck() { const intervalId = setInterval(() => { this.retrieveRun(this.getThreadId(), this.run_id); if (this.currentRunStatus === ""completed"") { clearInterval(intervalId); } }, 500); // 500 milliseconds interval } } ",oArguments 89,"let calc = document.getElementById(""calc""); function isDigit(value: string): boolean { return value != "" "" && !isNaN(Number(value)); } function isOperator(ch: string): boolean { switch (ch) { case ""+"": return true; case ""-"": return true; case ""/"": return true; case ""*"": return true; default: return false; } } function processHighPriorityOperators(operands:number[], operators:string[]):void { if (operands && operators) { for (let i:number = 0; i < operators.length; i++) { let operator:string = operators[i]; let value:number; switch (operator) { case ""*"": { value = operands[i] * operands[i + 1]; operators.splice(i, 1); operands.splice(i, 1); operands[i] = value; i = -1; break; } case ""/"": { value = operands[i] / operands[i + 1]; operators.splice(i, 1); operands.splice(i, 1); operands[i] = value; i = -1; break; } } } } } function processLowPriorityOperators(operands:number[], operators:string[]):void { if (operands && operators) { for (let i:number = 0; i < operators.length; i++) { let operator:string = operators[i]; let value:number; switch (operator) { case ""+"": { value = operands[i] + operands[i + 1]; operators.splice(i, 1); operands.splice(i, 1); operands[i] = value; i = -1; break; } case ""-"": { value = operands[i] - operands[i + 1]; operators.splice(i, 1); operands.splice(i, 1); operands[i] = value; i = -1; break; } } } } } calc.onclick = function (evt) { let [MASK] = document.getElementById(""expression""); if ( [MASK] ) { let expression:string = ( [MASK] ).value + "" ""; //need to exclude last operand loosing let operand:string = """"; let operands:number[] = []; let operators:string[] = []; for (let i:number = 0; i < expression.length; i++) { if (isDigit(expression[i])) { operand += expression[i]; } else { if (operand) { operands.push(Number(operand)); operand = """"; } if (isOperator(expression[i])) { operators.push(expression[i]) } } } if (operands.length == operators.length + 1) { processHighPriorityOperators(operands, operators); processLowPriorityOperators(operands, operators); } else { alert(""Wrong expression.""); } let resultContainer = document.getElementById(""result""); resultContainer.innerHTML = operands[0].toString(); } else alert(""Can't find expression text box.""); };",expressionField 90,"import { Injectable } from '@angular/core'; import { AngularFireAuth } from '@angular/fire/auth'; import { BehaviorSubject, Observable, ReplaySubject, Subject } from 'rxjs'; import { tap, map, share } from 'rxjs/operators'; import { Router } from '@angular/router'; interface User { uid: string; email: string; } @Injectable({ providedIn: 'root' }) export class AuthService { public authErrorMessages$ = new BehaviorSubject(null); public isLoading$ = new BehaviorSubject(true); public user$ = new BehaviorSubject(null); private authState:User|null = null; constructor(private afAuth: AngularFireAuth, private router: Router) { this.isLoggedIn().subscribe(user => { if (user) { this.authState = user; this.router.navigateByUrl('/notes'); } }); } get authenticated(): boolean { return this.authState !== null; } get id(): string { return this.authenticated ? this.authState!.uid : ''; } private isLoggedIn(): Observable { return this.afAuth.authState.pipe( map((user:any) => { if (user) { const { email, uid } = user; this.user$.next({ email, uid }); return { email, uid }; } return null; }), tap(() => this.isLoading$.next(false)) ); } public getToken(): Observable { return this.afAuth.idToken; } public getCurrentUserUid(): any | null { // return this.afAuth.auth.currentUser.uid; return this.afAuth.currentUser.then((user:any) => {return user.uid}) } // public signUpFirebase({ email, password }) { public signUpFirebase( {email, password}:any){ this.isLoading$.next(true); this.handleErrorOrSuccess(() => { // return this.afAuth.auth.createUserWithEmailAndPassword(email, password); return this.afAuth.createUserWithEmailAndPassword(email,password) }); } // public loginFirebase({ email, password }) { public loginFirebase( {email, password }:any) { this.isLoading$.next(true); this.handleErrorOrSuccess(() => { // return this.afAuth.auth.signInWithEmailAndPassword(email, password); return this.afAuth.signInWithEmailAndPassword(email, password); }); } public logOutFirebase() { this.isLoading$.next(true); // return this.afAuth.auth.signOut(); return this.afAuth.signOut(); } private handleErrorOrSuccess( // cb: () => Promise cb: () => Promise ) { cb() .then(data => this.authenticateUser(data)) .catch(e => this.handleSignUpLoginError(e)); } private authenticateUser(UserCredential:any) { const { user: { email, uid } } = UserCredential; this.isLoading$.next(false); } private handleSignUpLoginError(error: { code: string; message: string }) { this.isLoading$.next(false); const [MASK] = error.message; this.authErrorMessages$.next( [MASK] ); } } ",errorMessage 91,"import {ChangeDetectorRef, Component, Input, OnChanges, OnInit, SimpleChange, SimpleChanges} from '@angular/core'; import {CategoryService} from '../../../services/category.service'; @Component({ selector: 'app-mini-budget', templateUrl: './mini-budget.component.html', styleUrls: ['./mini-budget.component.scss'] }) export class MiniBudgetComponent implements OnInit, OnChanges { @Input() data: number; onViewMonth: number; onViewYear = new Date().getFullYear(); categories = []; parametreString: string; constructor(private cd: ChangeDetectorRef, private categoryService: CategoryService) { } ngOnChanges( [MASK] : SimpleChanges) { const data: SimpleChange = [MASK] .data; this.onViewMonth = data.currentValue; this.parametreString = this.onViewYear + '-' + this.onViewMonth; this.categoryService.getCategoryLimit(this.parametreString).subscribe( data => { if (data) { console.log(data); this.categories = data['data']; } else{ this.categories = []; } } ); // this.categoryService.getCategories().subscribe( // data => { // if (data['data']) { // this.categories = data['data']; // } // } // ); } ngOnInit() { this.cd.detectChanges(); // this.categoryService.getCategories().subscribe( // data => { // this.categories = data['data']; // } // ); } } ",changes 92,"import axios from 'axios'; import { setupAxiosInterceptors } from '@/api/axiosConfig'; import { OrgUnitsResponseProps } from '@/types/orgUnits'; import { chromeOsDevicesResponseProps } from '@/types/chromeOsDevices'; import { googleListUsersResponseProps } from '@/types/user'; class DirectoryApi { private axiosInstance = axios.create({ baseURL: 'https://admin.googleapis.com/admin/directory/v1/customer/my_customer', }); constructor() { setupAxiosInterceptors(this.axiosInstance); } /** * TODO: instead of returning all, we return immediate children of a specific OU */ async listOrganizationalUnits(): Promise { let requestUrl = '/orgunits?type=ALL_INCLUDING_PARENT'; const response = await this.axiosInstance.get(requestUrl); return response.data; } async listChromeOsDevicesByOrgUnitId( [MASK] : string, ): Promise { let requestUrl = `/devices/chromeos?projection=BASIC&orgUnitPath=${ [MASK] }`; const response = await this.axiosInstance.get(requestUrl); return response.data; } async listGoogleUsersByOrgUnitPath( orgUnitPath: string, ): Promise { let requestUrl = `/users?query=orgUnitPath='${orgUnitPath}'&viewType=admin_view&projection=BASIC&customer=my_customer`; const response = await this.axiosInstance.get(requestUrl, { baseURL: 'https://admin.googleapis.com/admin/directory/v1', }); return response.data; } } export const directoryApi = new DirectoryApi(); ",orgUnitId 93,"import { Investments } from './yearly/types.js'; export const calculateInvestments = ( [MASK] : { Action: string; Name: string; Total: string }[], ): Investments => { const investments = { totalDeposit: 0, totalInvestedInSek: 0, investedInUSD: { amount: 0, amountInSek: 0, conversionRate: 0, }, investedInEUR: { amount: 0, amountInSek: 0, conversionRate: 0, }, investedInGBP: { amount: 0, amountInSek: 0, conversionRate: 0, }, investedInGBX: { amount: 0, amountInSek: 0, conversionRate: 0, }, }; for (const record of [MASK] ) { if (record['Action'] === 'Deposit') { investments.totalDeposit += parseFloat(record['Total']); } else if ( record['Currency conversion fee'] && (record['Action'] === 'Market buy' || record['Action'] === 'Limit buy') && record['Currency (Currency conversion fee)'] === 'SEK' ) { investments.totalInvestedInSek += parseFloat(record['Total']); if (record['Currency (Price / share)'] === 'USD') { investments.investedInUSD.amountInSek += parseFloat(record['Total']); investments.investedInUSD.amount += parseFloat(record['Price / share']) * parseFloat(record['No. of shares']); } else if (record['Currency (Price / share)'] === 'EUR') { investments.investedInEUR.amountInSek += parseFloat(record['Total']); investments.investedInEUR.amount += parseFloat(record['Price / share']) * parseFloat(record['No. of shares']); } else if (record['Currency (Price / share)'] === 'GBP') { investments.investedInGBP.amountInSek += parseFloat(record['Total']); investments.investedInGBP.amount += parseFloat(record['Price / share']) * parseFloat(record['No. of shares']); } else if (record['Currency (Price / share)'] === 'GBX') { investments.investedInGBX.amountInSek += parseFloat(record['Total']); investments.investedInGBX.amount += (parseFloat(record['Price / share']) * parseFloat(record['No. of shares'])) / 100; } } } // calculate conversion rates investments.investedInUSD.conversionRate = investments.investedInUSD.amountInSek / investments.investedInUSD.amount; investments.investedInEUR.conversionRate = investments.investedInEUR.amountInSek / investments.investedInEUR.amount; investments.investedInGBP.conversionRate = investments.investedInGBP.amountInSek / investments.investedInGBP.amount; investments.investedInGBX.conversionRate = investments.investedInGBX.amountInSek / investments.investedInGBX.amount; return investments; }; ",records 94,"import { Schema, model } from ""mongoose""; export enum Category { Amenagement = ""AMÉNAGEMENT"", Vehicule = ""VÉHICULE"", Application = ""APPLICATION"", Sensibilisation = ""SENSIBILISATION"", Ateliers = ""ATELIER"", Other = ""AUTRE"", } export enum Region { HautesPyrenees = ""hautes-pyrenees"", PyrennesAtlantiques = ""pyrenees-atlantiques"", Other = ""autre"", } export interface ISolution { name: string; description: string; category: Category; img: string; imgId: string; region: Region; coordinates: [number, number]; website?: string; contact?: string; details?: string; } const solutionSchema = new Schema({ name: { type: String, required: true, }, author: String, description: { type: String, required: true, }, category: { type: String, enum: Object.values(Category), required: true, }, img: { type: String, required: true, }, imgId: { type: String, required: true, }, region: { type: String, enum: Object.values(Region), required: true, }, coordinates: { type: [Number], required: true, }, website: { type: String, required: false, }, contact: { type: String, required: false, }, details: { type: String, required: false, }, }); solutionSchema.set(""toJSON"", { transform: (_document, [MASK] ) => { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call [MASK] .id = [MASK] ._id.toString(); delete [MASK] ._id; delete [MASK] .__v; }, }); export default model(""Solution"", solutionSchema); ",returnedObject 95,"/* * 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 * * https://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. */ /* eslint-disable no-console */ // The following block is required to make 'window' available within the service worker, since opentelemetry-core getEnv() depends on it. export type {}; interface MyServiceWorkerGlobalScope extends ServiceWorkerGlobalScope { window: unknown; } declare const self: MyServiceWorkerGlobalScope; if (self.constructor.name !== 'Window') { self.window = self; } import { ConsoleSpanExporter, SimpleSpanProcessor, } from '@opentelemetry/tracing'; import { WebTracerProvider } from '@opentelemetry/web'; // the following two 'require' are here for webpack. require('../manifest.json5'); require('../icons/otel-logo.png'); try { chrome.tabs.onUpdated.addListener( (tabId: number, changeInfo: chrome.tabs.TabChangeInfo) => { if (changeInfo.status !== 'loading') { return; } chrome.tabs.get(tabId, (tab: chrome.tabs.Tab) => { console.log(tab); if (tab.url) { if (chrome.scripting) { chrome.scripting.executeScript({ target: { allFrames: true, tabId, }, files: ['contentScript.js'], }); } else { console.log('execute'); chrome.tabs.executeScript(tabId, { file: 'contentScript.js', allFrames: true, }); } } }); } ); chrome.runtime.onMessage.addListener((request, [MASK] ) => { if ( request.type === 'OTEL_EXTENSION_SPANS' && request.extensionId === chrome.runtime.id && [MASK] .id === chrome.runtime.id ) { const spans = JSON.parse(request.spans); const consoleExporter = new ConsoleSpanExporter(); const provider = new WebTracerProvider(); provider.addSpanProcessor(new SimpleSpanProcessor(consoleExporter)); consoleExporter.export(spans, r => console.log(r)); } }); } catch (e) { console.log(e); } ",sender 96,"import { beforeEach, describe, expect, it, vi } from ""vitest""; import { DeltaTimeStrategy } from "".""; import { IngestionStrategy } from ""../../strategy""; describe(""DeltaTimeStrategy"", () => { // Mock implementation for nowResolver let mockTimeValue = 1000; const mockNowResolver = vi.fn(() => mockTimeValue); // Mock for createExecutionHandler const mockExecute = vi.fn(); // Test subject let deltaTimeStrategy: DeltaTimeStrategy; beforeEach(() => { // Reset mocks and create fresh instance for each test vi.clearAllMocks(); mockTimeValue = 1000; deltaTimeStrategy = new DeltaTimeStrategy(mockNowResolver); // Mock the createExecutionHandler method vi.spyOn(deltaTimeStrategy, ""createExecutionHandler"").mockReturnValue( mockExecute, ); }); it(""should be an instance of IngestionStrategy"", () => { expect(deltaTimeStrategy).toBeInstanceOf(IngestionStrategy); }); it(""should initialize with the provided nowResolver"", () => { expect(deltaTimeStrategy.nowResolver).toBe(mockNowResolver); }); it(""client method should return a start function"", () => { const customerId = ""test-customer-id""; const startFn = deltaTimeStrategy.client({ customerId, }); expect(typeof startFn).toBe(""function""); }); it(""start function should return a stop function"", () => { const customerId = ""test-customer-id""; const startFn = deltaTimeStrategy.client({ customerId, }); const stopFn = startFn(); expect(typeof stopFn).toBe(""function""); }); it(""should calculate correct delta time between start and stop"", () => { const customerId = ""test-customer-id""; const startFn = deltaTimeStrategy.client({ customerId, }); // First call to nowResolver (start time) const stopFn = startFn(); expect(mockNowResolver).toHaveBeenCalledTimes(1); // Simulate time passing mockTimeValue = 1500; // Call stop function const deltaTime = stopFn(); // Second call to nowResolver (end time) expect(mockNowResolver).toHaveBeenCalledTimes(2); // Check delta time calculation expect(deltaTime).toBe(500); // 1500 - 1000 = 500 }); it(""should call execution handler with correct context and customerId"", () => { const customerId = ""test-customer-id""; const startFn = deltaTimeStrategy.client({ customerId, }); // Start time = 1000 const stopFn = startFn(); // Simulate time passing mockTimeValue = 1300; // Call stop function stopFn(); // Verify execution handler was called with correct parameters expect(mockExecute).toHaveBeenCalledTimes(1); expect(mockExecute).toHaveBeenCalledWith( { deltaTime: 300 }, { customerId }, ); }); it(""should return the calculated delta time from stop function"", () => { const customerId = ""test-customer-id""; const startFn = deltaTimeStrategy.client({ customerId, }); // Start time = 1000 const stopFn = startFn(); // Simulate time passing mockTimeValue = 1800; // Call stop function and check return value const [MASK] = stopFn(); expect( [MASK] ).toBe(800); // 1800 - 1000 = 800 }); }); ",returnedDeltaTime 97,"import { JSONPrase } from '@/utils/utils'; export const paramsTableToJson = (data: any) => { let value = {}; if (Array.isArray(data)) { for (let i = 0; i < data.length; i++) { const item = data[i]; if (item.name) { const type = item.type.type; if (type !== 'string') { value[item.name] = JSONPrase(item.value); } else { value[item.name] = item.value?.toString() || null; } } } } return value; }; export const parseCascaderJson = (value: any) => { if (['object', 'boolean'].includes(typeof value)) { return JSON.stringify(value); } return value; }; export const paramsJsonToTable = (data: any, fixType: string | null = null) => { let value: any = []; let [MASK] = []; let rowKey = Date.now(); for (let key in data) { [MASK] .push(rowKey); value.push({ id: rowKey, name: key, value: parseCascaderJson(data[key]), type: { type: fixType || typeof data[key], auto: true }, }); rowKey += 1; } return [value, [MASK] ]; }; ",editKeys 98,"import { Component, OnInit, Inject } from '@angular/core'; import { PrivilegeResponseDto, RoleResponseDto, RoleRequestDto } from 'src/app/app-security-module/models/role'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { PrivilegeApiService } from 'src/app/app-security-module/services/privilege-api.service'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; @Component({ selector: 'app-role-dialog', templateUrl: './role-dialog.component.html', styleUrls: ['./role-dialog.component.scss'] }) export class RoleDialogComponent implements OnInit { form: FormGroup; privileges: PrivilegeResponseDto[]; constructor( private fb: FormBuilder, private privilegeApiService: PrivilegeApiService, private dialogRef: MatDialogRef, @Inject(MAT_DIALOG_DATA) data: RoleResponseDto) { this.privilegeApiService.getPrivileges().subscribe(privilegesResponse => { this.privileges = privilegesResponse; const [MASK] = data.privileges ? this.privileges.filter(privilege => data.privileges.map(r => r.id).indexOf(privilege.id) > -1) : []; this.form.patchValue({ privileges: [MASK] }); }); this.form = this.fb.group({ name: [data.name, [Validators.required]], description: [data.description, [Validators.required]], privileges: [[], [Validators.required, Validators.min(1)]] }); } ngOnInit() { } save() { const roleRequest: RoleRequestDto = { name: this.form.value.name, description: this.form.value.description, privilegeIds: this.form.value.privileges.map(privilege => privilege.id), }; this.dialogRef.close(roleRequest); } } ",selectedPrivileges 99,"// Return an array with the same shape as the input export function boundingBox(imageArray: number[][]): number[][] { const rows = imageArray.length; const cols = imageArray[0]?.length || 0; if (rows === 0 || cols == 0) return [] let top = rows; let bottom = 0; let left = cols; let [MASK] = 0; for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { if (imageArray[i][j] === 1) { top = Math.min(top, i); bottom = Math.max(bottom, i); left = Math.min(left, j); [MASK] = Math.max( [MASK] , j); } } } const boundingBox: number[][] = Array.from({ length: rows }, () => Array(cols).fill(0)); for (let i = top; i <= bottom; i++) { boundingBox[i][left] = 1; boundingBox[i][ [MASK] ] = 1; } for (let j = left; j <= [MASK] ; j++) { boundingBox[top][j] = 1; boundingBox[bottom][j] = 1; } return boundingBox; } ",right 100,"import { Chart, utils } from '@tradeconstruct/klinecharts'; import type { Candle, IChartEngine, InitOptions, IndicatorDef, CrosshairEvent, Unsubscribe } from '@tradeconstruct/chart-core'; function mapCandle(c: Candle) { return { ...c } as any; } export class KLineAdapter implements IChartEngine { private _chart: Chart | null = null; init(el: HTMLElement, [MASK] : InitOptions): void { this._chart = utils.createChart(el, [MASK] as any); } setData(series: Candle[]): void { this._chart?.applyNewData(series.map(mapCandle)); } updatePoint(point: Candle): void { this._chart?.updateData(mapCandle(point)); } addIndicator(def: IndicatorDef): string { return this._chart?.createIndicator(def as any) ?? ''; } removeIndicator(id: string): void { this._chart?.removeIndicator(id); } onCrosshair(cb: (p: CrosshairEvent) => void): Unsubscribe { if (!this._chart) return () => {}; // @ts-expect-error - event binding depends on klinecharts API this._chart.subscribeCrosshairMove(cb as any); return () => { // @ts-expect-error this._chart?.unsubscribeCrosshairMove(cb as any); }; } destroy(): void { this._chart?.destroy(); this._chart = null; } } ",opts 101,"import {MediaServerRepository} from ""./MediaServerRepository""; import {MediaServer} from ""./model/MediaServer""; import {MediaRouterStatus} from ""./model/MediaRouterStatus""; export class MediaServerRouter { public constructor( private _repository: MediaServerRepository = new MediaServerRepository() ) { } public register = (socketId: string, mediaServer: MediaServer) => { this._repository.register(socketId, mediaServer); } public unregister = (socketId: string) => { this._repository.unregister(socketId); } public addRoom = (socketId: string, roomId: string) => { const mediaServer = this._repository.requireMediaServerBySocketId(socketId); mediaServer.addRoom(roomId); } public removeRoom = (socketId: string, roomId: string) => { const mediaServer = this._repository.requireMediaServerBySocketId(socketId); mediaServer.removeRoom(roomId); } public findServerByRoomId = (roomId: string): MediaServer | undefined => { const mediaServers = this._repository.getMediaServers(); return mediaServers.find((server) => server.hasRoom(roomId)); } public findAvailableServer = (): MediaServer | undefined => { const mediaServers = this._repository.getMediaServers() let fewestRoomsServer: MediaServer | undefined; let [MASK] = Number.MAX_SAFE_INTEGER; for (const mediaServer of mediaServers) { if (mediaServer.canAddRoom() && mediaServer.roomCount < [MASK] ) { fewestRoomsServer = mediaServer; [MASK] = mediaServer.roomCount; } } return fewestRoomsServer; } public getStatus = (): MediaRouterStatus => { return new MediaRouterStatus(this._repository.getMediaServers()); } } export const mediaServerRouter = new MediaServerRouter(); ",fewestRoomCount 102,"import { sleep, check } from 'k6'; import { Options } from 'k6/options'; import http from 'k6/http'; import type { StudentInfo } from './types/StudentInfo'; export let options:Options = { scenarios: { constant_vus_test: { executor: 'constant-vus', vus: 50, duration: '5m', gracefulStop: '0s', // do not wait for iterations to finish in the end tags: { test_type: 'constant_vus_test' }, // extra tags for the metrics generated by this scenario exec: 'createAndUpdateScenario', // the function this scenario will execute }, constant_arrival_rate_test: { executor: 'constant-arrival-rate', rate: 90, timeUnit: '1m', // 90 iterations per minute, i.e. 1.5 RPS duration: '5m', preAllocatedVUs: 10, // the size of the VU (i.e. worker) pool for this scenario tags: { test_type: 'constant_arrival_rate_test' }, // different extra metric tags for this scenario exec: 'fetchScenario', // this scenario is executing different code than the one above! }, ramping_arrival_rate_test: { executor: 'ramping-arrival-rate', startTime: '30s', // the ramping API test starts a little later startRate: 50, timeUnit: '1s', // we start at 50 iterations per second stages: [ { target: 100, duration: '30s' }, // go from 50 to 200 iters/s in the first 30 seconds { target: 100, duration: '3m30s' }, // hold at 200 iters/s for 3.5 minutes { target: 0, duration: '30s' }, // ramp down back to 0 iters/s over the last 30 second ], preAllocatedVUs: 50, // how large the initial pool of VUs would be maxVUs: 100, // if the preAllocatedVUs are not enough, we can initialize more tags: { test_type: 'ramping_arrival_rate_test' }, // different extra metric tags for this scenario exec: 'fetchScenario', // same function as the scenario above, but with different env vars }, }, discardResponseBodies: true, thresholds: { 'http_req_duration{scenario:constant_vus_test}': ['p(99)<1500'], 'http_req_duration{scenario:constant_arrival_rate_test}': ['p(99)<1500'], 'http_req_duration{scenario:ramping_arrival_rate_test}': ['p(99)<1500'], }, }; export function createAndUpdateScenario() { createStudent(); updateStudent(); sleep(Math.random() * 2); } export function fetchScenario() { getStudents(); getClasses(); } export function createStudent() { const newStudent = { firstName: ""FirstName"", lastName: ""LastName"", sex: ""NG"" } as StudentInfo; const params = { headers: { ""Content-Type"": ""application/json"", }, }; const res = http.post(`${__ENV.BASE_URL}/api/students`, JSON.stringify(newStudent), params); check(res, { ""status is 200"": () => res.status === 200, }); }; export function updateStudent() { const [MASK] = { firstName: ""FirstNameUpdated"", lastName: ""LastNameUpdated"", sex: ""NG"" } as StudentInfo; const params = { headers: { ""Content-Type"": ""application/json"", }, }; const res = http.put(`${__ENV.BASE_URL}/api/students/1`, JSON.stringify( [MASK] ), params); check(res, { ""status is 200"": () => res.status === 200, }); }; export function getStudents() { const res = http.get(`${__ENV.BASE_URL}/api/students`); check(res, { ""status is 200"": () => res.status === 200, }); }; export function getClasses() { const res = http.get(`${__ENV.BASE_URL}/api/classes`); check(res, { ""status is 200"": () => res.status === 200, }); }; ",newStudentData 103,"import { Injectable } from '@angular/core'; import { HttpClient} from '@angular/common/http'; import { Observable, of } from 'rxjs'; import { delay, tap } from 'rxjs/operators'; import { ATM } from './model/atm'; import { MOCK_ATMs } from './MOCK/mock-atms-list'; import{ GlobalConstants } from './config/constants'; @Injectable({ providedIn: 'root', }) export class ATMsService { constructor(private httpClient: HttpClient) {} getMockResults(): Observable { return of(MOCK_ATMs).pipe( delay(1000), tap(_ => this.log('fetched MOCK ATMs results')), ) } getSearchResults(fullTextSearch: string): Observable { console.log(GlobalConstants.API_FULL_TEXT_SEARCH_ENDPOINT) let params = {fullTextSearch: fullTextSearch} return this.httpClient.get(GlobalConstants.API_FULL_TEXT_SEARCH_ENDPOINT, {params: params}) .pipe( delay(1000), tap(_ => this.log('fetched ATMs results')) ) } private log( [MASK] : string) { console.log( [MASK] ) } } ",message 104,"// SPDX-License-Identifier: Apache-2.0 // Copyright 2024 Tiny Tapeout LTD // Author: import { githubURLToRaw } from '../util/github'; export interface ILibraryDefinition { path: string; url: string; } export class LibraryLoader { private readonly cache = new Map(); readonly pathToUrl = new Map(); baseURL?: string; constructor(readonly libraries: ILibraryDefinition[]) {} async fileExists(path: string) { try { await this.load(path); return true; } catch { return false; } } async load(path: string) { const [MASK] = this.cache.get(path); if ( [MASK] != null) { return [MASK] ; } const response = await this.fetchContent(path); if (!response.ok) { throw new Error(`File not found: ${path}`); } const content = await response.text(); this.cache.set(path, content); return content; } private async fetchContent(path: string): Promise { if (path.toLowerCase().startsWith('https://')) { const url = githubURLToRaw(path); return await fetch(url); } for (const library of this.libraries) { if (path.startsWith(library.path)) { const url = library.url + path; return await fetch(url); } } if (this.baseURL != null) { const url = new URL(path, githubURLToRaw(this.baseURL)); const result = await fetch(url); if (result.ok) { this.pathToUrl.set(path, url.toString()); return result; } // Try to look under the root of the github repo const altPath = url.pathname.split('/').slice(0, 4).join('/') + '/' + path; if (url.hostname === 'raw.githubusercontent.com' && url.pathname !== altPath) { url.pathname = altPath; const result = await fetch(url); if (result.ok) { this.pathToUrl.set(path, url.toString()); return result; } } } if (!path.includes('/')) { // as a fallback, look under devices/ return await this.fetchContent(`devices/${path}`); } throw new Error(`File not found: ${path}`); } } ",cacheEntry 105,"import { NextRequest, NextResponse } from 'next/server'; import Groq from ""groq-sdk""; const groq = new Groq(); export async function POST(req: NextRequest) { try { const { prompt, model } = await req.json(); if (!prompt || !model) { return NextResponse.json({ error: 'Prompt and model are required' }, { status: 400 }); } // Set the API key from environment variable if (!process.env.GROQ_API_KEY) { throw new Error('GROQ_API_KEY is not set in the environment variables'); } groq.apiKey = process.env.GROQ_API_KEY; const stream = await groq.chat.completions.create({ messages: [ { role: ""user"", content: prompt, }, ], model: model, temperature: 0.7, max_tokens: 1024, top_p: 1, stream: true, }); return new Response( new ReadableStream({ async start( [MASK] ) { let lastChunk; try { for await (const chunk of stream) { const content = chunk.choices[0]?.delta?.content || """"; if (content) { [MASK] .enqueue(content); } lastChunk = chunk; } // After the stream is complete, send the metrics if (lastChunk?.x_groq?.usage) { console.log('Sending metrics:', lastChunk.x_groq.usage); // Debug log const metricsMessage = `\n__METRICS__${JSON.stringify({ __metrics: { completion_time: lastChunk.x_groq.usage.completion_time, completion_tokens: lastChunk.x_groq.usage.completion_tokens, total_tokens: lastChunk.x_groq.usage.total_tokens } })}`; [MASK] .enqueue(metricsMessage); } } catch (error) { console.error('Error in stream processing:', error); } finally { [MASK] .close(); } }, }), { headers: { 'Content-Type': 'text/plain; charset=utf-8', }, } ); } catch (error) { console.error('Error in Groq API request:', error); return NextResponse.json({ error: 'An error occurred while processing your request' }, { status: 500 }); } } ",controller 106,"import * as React from ""react"" type State = { error: string isLoading: boolean response: any, url: RequestInfo } function initialState( [MASK] : { error?: any isLoading?: boolean response?: any, url: RequestInfo }) { return { response: null, error: null, isLoading: true, ... [MASK] , } } const useApi = ( url: RequestInfo, options = null ): State => { const [state, setState] = React.useState(() => initialState({url})) React.useEffect(() => { const fetchData = async () => { try { console.log(""Fetching:"", url) const res = await fetch(url, { ...(options || {}), }) if (res.status >= 400) { setState( initialState({ error: await res.json(), isLoading: false, url }) ) } else { setState( initialState({ response: await res.json(), isLoading: false, url }) ) } // TODO: Use Result instead } catch (error) { setState( initialState({ error: { error: (error as Error).message, }, isLoading: false, url }) ) } } fetchData() }, [url, options]) return state } export default useApi ",args 107,"/* * Copyright The OpenTelemetry Authors * * 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 * * https://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. */ import { CollectorExporterBase } from '../../CollectorExporterBase'; import { ReadableSpan, SpanExporter } from '@opentelemetry/tracing'; import { toCollectorExportTraceServiceRequest } from '../../transform'; import { CollectorExporterConfigBrowser } from './types'; import * as collectorTypes from '../../types'; import { sendWithBeacon, sendWithXhr } from './util'; import { parseHeaders } from '../../util'; const DEFAULT_SERVICE_NAME = 'collector-trace-exporter'; const DEFAULT_COLLECTOR_URL = 'http://localhost:55680/v1/trace'; /** * Collector Trace Exporter for Web */ export class CollectorTraceExporter extends CollectorExporterBase< CollectorExporterConfigBrowser, ReadableSpan, collectorTypes.opentelemetryProto.collector.trace.v1.ExportTraceServiceRequest > implements SpanExporter { DEFAULT_HEADERS: Record = { [collectorTypes.OT_REQUEST_HEADER]: '1', }; private _headers: Record; private _useXHR: boolean = false; /** * @param config */ constructor(config: CollectorExporterConfigBrowser = {}) { super(config); this._headers = parseHeaders(config.headers, this.logger) || this.DEFAULT_HEADERS; this._useXHR = !!config.headers || typeof navigator.sendBeacon !== 'function'; } onInit(): void { window.addEventListener('unload', this.shutdown); } onShutdown(): void { window.removeEventListener('unload', this.shutdown); } getDefaultUrl(config: CollectorExporterConfigBrowser) { return config.url || DEFAULT_COLLECTOR_URL; } getDefaultServiceName(config: CollectorExporterConfigBrowser): string { return config.serviceName || DEFAULT_SERVICE_NAME; } convert( spans: ReadableSpan[] ): collectorTypes.opentelemetryProto.collector.trace.v1.ExportTraceServiceRequest { return toCollectorExportTraceServiceRequest(spans, this); } send( spans: ReadableSpan[], [MASK] : () => void, onError: (error: collectorTypes.CollectorExporterError) => void ) { const exportTraceServiceRequest = this.convert(spans); const body = JSON.stringify(exportTraceServiceRequest); if (this._useXHR) { sendWithXhr( body, this.url, this._headers, this.logger, [MASK] , onError ); } else { sendWithBeacon(body, this.url, this.logger, [MASK] , onError); } } } ",onSuccess 108,"import { getBackendSrv, isFetchError } from '@grafana/runtime'; import { CoreApp, DataQueryRequest, DataQueryResponse, DataSourceApi, DataSourceInstanceSettings, MutableDataFrame, FieldType, } from '@grafana/data'; import { MyQuery, MyDataSourceOptions, DEFAULT_QUERY, DataSourceResponse } from './types'; import { lastValueFrom } from 'rxjs'; import _ from 'lodash'; import defaults from 'lodash/defaults'; export const defaultQuery: Partial = { constant: 6.5, }; export class DataSource extends DataSourceApi { baseUrl: string; resolution: number; constructor(instanceSettings: DataSourceInstanceSettings) { super(instanceSettings); this.baseUrl = instanceSettings.url!; this.resolution= instanceSettings.jsonData.resolution || 1000.0; } getDefaultQuery(_: CoreApp): Partial { return DEFAULT_QUERY; } filterQuery(query: MyQuery): boolean { // if no query has been provided, prevent the query from being executed return !!query.queryText; } async query(options: DataQueryRequest): Promise { const { range } = options; const from = range!.from.valueOf(); const to = range!.to.valueOf(); // Return a constant for each query. const data = options.targets.map((target) => { const query = defaults(target, defaultQuery); const frame = new MutableDataFrame({ refId: query.refId, fields: [ { name: 'time', type: FieldType.time }, { name: 'value', type: FieldType.number }, ], }); const duration = to - from; const [MASK] = duration / this.resolution; for (let t = 0; t < duration; t += [MASK] ) { frame.add({ time: from + t, value: Math.sin((2 * Math.PI * query.frequency * t) / duration) }); } return frame; }); return { data }; } async request(url: string, params?: string) { const response = getBackendSrv().fetch({ url: `${this.baseUrl}${url}${params?.length ? `?${params}` : ''}`, }); return lastValueFrom(response); } /** * Checks whether we can connect to the API. */ async testDatasource() { const defaultErrorMessage = 'Cannot connect to API'; try { const response = await this.request('/health'); if (response.status === 200) { return { status: 'success', message: 'Success', }; } else { return { status: 'error', message: response.statusText ? response.statusText : defaultErrorMessage, }; } } catch (err) { let message = ''; if (_.isString(err)) { message = err; } else if (isFetchError(err)) { message = 'Fetch error: ' + (err.statusText ? err.statusText : defaultErrorMessage); if (err.data && err.data.error && err.data.error.code) { message += ': ' + err.data.error.code + '. ' + err.data.error.message; } } return { status: 'error', message, }; } } } ",step 109,"import { Component, inject, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms'; import { MatInputModule } from '@angular/material/input'; import { ProductFull, Category, Product } from '../../interfaces/store'; import { ReactiveFormsModule } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { StoreService } from '../../services/store.service'; import { MatSelectModule } from '@angular/material/select'; import { MatSnackBar } from '@angular/material/snack-bar'; @Component({ selector: 'app-admin-category-detail', standalone: true, imports: [ MatInputModule, ReactiveFormsModule,], templateUrl: './admin-category-detail.component.html', styleUrl: './admin-category-detail.component.css' }) export class AdminCategoryDetailComponent implements OnInit { categoryForm!: FormGroup; constructor(private fb: FormBuilder,private storeService: StoreService,private activatedRoute: ActivatedRoute, private router: Router) {} ngOnInit(){ if(this.router.url.endsWith(""create"")){ this.categoryForm = this.fb.group({ id: [null], name: ['', Validators.required], }); } else{ this.activatedRoute.data.subscribe(({ data })=>{ this.categoryForm = this.fb.group({ id: [data.id], name: [data.name, Validators.required], }); }) } } private _snackBar = inject(MatSnackBar); openSnackBar(message: string, action: string) { this._snackBar.open(message, action); } onSubmit() { if (this.categoryForm.valid) { const category: Category = this.categoryForm.value; if(this.router.url.endsWith(""create"")){ this.storeService.createCategory(category).subscribe({ next: () => { this.router.navigate(['admin/category']); this.openSnackBar(""Categoria Creado Exitosamente"",""OK""); }, error: (err) => { this.openSnackBar(""Producto no se pudo crear"",""OK""); } }); } else{ this.storeService.updateCategory(category).subscribe({ next: () => { this.router.navigate(['admin/category']); this.openSnackBar(""Cateogoria Editada Exitosamente"",""OK""); }, error: (err) => { this.openSnackBar(""Categoria no se pudo editar"",""OK""); } }); } } else { this.openSnackBar(""Formulario no se pudo editar"",""OK""); this.markFormGroupTouched(this.categoryForm); } } private markFormGroupTouched( [MASK] : FormGroup ) { Object.values( [MASK] .controls).forEach(control => { control.markAsTouched(); if (control instanceof FormGroup) { this.markFormGroupTouched(control); } }); } } ",formGroup 110,"/** * Copyright 2017 The Mifos Initiative. * * 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. */ import {JournalEntry} from '../../../../services/accounting/domain/journal-entry.model'; import {FormComponent} from '../../../../common/forms/form.component'; import {Component, OnDestroy, OnInit, ViewChild} from '@angular/core'; import {AbstractControl, FormArray, FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; import {ActivatedRoute, Router} from '@angular/router'; import {TdStepComponent} from '@covalent/core'; import {FetchRequest} from '../../../../services/domain/paging/fetch-request.model'; import {Account} from '../../../../services/accounting/domain/account.model'; import {Observable, Subscription} from 'rxjs'; import {toLongISOString} from '../../../../services/domain/date.converter'; import {FimsValidators} from '../../../../common/validator/validators'; import * as fromAccounting from '../../store'; import * as fromRoot from '../../../reducers'; import {CREATE, RESET_FORM} from '../../store/ledger/journal-entry/journal-entry.actions'; import {Error} from '../../../../services/domain/error.model'; import {SEARCH} from '../../../reducers/account/account.actions'; import {AccountingStore} from '../../store/index'; import {JournalEntryValidators} from './journal-entry.validator'; import {AccountingService} from '../../../../services/accounting/accounting.service'; import {transactionTypeExists} from './transaction-type-select/validator/transaction-type-exists.validator'; @Component({ selector: 'fims-journal-entry-form-component', templateUrl: './form.component.html' }) export class JournalEntryFormComponent extends FormComponent implements OnInit, OnDestroy { private formStateSubscription: Subscription; private userNameSubscription: Subscription; @ViewChild('detailsStep') detailsStep: TdStepComponent; selectedClerk: string; term = new FormControl(); accounts: Observable; constructor(private formBuilder: FormBuilder, private router: Router, private route: ActivatedRoute, private store: AccountingStore, private accountingService: AccountingService) { super(); } get formData(): JournalEntry { return null; } ngOnInit(): void { this.formStateSubscription = this.store.select(fromAccounting.getJournalEntryFormError) .filter((error: Error) => !!error) .subscribe((error: Error) => this.setError('transactionIdentifier', 'unique', true)); this.accounts = this.store.select(fromRoot.getAccountSearchResults) .map(accountPage => accountPage.accounts); this.detailsStep.open(); this.userNameSubscription = this.store.select(fromRoot.getUsername).subscribe(username => this.selectedClerk = username); this.form = this.formBuilder.group({ transactionIdentifier: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(32), FimsValidators.urlSafe()]], transactionType: ['', [Validators.required], transactionTypeExists(this.accountingService)], transactionDate: [new Date().toISOString().slice(0, 10), Validators.required], note: [''], message: [''], creditors: this.formBuilder.array([], JournalEntryValidators.minItems(1)), debtors: this.formBuilder.array([], JournalEntryValidators.minItems(1)) }, { validator: JournalEntryValidators.equalSum('creditors', 'debtors') }); this.term.valueChanges .debounceTime(500) .subscribe((event) => this.onAccountSearch(event)); this.onAccountSearch(); } ngOnDestroy(): void { this.formStateSubscription.unsubscribe(); this.userNameSubscription.unsubscribe(); this.store.dispatch({ type: RESET_FORM }) } onClerkSelectionChange(selections: string[]): void { this.selectedClerk = selections[0]; } save(): void { let [MASK] = toLongISOString(this.form.get('transactionDate').value); let journalEntry: JournalEntry = { transactionIdentifier: this.form.get('transactionIdentifier').value, transactionType: this.form.get('transactionType').value, transactionDate: [MASK] , clerk: this.selectedClerk, note: this.form.get('note').value, message: this.form.get('message').value, creditors: this.form.get('creditors').value, debtors: this.form.get('debtors').value, }; this.store.dispatch({ type: CREATE, payload: { journalEntry, activatedRoute: this.route } }); } addCreditor(accountNumber: string): void { const control: FormArray = this.form.get('creditors') as FormArray; control.push(this.initCreditor(accountNumber)); } removeCreditor(index: number): void { const control: FormArray = this.form.get('creditors') as FormArray; control.removeAt(index); } addDebtor(accountNumber: string): void { const control: FormArray = this.form.get('debtors') as FormArray; control.push(this.initDebtor(accountNumber)); } removeDebtor(index: number): void { const control: FormArray = this.form.get('debtors') as FormArray; control.removeAt(index); } onCancel() { this.navigateAway(); } navigateAway(): void { this.router.navigate(['../'], {relativeTo: this.route}); } get debtors(): AbstractControl[] { const debtors: FormArray = this.form.get('debtors') as FormArray; return debtors.controls; } get creditors(): AbstractControl[] { const creditors: FormArray = this.form.get('creditors') as FormArray; return creditors.controls; } private onAccountSearch(searchTerm?: string): void { let fetchRequest: FetchRequest = { page: { pageIndex: 0, size: 5 }, searchTerm: searchTerm }; this.store.dispatch({ type: SEARCH, payload: fetchRequest }); } private initCreditor(accountNumber: string): FormGroup { return this.formBuilder.group({ accountNumber: [accountNumber], amount: [0] }) } private initDebtor(accountNumber: string): FormGroup { return this.formBuilder.group({ accountNumber: [accountNumber], amount: [0] }) } } ",transactionDateString 111,"import { Injectable } from '@angular/core'; import {HttpClient} from ""@angular/common/http""; import {catchError, throwError} from ""rxjs""; @Injectable({ providedIn: 'root' }) export class HttpService { private baseUrl = ""https://jsonplaceholder.typicode.com"" constructor(private http:HttpClient) { } get( [MASK] :string, params?:any){ const data = {params}; return this.http.get(this.baseUrl + [MASK] ).pipe(catchError(this.errorHandler.bind(this))) } private errorHandler(response:any){ const error = response.error; const keys = Object.keys(error); const key = keys[0]; let message = error[key]; if (response.status == 401){ // Auth token } if(error[key] instanceof Array){ message = error[key][0]; } if(key === 'isTrusted'){ } else { } // Call Snackbar return throwError({messages: message, error}); } } ",url 112,"import React from 'react'; import { useSetState, useUnmount } from 'react-use'; type UpdateFn = (patch: Partial | ((prevState: T) => Partial)) => void; type UpdatePartFn = (patch: U | Function) => void; type UpdaterFn = { [K in keyof T]: UpdatePartFn }; // 测试 useUpdate 类型 // const Test = () => { // const [state, updater] = useUpdate({ // str: '', // num: 0, // bool: true, // undef: undefined, // nul: null, // strList: ['one', 'two'], // numList: [1, 2], // multiList: ['one', 1, false], // 允许包含的类型 // emptyList: [], // 允许任何数组对象 // emptyObj: {}, // 允许任何对象 // obj: { k: 'v', n: 2 }, // 允许相同形状对象 // objList: [{ ok: true, msg: 'yes' }], // 允许设置任意对象 // }); // updater.nul({ any: true }); // updater.multiList([1, '']); // updater.emptyList([1, '']); // updater.emptyObj({ a: 2 }); // updater.objList([{ ok: false, msg: '' }]); // return null; // }; type NullableValue = { [K in keyof T]: T[K] extends null ? null | Record // 初始状态里对象值可能是null : T[K] extends never[] ? any[] // 初始值是空数组,则认为可放任意结构数组 : T[K] extends { [p: string]: never } ? Record // 初始值是空对象,不限制内部结构,是object类型即可 : T[K] }; type ResetFn = () => void; /* eslint-disable arrow-parens */ /** * 状态更新 * @param initState 初始状态 * @return [state, updateAll, updater] */ export const useUpdate = ( initState: NullableValue ): [NullableValue, UpdaterFn>, UpdateFn>, ResetFn] => { const [state, _update] = useSetState>(initState || {}); // 使用ref,避免updater的更新方法中,在闭包里使用上次的state const ref = React.useRef(state); const updateRef = React.useRef(_update); ref.current = state; const update: any = React.useCallback((args: any) => updateRef.current(args), []); const updater: any = React.useMemo(() => { const result = {}; Object.keys(ref.current).forEach((k) => { result[k] = (patch: Function | any) => { const newPart = patch instanceof Function ? patch(ref.current[k], ref.current) : patch; ref.current[k] = newPart; return updateRef.current({ [k]: newPart } as Partial>); }; }); return result; }, []); const [MASK] = React.useCallback(() => updateRef.current(initState), [initState]); useUnmount(() => { updateRef.current = () => {}; }); return [state, updater, update, [MASK] ]; }; ",reset 113,"/// module emailEditorMod{ 'use strict'; /** * Object to use in directive hierarchy */ export class EMailCollection implements IEMailCollection{ mailList: EMailModel[]; constructor(){ this.mailList = []; } addEMail(eMail:string): void{ if (eMail){ let mail = new EMailModel(eMail); if(this.mailList.indexOf(mail) < 0){ this.mailList.push(mail); } } } removeMail(mail:string): void{ let [MASK] = this.mailList; for (let i = [MASK] .length - 1; i >= 0; i--){ let el = [MASK] [i]; if(el.getMail() === mail){ this.mailList.splice(i, 1); } } } length():number { return this.mailList.length; } } }",mList 114,"'use client'; import { useState, useEffect, useCallback } from 'react'; import { useParams } from 'next/navigation'; import Cookies from 'js-cookie'; import { toast } from 'react-toastify'; import { env } from 'next-runtime-env'; interface InfoTcc { title: string; summary: string; presentationDate: string | null; presentationTime: string | null; presentationLocation: string; } interface InfoStudent { name: string; registration: string; cpf: string; course: string; email: string; } interface InfoAdvisor { name: string; email: string; } interface InfoBanking { nameInternal: string; emailInternal: string; nameExternal: string; emailExternal: string; } export interface CompletedTccDetailsResponse { infoTcc: InfoTcc; infoStudent: InfoStudent[]; infoAdvisor: InfoAdvisor; infoBanking: InfoBanking; } export function useCompletedTccDetails() { const [tccDetails, setTccDetails] = useState(null); const [isLoading, setIsLoading] = useState(true); const [MASK] = useParams(); const tccId = [MASK] .id as string; const API_URL = env('NEXT_PUBLIC_API_URL'); const fetchDetails = useCallback(async () => { if (!tccId) return; setIsLoading(true); const token = Cookies.get('token'); try { const res = await fetch(`${API_URL}/Tcc?tccId=${tccId}`, { headers: { Authorization: `Bearer ${token}` }, }); if (!res.ok) throw new Error('Falha ao buscar detalhes do TCC.'); const data = await res.json(); setTccDetails(data); } catch { toast.error('Erro ao carregar detalhes do TCC.'); } finally { setIsLoading(false); } }, [tccId, API_URL]); useEffect(() => { fetchDetails(); }, [fetchDetails]); return { tccDetails, isLoading }; }",params 115,"import express, { Request, Response } from 'express'; import { body } from 'express-validator'; import jwt from 'jsonwebtoken'; import { BadRequestError, validateRequest } from '@jmtickt/common'; import User from '../models/User'; import Password from '../services/Password'; const router = express.Router(); router.post( '/login', [ body('email').isEmail().withMessage('Email must be valid.'), body('password').trim().notEmpty().withMessage('Password is required.'), ], validateRequest, async (req: Request, res: Response) => { const { email, password } = req.body; const user = await User.findOne({ email }); if (!user) { throw new BadRequestError('Invalid Credentials'); } const [MASK] = await Password.compare(user.password, password); if (! [MASK] ) { throw new BadRequestError('Invalid Credentials'); } const jwtToken = jwt.sign( { id: user.id, email: user.email, }, process.env.JWT_KEY! ); // Store JWT in session req.session = { jwt: jwtToken }; return res.status(200).send({ token: jwtToken }); } ); export { router as loginRouter }; ",isValid 116,"import supertest from 'supertest'; import app from '../index'; import resize from '../controllers/resize'; const req = supertest(app); interface MockFile { filename: string; width: number; height: number; } describe('Test image prcessing utilities ', () => { it('gets the image processing endpoint', () => { const newMockFile = { filename: 'fjord', width: 200, height: 200, }; return resize( newMockFile.filename, newMockFile.width, newMockFile.height ).then(( [MASK] ) => { expect( [MASK] ).toBe(newMockFile.filename); }); }); }); describe('Test endpoint responses', () => { it('gets the image processing endpoint', (done) => { const newMockFile: MockFile = { filename: 'fjord', width: 200, height: 200, }; req .get( `/api/images?filename=${newMockFile.filename}&width=${newMockFile.width}&height=${newMockFile.height}` ) .expect(200, (err) => { if (err) done.fail(err); else done(); }); }); it('gets home page endpoint', (done) => { req.get('/').expect(200, (err) => { if (err) done.fail(err); else done(); }); }); }); ",resFilename 117,"import { DynamoDB } from ""@aws-sdk/client-dynamodb""; import { fromEnv } from ""@aws-sdk/credential-providers""; import { marshall, unmarshall } from ""@aws-sdk/util-dynamodb""; import { chunk } from ""@/Array.js""; import type { UpdateItemCommandInput } from ""@aws-sdk/client-dynamodb""; import type { NativeAttributeValue } from ""@aws-sdk/util-dynamodb""; let instance: DynamoDB | undefined = undefined; export function DDB() { return (instance ??= new DynamoDB({ region: process.env.AWS_REGION ?? ""us-east-1"", credentials: fromEnv(), })); } export async function DDBGetItem( table: string, partitionKey: string, partitionValue: number | string, sortKey?: string, sortValue?: number | string, projection?: string[], ) { const result = await DDB().getItem({ TableName: table, ConsistentRead: false, ReturnConsumedCapacity: ""TOTAL"", Key: marshall({ [partitionKey]: partitionValue, ...(sortKey !== undefined && sortValue !== undefined ? { [sortKey]: sortValue } : {}), }), ProjectionExpression: projection?.map((name) => `#${name}`).join("", ""), ExpressionAttributeNames: projection === undefined ? undefined : Object.fromEntries(projection.map((name) => [`#${name}`, name])), }); return result.Item ? (unmarshall(result.Item) as T) : null; } export async function DDBUpdateItem( table: string, partitionKey: string, partitionValue: number | string, sortKey: string | undefined, sortValue: number | string | undefined, keys: Record, ) { const attributeNames: Record = {}; const attributeValues: Record = {}; const [MASK] : string[] = []; const expressionRemove: string[] = []; for (const [key, value] of Object.entries(keys)) { attributeNames[`#${key}`] = key; if (value === undefined) { expressionRemove.push(`#${key}`); continue; } attributeValues[`:${key}`] = value as unknown; [MASK] .push(`#${key} = :${key}`); } const updateExpression = [ [MASK] .length > 0 ? `SET ${ [MASK] .join("", "")}` : undefined, expressionRemove.length > 0 ? `REMOVE ${expressionRemove.join("", "")}` : undefined, ]; const updateItemParams: UpdateItemCommandInput = { TableName: table, Key: marshall({ [partitionKey]: partitionValue, ...(sortKey !== undefined && sortValue !== undefined ? { [sortKey]: sortValue } : {}), }), UpdateExpression: updateExpression.join("" ""), ExpressionAttributeNames: attributeNames, ExpressionAttributeValues: marshall(attributeValues), }; return DDB().updateItem(updateItemParams); } export async function DDBDeleteItem( table: string, partitionKey: string, partitionValue: number | string, sortKey: string, sortValue: number | string, ) { return DDB().deleteItem({ TableName: table, Key: marshall({ [partitionKey]: partitionValue, [sortKey]: sortValue, }), }); } export async function DDBBatchWrite( table: string, entries: object[], chunkSize = 25, ) { for (const chunkEntries of chunk(entries, chunkSize)) { // eslint-disable-next-line no-await-in-loop await DDB().batchWriteItem({ RequestItems: { [table]: chunkEntries.map((entry) => ({ PutRequest: { Item: marshall(entry) }, })), }, }); } } export async function DDBBatchDelete( table: string, entries: object[], chunkSize = 25, ) { for (const chunkEntries of chunk(entries, chunkSize)) { // eslint-disable-next-line no-await-in-loop await DDB().batchWriteItem({ RequestItems: { [table]: chunkEntries.map((entry) => ({ DeleteRequest: { Key: marshall(entry) }, })), }, }); } } ",expressionSet 118,"// 白名单 const whiteList = [ 'pages/index/index', 'pages/login/login' ] function hasPermission (url:string) { let [MASK] = uni.getStorageSync('isLogin');//isLogin是登录成功后在本地存储登录标识,存储一个能够判断用户登录的唯一标识就行 [MASK] = Boolean(Number( [MASK] ));//返回布尔值 // 在白名单中或有登录判断条件可以直接跳转 if(whiteList.indexOf(url) !== -1 || [MASK] ) { console.log('通过') return true } return false } export default async function () { const list = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab'] // 用遍历的方式分别为,uni.navigateTo,uni.redirectTo,uni.reLaunch,uni.switchTab这4个路由方法添加拦截器 list.forEach(item => { uni.addInterceptor(item, { invoke (e) { if(!hasPermission(e.url)){ console.log('没登陆') // 测试,先注释 // uni.showModal({ // title: '请登录', // content: '', // confirmText: '确认', // cancelText: '取消', // success: (res) => { // if (res.confirm) { // console.log(1111111) // uni.navigateTo({ // url: 'pages/login/login' // }) // } // } // }); // return false } else { return true } }, fail(err) { // 失败回调拦截 console.log(err) } }) }) } ",islogin 119,"import * as dotenv from ""dotenv""; // Environment variables import Sniper from ""./sniper""; // Sniper // Setup env dotenv.config(); (async () => { // Token address const tokenAddress: string | undefined = process.env.TOKEN_ADDRESS; // Factory address const factoryAddress: string | undefined = process.env.FACTORY_ADDRESS; // RPC endpoint const rpcEndpoint: string = process.env.RPC_ENDPOINT ?? ""http://localhost:8545""; // Wallet private key const [MASK] : string | undefined = process.env.PRIVATE_KEY; // Purchase amount in chain base token const purchaseAmount: string = process.env.AMOUNT ?? ""0.01""; // 0.01 eth/matic/etc. // Gas price to send const gasPrice: string = process.env.GAS_PRICE ?? ""2000""; // 2,000 gwei // Slippage tolerance const slippage: number = Number(process.env.SLIPPAGE) ?? 0.1; // 10% // Testnet? const testnet: boolean = Boolean(process.env.TESTNET) ?? false; // Throw if missing necessary params if (!tokenAddress || ! [MASK] || !factoryAddress) { throw new Error(""Missing necessary parameters""); } // Initialize sniper const sniper = new Sniper( tokenAddress, factoryAddress, rpcEndpoint, [MASK] , purchaseAmount, gasPrice, slippage, testnet ); // Wait and snipe pool await sniper.snipe(); })(); ",privateKey 120,"import { Author } from './author'; export class Book { private title: string; private author: Author; private rating: number; constructor(newTitle: string, newAuthor: Author, newRating: number) { if (newAuthor === null) { throw new Error('El autor no puede ser nulo'); } this.title = newTitle; this.author = newAuthor; this.rating = newRating; } public getTitle(): string { return this.title; } public setTitle(title: string): void { this.title = title; } public getAuthor(): Author { return this.author; } public setAuthor(author: Author): void { this.author = author; } public getRating(): number { return this.rating; } /** * Change book's rating. We only accept rating values between 0 and 5. * @param rating is the new rating value */ public setRating(newRating: number): void { if (newRating > 5) { this.rating = 5; } else if (newRating < 0) { this.rating = 0; } else { this.rating = newRating; } } public equals( [MASK] : Book): boolean { return [MASK] != null && this.title === [MASK] .getTitle() && this.author.equals( [MASK] .getAuthor().getName()); } public titleContains(target: string): boolean { return this.title.toLowerCase().indexOf(target.toLowerCase()) != -1; } public authorContains(target: string): boolean { return this.author.getName().toLowerCase().indexOf(target.toLowerCase()) != -1; } }",other 121,"//const express = require('express'); import express, {Router, Express, Request, Response} from ""express"" import CategoriesModel from ""../models/categoryModel"" const categoryRouter:Router = express.Router(); categoryRouter.get('/', async (req:Request, res:Response) => { const categories = await CategoriesModel.find().exec(); const [MASK] = categories.map((category:any) => ( { id: category.id, name: category.name, })) res.status(200).json({ categories: [MASK] }); }) categoryRouter.delete('/:id', async (req:Request, res:Response) => { const result = await CategoriesModel.findByIdAndDelete(req.params.id).exec(); res.status(200).json({ deleted: result }); }) categoryRouter.put('/:id', async (req:Request, res:Response) => { var update = { name: req.body.name, } const result = await CategoriesModel.findByIdAndUpdate(req.params.id, update).exec(); res.status(200).json({ updated: update }); }) categoryRouter.post('/', async (req:Request, res:Response) => { const category:InstanceType = new CategoriesModel({ name: req.body.name, }); await category.save() res.status(200).json({ message: category }); }) export default categoryRouter;",returnCategories 122,"import fs from ""fs""; const dataFile = ""./data.json""; const checkIfDataFileExists = (): boolean => { try { return fs.existsSync(dataFile); } catch (err) { console.error(err); } return false; }; const createAndInitDataFile = () => { const data = Array.from({ length: 100 }, (_, i) => ({ name: ""Task "" + (i + 1), completed: false, })); const [MASK] = JSON.stringify(data); fs.writeFileSync(dataFile, [MASK] ); }; export const initData = () => { if (!checkIfDataFileExists()) { createAndInitDataFile(); } }; export const getTasks = () => { const rawdata = fs.readFileSync(dataFile); return JSON.parse(rawdata.toString()); }; export const updateTask = (idx: number, state: boolean) => { const tasks = getTasks(); tasks[idx] = { ...tasks[idx], completed: state }; const data = JSON.stringify(tasks); fs.writeFileSync(dataFile, data); return tasks[idx]; }; ",jsonData 123,"import * as dartStyle from 'dart-style'; import * as path from 'path'; import * as ts from 'typescript'; import {OutputContext, Transpiler} from './main'; /** * Map from identifier name to resolved type. * Example: 'E' should map to a TypeNode for number when resolving a usage of MyArray * where MyArray is the alias type: * type MyArray = Array */ export type ResolvedTypeMap = Map; /*** * Options for how TypeScript types are represented as Dart types. */ export interface TypeDisplayOptions { /// We are displaying the type inside a comment so we don't have to restrict to valid Dart syntax. /// For example, we can display string literal type using the regular TypeScript syntax. /// /// Example: /// TypeScript type: number|string /// Dart inside comment: num|String /// Dart outside comment: dynamic /* num|string */ insideComment?: boolean; /// Dart has additional restrictions for what types are valid to emit inside a type argument. For /// example, ""void"" is not valid inside a type argument so Null has to be used instead. /// /// Example: /// TypeScript type: Foo /// Dart inside type argument: Foo /// Dart outside type argument: N/A /// TypeScript type: bar():void /// Dart inside type argument: N/A /// Dart outside type argument: void bar(); insideTypeArgument?: boolean; /// Indicates that we should not append an additional comment indicating what the true TypeScript /// type was for cases where Dart cannot express the type precisely. /// /// Example: /// TypeScript type: number|string /// Dart hide comment: dynamic /// Dart show comment: dynamic /*number|string*/ hideComment?: boolean; /** * Type arguments associated with the current type to display. * Arguments are emitted directly in normal cases but in the case of type aliases we have to * propagate and substitute type arguments. */ typeArguments?: ts.NodeArray; /** * Parameter declarations to substitute. This is required to support type aliases with type * arguments that are not representable in Dart. */ resolvedTypeArguments?: ResolvedTypeMap; } /** * Summary information on what is imported via a particular import. */ export class ImportSummary { showAll = false; shown: Set = new Set(); asPrefix: string; } export type Constructor = ts.ConstructorDeclaration|ts.ConstructSignatureDeclaration; export type ClassLike = ts.ClassLikeDeclaration|ts.InterfaceDeclaration; /** * Interface extending the true InterfaceDeclaration interface to add optional state we store on * interfaces to simplify conversion to Dart classes. */ export interface ExtendedInterfaceDeclaration extends ts.InterfaceDeclaration { /** * The type associated with this interface that we want to treat as the concrete location of this * interface to enable interfaces that act like constructors. Because Dart does not permit calling * objects like constructors we have to add this workaround. */ constructedType?: ts.InterfaceDeclaration|ts.TypeLiteralNode; } export function ident(n: ts.Node): string { if (ts.isIdentifier(n) || ts.isStringLiteralLike(n)) { return n.text; } if (ts.isQualifiedName(n)) { const leftName = ident(n.left); if (leftName) { return leftName + '.' + ident(n.right); } } return null; } export function isFunctionTypedefLikeInterface(ifDecl: ts.InterfaceDeclaration): boolean { return ifDecl.members && ifDecl.members.length === 1 && ts.isCallSignatureDeclaration(ifDecl.members[0]); } export function isExtendsClause(heritageClause: ts.HeritageClause) { return heritageClause.token === ts.SyntaxKind.ExtendsKeyword && !ts.isInterfaceDeclaration(heritageClause.parent); } export function isConstructor(n: ts.Node): n is Constructor { return ts.isConstructorDeclaration(n) || ts.isConstructSignatureDeclaration(n); } export function isStatic(n: ts.Node): boolean { let hasStatic = false; ts.forEachChild(n, (child) => { if (child.kind === ts.SyntaxKind.StaticKeyword) { hasStatic = true; } }); return hasStatic; } export function isReadonly(n: ts.Node): boolean { let hasReadonly = false; ts.forEachChild(n, (child) => { if (child.kind === ts.SyntaxKind.ReadonlyKeyword) { hasReadonly = true; } }); return hasReadonly; } export function isCallableType(type: ts.TypeNode, tc: ts.TypeChecker): boolean { if (isFunctionType(type, tc)) return true; if (ts.isTypeReferenceNode(type)) { if (tc.getSignaturesOfType(tc.getTypeAtLocation(type), ts.SignatureKind.Call).length > 0) return true; } return false; } /** * Returns whether a type declaration is on we can generate a named Dart type for. * For unsupported alias types we need to manually substitute the expression * the alias corresponds to in call sites. */ export function supportedTypeDeclaration(decl: ts.Declaration): boolean { if (ts.isTypeAliasDeclaration(decl)) { let type = decl.type; return ts.isTypeLiteralNode(type) || ts.isFunctionTypeNode(type); } return true; } export function isFunctionType(type: ts.TypeNode, tc: ts.TypeChecker): boolean { if (ts.isFunctionTypeNode(type)) return true; if (ts.isTypeReferenceNode(type)) { let t = tc.getTypeAtLocation(type); if (t.symbol && t.symbol.flags & ts.SymbolFlags.Function) return true; } if (ts.isIntersectionTypeNode(type)) { let types = type.types; for (let i = 0; i < types.length; ++i) { if (isFunctionType(types[i], tc)) { return true; } } return false; } if (ts.isUnionTypeNode(type)) { let types = type.types; for (let i = 0; i < types.length; ++i) { if (!isFunctionType(types[i], tc)) { return false; } } return true; } // Warning: if the kind is a reference type and the reference is to an // interface that only has a call member we will not return that it is a // function type. if (ts.isTypeLiteralNode(type)) { let members = type.members; for (let i = 0; i < members.length; ++i) { if (ts.isCallSignatureDeclaration(members[i])) { return false; } } return true; } return false; } /** * Whether a parameter declaration is specifying information about the type of ""this"" passed to * the function instead of being a normal type parameter representable by a Dart type. */ export function isThisParameter(param: ts.ParameterDeclaration): boolean { return param.name && ts.isIdentifier(param.name) && param.name.text === 'this'; } /** * Dart does not have a concept of binding the type of the ""this"" parameter to a method. */ export function filterThisParameter(params: ts.NodeArray): ts.ParameterDeclaration[] { let ret: ts.ParameterDeclaration[] = []; for (let i = 0; i < params.length; i++) { let param = params[i]; if (!isThisParameter(param)) { ret.push(param); } } return ret; } export function isTypeNode(node: ts.Node): boolean { switch (node.kind) { case ts.SyntaxKind.IntersectionType: case ts.SyntaxKind.UnionType: case ts.SyntaxKind.ParenthesizedType: case ts.SyntaxKind.TypeReference: case ts.SyntaxKind.TypeLiteral: case ts.SyntaxKind.LastTypeNode: case ts.SyntaxKind.LiteralType: case ts.SyntaxKind.ArrayType: case ts.SyntaxKind.TypeOperator: case ts.SyntaxKind.IndexedAccessType: case ts.SyntaxKind.MappedType: case ts.SyntaxKind.TypePredicate: case ts.SyntaxKind.TypeQuery: case ts.SyntaxKind.TupleType: case ts.SyntaxKind.NumberKeyword: case ts.SyntaxKind.StringKeyword: case ts.SyntaxKind.VoidKeyword: case ts.SyntaxKind.NullKeyword: case ts.SyntaxKind.UndefinedKeyword: case ts.SyntaxKind.BooleanKeyword: case ts.SyntaxKind.AnyKeyword: case ts.SyntaxKind.NeverKeyword: case ts.SyntaxKind.FunctionType: case ts.SyntaxKind.ThisType: return true; default: return false; } } export function isPromise(type: ts.TypeNode): boolean { return type && ts.isTypeReferenceNode(type) && ident(type.typeName) === 'Promise'; } export function isCallable(decl: ClassLike): boolean { let members = decl.members as ReadonlyArray; return members.some((member) => { return member.kind === ts.SyntaxKind.CallSignature; }); } export function copyLocation(src: ts.Node, dest: ts.Node) { dest.pos = src.pos; dest.end = src.end; dest.parent = src.parent; } export function cloneNodeArray(src?: ts.NodeArray): ts.NodeArray| undefined { if (!src) { return undefined; } const clone = ts.createNodeArray(src.map(ts.getMutableClone)); copyNodeArrayLocation(src, clone); return clone; } export function copyNodeArrayLocation(src: ts.TextRange, dest: ts.NodeArray) { dest.pos = src.pos; dest.end = src.end; } export function getAncestor(n: ts.Node, kind: ts.SyntaxKind): ts.Node { for (let parent = n; parent; parent = parent.parent) { if (parent.kind === kind) return parent; } return null; } export function getEnclosingClass(n: ts.Node): ClassLike { while (n) { if (ts.isClassDeclaration(n) || ts.isInterfaceDeclaration(n)) { return n; } n = n.parent; } return null; } export function isConstCall(node: ts.CallExpression): boolean { return node && ident(node.expression) === 'CONST_EXPR'; } export function isInsideConstExpr(node: ts.Node): boolean { return isConstCall(getAncestor(node, ts.SyntaxKind.CallExpression)); } export function getModuleBlock(moduleDecl: ts.ModuleDeclaration): ts.ModuleBlock { while (ts.isModuleDeclaration(moduleDecl.body)) { moduleDecl = moduleDecl.body; } if (ts.isModuleBlock(moduleDecl.body)) { return moduleDecl.body; } else { throw new Error('Module body must be a module block.'); } } /** * Determine the full module name including dots. * * e.g. returns 'foo.bar' for a declaration of namespace or module foo.bar */ export function getModuleName(moduleDecl: ts.ModuleDeclaration): string { let name = moduleDecl.name.text; while (ts.isModuleDeclaration(moduleDecl.body)) { moduleDecl = moduleDecl.body; name += '.' + moduleDecl.name.text; } return name; } export function formatType(s: string, comment: string, options: TypeDisplayOptions): string { if (!comment || options.hideComment) { return s; } else if (options.insideComment) { // When inside a comment we only need to emit the comment version which // is the syntax we would like to use if Dart supported all language // features we would like to use for interop. return comment; } else { let sb = s + '/*'; // Check if the comment is a valid type name in which case it is safe to use the Dart code // written in comments syntax. const stubToMakeTypeValidStatement = ' DUMMY_VARIABLE_NAME;'; comment = comment.trim(); let statement = comment + stubToMakeTypeValidStatement; let result = dartStyle.formatCode(statement); if (!result.error) { result.code = result.code.trim(); let expectedStubIndex = result.code.length - stubToMakeTypeValidStatement.length; if (result.code.lastIndexOf(stubToMakeTypeValidStatement) === expectedStubIndex) { comment = result.code.substring(0, expectedStubIndex).trim(); } } sb += comment; sb += '*/'; return sb; } } export class TranspilerBase { private idCounter = 0; constructor(protected transpiler: Transpiler) {} visit(n: ts.Node) { this.transpiler.visit(n); } pushContext(context: OutputContext) { this.transpiler.pushContext(context); } popContext() { this.transpiler.popContext(); } emit(s: string) { this.transpiler.emit(s); } emitNoSpace(s: string) { this.transpiler.emitNoSpace(s); } emitType(s: string, comment: string) { this.transpiler.emitType(s, comment); } maybeLineBreak() { return this.transpiler.maybeLineBreak(); } enterCodeComment() { return this.transpiler.enterCodeComment(); } exitCodeComment() { return this.transpiler.exitCodeComment(); } maybeWrapInCodeComment({shouldWrap = true, newLine = false}, emit: () => void): void { if (shouldWrap) { this.enterCodeComment(); } emit(); if (shouldWrap) { this.exitCodeComment(); } if (newLine) { this.emit('\n'); } } enterTypeArguments() { this.transpiler.enterTypeArgument(); } exitTypeArguments() { this.transpiler.exitTypeArgument(); } get insideTypeArgument() { return this.transpiler.insideTypeArgument; } get insideCodeComment() { return this.transpiler.insideCodeComment; } getImportSummary(libraryUri: string): ImportSummary { if (!this.transpiler.imports.has(libraryUri)) { let summary = new ImportSummary(); this.transpiler.imports.set(libraryUri, summary); return summary; } return this.transpiler.imports.get(libraryUri); } /** * Add an import. If an identifier is specified, only show that name. */ addImport(libraryUri: string, identifier?: string): ImportSummary { let summary = this.getImportSummary(libraryUri); if (identifier) { summary.shown.add(identifier); } else { summary.showAll = true; } return summary; } /** * Return resolved name possibly including a prefix for the identifier. */ resolveImportForSourceFile(sourceFile: ts.SourceFile, context: ts.SourceFile, identifier: string): string { if (sourceFile === context) { return identifier; } if (sourceFile.hasNoDefaultLib) { // We don't want to emit imports to default lib libraries as we replace with Dart equivalents // such as dart:html, etc. return identifier; } const relativePath = path.relative(path.dirname(context.fileName), sourceFile.fileName); const fileName = this.getDartFileName(relativePath); const identifierParts = identifier.split('.'); identifier = identifierParts[identifierParts.length - 1]; const summary = this.addImport(this.transpiler.getDartFileName(fileName), identifier); if (summary.asPrefix) { return summary.asPrefix + '.' + identifier; } return identifier; } reportError(n: ts.Node, message: string) { this.transpiler.reportError(n, message); } visitNode(n: ts.Node): boolean { throw new Error('not implemented'); } visitEach(nodes: ts.NodeArray) { nodes.forEach((n) => this.visit(n)); } visitEachIfPresent(nodes?: ts.NodeArray) { if (nodes) this.visitEach(nodes); } visitList(nodes: ts.NodeArray, [MASK] ?: string) { [MASK] = [MASK] || ','; for (let i = 0; i < nodes.length; i++) { this.visit(nodes[i]); if (i < nodes.length - 1) this.emitNoSpace( [MASK] ); } } /** * Returns whether any parameters were actually emitted. */ visitParameterList(nodes: ts.ParameterDeclaration[], namesOnly: boolean): boolean { let emittedParameters = false; for (let i = 0; i < nodes.length; ++i) { let param = nodes[i]; if (!this.insideCodeComment && isThisParameter(param)) { // Emit the this type in a comment as it could be of interest to Dart users who are // calling allowInteropCaptureThis to bind a Dart method. this.enterCodeComment(); this.visit(param.type); this.emit('this'); this.exitCodeComment(); continue; } if (emittedParameters) { this.emitNoSpace(','); } if (namesOnly) { this.emit(ident(param.name)); } else { this.visit(param); } emittedParameters = true; } return emittedParameters; } uniqueId(name: string): string { const id = this.idCounter++; return `_${name}\$\$js_facade_gen\$${id}`; } assert(c: ts.Node, condition: boolean, reason: string): void { if (!condition) { this.reportError(c, reason); throw new Error(reason); } } getAncestor(n: ts.Node, kind: ts.SyntaxKind): ts.Node { for (let parent = n; parent; parent = parent.parent) { if (parent.kind === kind) return parent; } return null; } hasAncestor(n: ts.Node, kind: ts.SyntaxKind): boolean { return !!getAncestor(n, kind); } hasAnnotation(decorators: ts.NodeArray, name: string): boolean { if (!decorators) return false; return decorators.some((d) => { let decName = ident(d.expression); if (decName === name) return true; if (!ts.isCallExpression(d.expression)) return false; let callExpr = d.expression; decName = ident(callExpr.expression); return decName === name; }); } hasNodeFlag(n: ts.Declaration, flag: ts.NodeFlags): boolean { return n && (ts.getCombinedNodeFlags(n) & flag) !== 0 || false; } hasModifierFlag(n: ts.Declaration, flag: ts.ModifierFlags): boolean { return n && (ts.getCombinedModifierFlags(n) & flag) !== 0 || false; } getRelativeFileName(fileName: string): string { return this.transpiler.getRelativeFileName(fileName); } getDartFileName(fileName?: string): string { return this.transpiler.getDartFileName(fileName); } maybeVisitTypeArguments(n: {typeArguments?: ts.NodeArray}) { if (n.typeArguments) { this.emitNoSpace('<'); this.enterTypeArguments(); this.visitList(n.typeArguments); this.exitTypeArguments(); this.emitNoSpace('>'); } } visitParameters(parameters: ts.NodeArray, {namesOnly = false}) { this.emitNoSpace('('); let firstInitParamIdx = 0; for (; firstInitParamIdx < parameters.length; firstInitParamIdx++) { // ObjectBindingPatterns are handled within the parameter visit. let isOpt = parameters[firstInitParamIdx].initializer || parameters[firstInitParamIdx].questionToken || parameters[firstInitParamIdx].dotDotDotToken; if (isOpt && !ts.isObjectBindingPattern(parameters[firstInitParamIdx].name)) { break; } } let hasValidParameters = false; if (firstInitParamIdx !== 0) { let requiredParams = parameters.slice(0, firstInitParamIdx); hasValidParameters = this.visitParameterList(requiredParams, namesOnly); } if (firstInitParamIdx !== parameters.length) { if (hasValidParameters) this.emitNoSpace(','); let positionalOptional = parameters.slice(firstInitParamIdx, parameters.length); if (!namesOnly) { this.emit('['); } this.visitParameterList(positionalOptional, namesOnly); if (!namesOnly) { this.emitNoSpace(']'); } } this.emitNoSpace(')'); } } ",separator 124,"import { applyStyles } from ""@popperjs/core""; import ""dayjs/locale/zh-cn""; import locale, { ElButton, ElMessage, ElMessageBox, ElNotification, ElMenu, ElMenuItem, ElSubMenu, ElBreadcrumb, ElBreadcrumbItem, ElIcon, ElTooltip, ElDropdown, ElDropdownItem, ElDropdownMenu, } from ""element-plus""; import ""element-plus/dist/index.css""; // import ""element-plus/lib/theme-chalk/index.css""; import ElementPlus from ""element-plus""; import zhCn from ""element-plus/es/locale/lang/zh-cn""; import { App } from ""vue""; export type Size = ""default"" | ""small"" | ""large"" ; interface ElementOptions{ size:Size } export default (app: App,options:ElementOptions): void => { app.use(ElementPlus, { locale: zhCn, }); const [MASK] = [ ElButton, ElMessage, ElNotification, ElMessageBox, ElMenu, ElMenuItem, ElSubMenu, ElBreadcrumb, ElBreadcrumbItem, ElIcon, ElTooltip, ElDropdown, ElDropdownItem, ElDropdownMenu, ]; [MASK] .forEach((component) => { app.use(component); }); app.config.globalProperties.$message = ElMessage; app.config.globalProperties.$notify = ElNotification; app.config.globalProperties.$confirm = ElMessageBox.confirm; app.config.globalProperties.$alert = ElMessageBox.alert; app.config.globalProperties.$prompt = ElMessageBox.prompt; // element-plus全局配置 // 说明文档:https://element-plus.gitee.io/#/zh-CN/component/quickstart#quan-ju-pei-zhi // 该对象目前支持 size 与 zIndex 字段。size 用于改变组件的默认尺寸 small,zIndex 设置弹框的初始 z-index(默认值:2000)。 app.config.globalProperties.$ELEMENT = { size: options.size, // zIndex: 2000 弹框zIndex默认值:2000 }; }; ",components 125,"import { getVariable } from ""azure-pipelines-task-lib""; enum CommentType { Unknown = 0, Text = 1, CodeChange = 2, System = 3 } interface Thread { id: number; isDeleted: boolean; properties?: Record; } interface GetVariablesOptions { accessToken?: string; } function getVariables({ accessToken }: GetVariablesOptions = {}) { return { token: accessToken ?? getVariable(""System.AccessToken""), collectionUri: getVariable(""System.CollectionUri""), repositoryId: getVariable(""Build.Repository.ID""), pullRequestId: getVariable(""System.PullRequest.PullRequestId"") }; } interface GetThreadOptions { accessToken?: string; } async function getThreads({ accessToken }: GetThreadOptions = {}): Promise { const { token, collectionUri, repositoryId, pullRequestId } = getVariables({ accessToken }); const url = `${collectionUri}/_apis/git/repositories/${repositoryId}/pullRequests/${pullRequestId}/threads?api-version=7.1-preview.1`; const response = await fetch(url, { headers: { ""Authorization"": `Basic ${btoa(`:${token}`)}` } }); if (!response.ok) { throw new Error(`Failed to fetch threads. Status: ${response.status}`); } const result = await response.json(); return result.value ?? []; } interface CreateThreadOptions { id?: string; accessToken?: string; } async function createThread(content: string, { id, accessToken }: CreateThreadOptions = {}) { const { token, collectionUri, repositoryId, pullRequestId } = getVariables({ accessToken }); const url = `${collectionUri}/_apis/git/repositories/${repositoryId}/pullRequests/${pullRequestId}/threads?api-version=7.1-preview.1`; const response = await fetch(url, { method: ""POST"", headers: { ""Content-Type"": ""application/json"", ""Authorization"": `Basic ${btoa(`:${token}`)}` }, body: JSON.stringify({ status: ""Unknown"", properties: { id }, comments: [ { commentType: CommentType.CodeChange, content } ] }) }); if (!response.ok) { throw new Error(`Failed to create thread. Status: ${response.status}`); } } interface EditThreadOptions { accessToken?: string; } async function editThread(content: string, [MASK] : number, commentId: number, { accessToken }: EditThreadOptions = {}) { const { token, collectionUri, repositoryId, pullRequestId } = getVariables({ accessToken }); const url = `${collectionUri}/_apis/git/repositories/${repositoryId}/pullRequests/${pullRequestId}/threads/${ [MASK] }/comments/${commentId}?api-version=7.1-preview.1`; const response = await fetch(url, { method: ""PATCH"", headers: { ""Content-Type"": ""application/json"", ""Authorization"": `Basic ${btoa(`:${token}`)}` }, body: JSON.stringify({ commentType: CommentType.CodeChange, content }) }); if (response.status !== 200) { throw new Error(`Failed to edit threads. Status: ${response.status}`); } } export interface PostThreadOptions { id?: string; accessToken?: string; } export async function postThread(content: string, { id, accessToken }: PostThreadOptions = {}) { const { pullRequestId } = getVariables(); // Not running in a PR, so we don't need to post a comment. if (!pullRequestId) { return; } try { let match: Thread | undefined = undefined; if (id) { const threads = await getThreads({ accessToken }); match = threads.find(thread => !thread.isDeleted && thread.properties?.id?.$value === id); } if (match) { await editThread(content, match.id, 1, { accessToken }); } else { await createThread(content, { id, accessToken }); } } catch (error) { throw new Error(`Could not post comment. Make sure the Project Collection Build Service Accounts has the 'Contribute to pull requests' permission set to 'Allowed'. ${error}`); } } ",threadId 126,"// @ts-ignore import type { EndpointConfig, Accountability } from ""@directus/types"" import axios from ""axios"" import { PubSub } from ""@google-cloud/pubsub"" import { randomUUID } from ""crypto"" import { CloudEvent } from ""cloudevents"" const apiPath = process.env.API_PATH const apiSecret = process.env.API_SECRET const getAccountability = (req: any) => { return req.accountability as Accountability } const getUserId = (req: any) => { try { return getAccountability(req).user ?? null } catch { return null } } const postQuery = async (query: string, variables: any) => { return await axios.post( apiPath + ""admin"", { query: query, variables: variables, }, { headers: { ""Content-Type"": ""application/json"", ""X-Api-Key"": apiSecret, }, } ) } const projectId = process.env.PUBSUB_PROJECT_ID const topicId = process.env.PUBSUB_TOPIC_ID const pubsubEnabled = process.env.PUBSUB_ENABLED !== ""false"" const pubsub = pubsubEnabled ? new PubSub({ projectId, }) : null; const endpointConfig: EndpointConfig = { id: ""tools"", handler: ( [MASK] ) => { [MASK] .post(""/preview/collection"", async (req, res) => { const userId = getUserId(req) if (userId == null) { res.status(401).send(""Unauthenticated"") return } const filter = req.body.filter try { const body = `query($filter: String!) { preview { collection(filter: $filter) { items { id collection title } } } }` const result = await postQuery(body, { filter: JSON.stringify(filter), }) res.send(result.data.data.preview.collection.items) return } catch (e) { console.log(e) console.log(""Couldn't fetch data from API"") } res.status(500).send( JSON.stringify({ error: ""Couldn't fetch data from API"", }) ) }) [MASK] .get(""/preview/asset/:assetId"", async (req, res) => { const userId = getUserId(req) if (userId == null) { res.status(401).send(""Unauthenticated"") return } try { const body = `query($assetId: ID!) { preview { asset(id: $assetId) { url type } } }` const result = await postQuery(body, { assetId: req.params[""assetId""], }) res.status(200).send(result.data.data.preview.asset) return } catch { console.log(""Couldn't fetch data from API"") } res.status(500).send( JSON.stringify({ error: ""Couldn't fetch data from API"", }) ) }) [MASK] .post(""/timedmetadata/import"", async (req: any, res: any) => { const userId = getUserId(req) if (userId == null) { res.status(401).send(""Unauthenticated"") return } const { collection, itemId } = req.body as { collection: string; itemId: string } try { if (collection == ""episodes"") { const body = `query($episodeId: ID!) { episodes { importTimedMetadata(episodeId: $episodeId) } }` const result = await postQuery(body, { episodeId: itemId, }) console.log(result.data) res.status(200).send( result.data.data.episodes.importTimedMetadata ) } else if (collection === ""mediaitems"") { const body = `query($mediaItemId: ID!) { mediaItems { importTimedMetadata(mediaItemId: $mediaItemId) } }` const result = await postQuery(body, { mediaItemId: itemId, }) console.log(result.data) res.status(200).send( result.data.data.mediaItems.importTimedMetadata ) } return } catch (e) { console.log(""Couldn't fetch data from API"") console.error(e) } res.status(500).send( JSON.stringify({ error: ""Couldn't fetch data from API"", }) ) }) [MASK] .get(""/filters/refresh"", async (req, res) => { const userId = getUserId(req) if (userId == null) { res.status(401).send(""Unauthenticated"") return } const topic = pubsub?.topic(topicId!) const event = new CloudEvent({ specversion: ""1.0"", id: randomUUID(), type: ""view.refresh"", source: ""directus"", datacontenttype: ""application/json"", data: { viewName: ""filter_dataset"", force: false, }, }) await topic?.publishMessage({ data: Buffer.from(JSON.stringify(event)), }) res.status(200).send() }) [MASK] .get(""/translations/sync"", async (req, res) => { const userId = getUserId(req) if (userId == null) { res.status(401).send(""Unauthenticated"") return } const topic = pubsub?.topic(topicId!) const event = new CloudEvent({ specversion: ""1.0"", id: randomUUID(), type: ""translations.sync"", source: ""directus"", datacontenttype: ""application/json"", }) await topic?.publishMessage({ data: Buffer.from(JSON.stringify(event)), }) res.status(200).send() }) }, } export default endpointConfig ",router 127,"import { graceData } from './data/grace-data'; import { gldasData } from './data/gldas-data'; export interface Env { // Environment bindings } // CORS headers for all responses const corsHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type', }; // Helper function to create JSON response with CORS function jsonResponse(data: any, status = 200) { return new Response(JSON.stringify(data), { status, headers: { 'Content-Type': 'application/json', ...corsHeaders, }, }); } // Calculate statistics for data function calculateStats(data: number[]) { const mean = data.reduce((a, b) => a + b, 0) / data.length; const min = Math.min(...data); const max = Math.max(...data); return { mean, min, max }; } // Calculate trend (simple linear regression) function calculateTrend(data: { date: string; value: number }[]) { const n = data.length; if (n === 0) return { slope: 0, intercept: 0 }; // Convert dates to numeric values (days since first date) const firstDate = new Date(data[0].date).getTime(); const x = data.map(d => (new Date(d.date).getTime() - firstDate) / (1000 * 60 * 60 * 24)); const y = data.map(d => d.value); const sumX = x.reduce((a, b) => a + b, 0); const sumY = y.reduce((a, b) => a + b, 0); const sumXY = x.reduce((acc, xi, i) => acc + xi * y[i], 0); const sumX2 = x.reduce((acc, xi) => acc + xi * xi, 0); const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX); const intercept = (sumY - slope * sumX) / n; // Convert slope from per day to per year const annualTrend = slope * 365.25; return { slope: annualTrend, intercept }; } export default { async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { const url = new URL(request.url); const path = url.pathname; // Handle CORS preflight if (request.method === 'OPTIONS') { return new Response(null, { headers: corsHeaders }); } // Route handling switch (path) { case '/': return jsonResponse({ message: 'WaterTrace API - Cloudflare Workers Edition', version: '2.0', endpoints: [ '/api/health', '/api/historical/timeseries', '/api/recent/timeseries', '/api/gldas/trend-analysis', '/api/analysis/summary', '/api/combined/timeline', '/api/districts/groundwater', '/api/predict' ] }); case '/api/health': return jsonResponse({ status: 'healthy', timestamp: new Date().toISOString() }); case '/api/historical/timeseries': // Return GRACE data const [MASK] = graceData.map(d => d.groundwater_cm); const graceStats = calculateStats( [MASK] ); return jsonResponse({ data: graceData, summary: { period: '2002-2017', data_source: 'GRACE satellite', total_records: graceData.length, statistics: graceStats, unit: 'cm' } }); case '/api/recent/timeseries': // Return GLDAS data matching Flask API const gldasBaseline = gldasData.slice(0, 12).reduce((acc, d) => acc + d.groundwater_cm, 0) / 12; const gldasTimeseries = gldasData.map(d => ({ date: d.date, groundwater_cm: d.groundwater_cm, data_source: 'GLDAS', groundwater_anomaly_cm: d.groundwater_cm - gldasBaseline })); return jsonResponse({ success: true, data: gldasTimeseries, summary: { period: '2018-2024', data_source: 'GLDAS model', total_records: gldasData.length, baseline_value: gldasBaseline, unit: 'kg/m²' } }); case '/api/gldas/trend-analysis': // Analyze GLDAS trends matching Flask API structure const baseline2018 = gldasData.filter(d => d.year === 2018).reduce((sum, d) => sum + d.groundwater_cm, 0) / 12; const currentValue = gldasData[gldasData.length - 1].groundwater_cm; const totalChange = currentValue - gldasData[0].groundwater_cm; // Calculate trend const gldasTrendData = gldasData.map(d => ({ date: d.date, value: d.groundwater_cm })); const trend = calculateTrend(gldasTrendData); const annualChange = trend.slope; // Interpretation let interpretation = ""Relatively stable - minimal change detected""; if (annualChange < -2) { interpretation = ""Declining trend - likely continued groundwater depletion""; } else if (annualChange > 2) { interpretation = ""Increasing trend - possible stabilization or recovery""; } // Time series with anomalies const timeSeries = gldasData.map(d => ({ date: d.date, absolute_value: d.groundwater_cm, anomaly: d.groundwater_cm - baseline2018, year: d.year })); return jsonResponse({ success: true, analysis: { baseline_2018: baseline2018, current_value: currentValue, total_change: totalChange, annual_change: annualChange, monthly_change: annualChange / 12, interpretation: interpretation, trend_direction: annualChange > 0 ? 'increasing' : 'decreasing', comparison_note: 'GLDAS measures soil moisture, not direct groundwater. Positive values may indicate better water retention.' }, time_series: timeSeries, metadata: { data_source: 'GLDAS V021', variable: 'Deep Soil Moisture (100-200cm)', units: 'kg/m²', period: '2018-01 to 2024-12' } }); case '/api/analysis/summary': // Return project summary return jsonResponse({ project: 'WaterTrace - Pakistan Groundwater Monitoring', description: 'Comprehensive groundwater depletion analysis using satellite data', key_findings: [ 'Pakistan lost 13.71 cm of groundwater from 2002-2017', 'Annual depletion rate: -0.81 cm per year during GRACE period', 'Recent GLDAS data shows slight improvement: +1.5 kg/m²/year', 'Most affected region: Quetta with -15.3 cm depletion', 'Critical districts: Lahore (-12.5 cm), Faisalabad (-10.8 cm)', '145 districts monitored across 4 provinces' ], data_sources: { historical: 'GRACE satellite (2002-2017)', recent: 'GLDAS model (2018-2024)' }, coverage: '145 districts across Pakistan', study_area: { country: 'Pakistan', districts: 145, provinces: 4, area_km2: 881913 }, datasets: { historical: { name: 'GRACE', period: '2002-2017', data_points: 164, source: 'NASA/GFZ' }, recent: { name: 'GLDAS', period: '2018-2024', data_points: 84, source: 'NASA LDAS' } } }); case '/api/combined/timeline': // Combine GRACE and GLDAS data with EXACT same calculations as Flask const combinedData = []; // Add GRACE data (already in anomalies) graceData.forEach(d => { combinedData.push({ date: d.date, value: d.groundwater_cm, // Already anomalies in cm source: 'GRACE', type: 'measured_anomaly' }); }); // Add GLDAS data converted to anomalies // Calculate 2018 baseline const gldas2018 = gldasData.filter(d => d.year === 2018); const baselineKg = gldas2018.reduce((sum, d) => sum + d.groundwater_cm, 0) / gldas2018.length; // Convert GLDAS to anomalies and rough cm equivalent // Rough conversion: 10 kg/m² ≈ 1 cm of water const graceEndValue = -8.727905291100553; // Exact last GRACE value in 2017 gldasData.forEach(d => { const anomalyKg = d.groundwater_cm - baselineKg; const anomalyCmEquivalent = anomalyKg / 10; // Convert to cm scale combinedData.push({ date: d.date, value: graceEndValue + anomalyCmEquivalent, // Apply GRACE offset for continuity source: 'GLDAS', type: 'estimated_anomaly' }); }); // Sort by date combinedData.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()); // Calculate statistics const graceTimelineValues = combinedData.filter(d => d.source === 'GRACE').map(d => d.value); const gldasTimelineValues = combinedData.filter(d => d.source === 'GLDAS').map(d => d.value); return jsonResponse({ success: true, data: combinedData, summary: { grace_period: { start: '2002', end: '2017', final_value: graceTimelineValues[graceTimelineValues.length - 1] || null, trend: 'Declining at -0.81 cm/year' }, gldas_period: { start: '2018', end: '2024', estimated_current: gldasTimelineValues[gldasTimelineValues.length - 1] || null, trend: 'Slight improvement (+0.15 cm/year equivalent)' }, interpretation: 'GLDAS data suggests possible stabilization after severe depletion' } }); case '/api/districts/groundwater': // Complete district data matching Flask API const regionalPatterns = { 'Punjab': { 'Lahore': -12.5, 'Faisalabad': -10.8, 'Multan': -9.2, 'Rawalpindi': -6.5, 'Gujranwala': -11.3, 'Sialkot': -9.8, 'Sargodha': -10.9, 'Bahawalpur': -8.1, 'Sheikhupura': -10.2, 'Jhang': -7.4 }, 'Sindh': { 'Karachi': -4.3, 'Hyderabad': -6.5, 'Sukkur': -7.8, 'Larkana': -8.4, '': -7.1, 'Nawabshah': -8.0, 'Jacobabad': -9.3, 'Shikarpur': -8.9 }, 'Khyber Pakhtunkhwa': { 'Peshawar': -5.3, 'Mardan': -4.8, 'Mingora': -1.2, 'Abbottabad': -2.1, 'Mansehra': -2.8, 'Kohat': -6.0, 'D': -7.1 }, 'Balochistan': { 'Quetta': -15.3, 'Gwadar': -3.5, 'Turbat': -6.1, 'Khuzdar': -10.0, 'Chaman': -13.0, 'Zhob': -8.6, 'Sibi': -11.4 } }; // Convert to features array const districtFeatures = []; for (const [province, districts] of Object.entries(regionalPatterns)) { for (const [district, change] of Object.entries(districts)) { districtFeatures.push({ district, province, groundwater_change: change, status: change < -10 ? 'Critical' : change < -5 ? 'Warning' : change < 0 ? 'Moderate' : 'Improving' }); } } // Calculate summary statistics const allValues = districtFeatures.map(d => d.groundwater_change); const avgChange = allValues.reduce((a, b) => a + b, 0) / allValues.length; return jsonResponse({ success: true, data: { type: 'FeatureCollection', features: districtFeatures.map(d => ({ type: 'Feature', properties: d, geometry: { type: 'Point', coordinates: [] // Empty as we handle coordinates in frontend } })) }, summary: { total_districts: districtFeatures.length, average_change: avgChange, most_depleted: Math.min(...allValues), most_improved: Math.max(...allValues), critical_districts: allValues.filter(v => v < -10).length, improving_districts: allValues.filter(v => v > 0).length, data_shown: districtFeatures.length, most_affected: 'Quetta' } }); case '/api/predict': if (request.method !== 'POST') { return jsonResponse({ error: 'Method not allowed' }, 405); } try { const body = await request.json() as { years?: number }; const years = body.years || 5; // Simple prediction based on recent trend const recentTrend = -0.81; // cm/year from historical data const lastValue = graceData[graceData.length - 1].groundwater_cm; const predictions = []; for (let i = 1; i <= years; i++) { predictions.push({ year: 2017 + i, predicted_groundwater_cm: lastValue + (recentTrend * i), confidence: 'medium', method: 'Linear extrapolation' }); } return jsonResponse({ predictions, parameters: { base_year: 2017, trend_rate: recentTrend, years_predicted: years } }); } catch (error) { return jsonResponse({ error: 'Invalid request body' }, 400); } default: return jsonResponse({ error: 'Not found' }, 404); } }, };",graceValues 128,"import type { MetadataRoute } from 'next' import { rankedBlogs,rankedEssays,rankedTranslations,rankedNotes,rankedStory,rankedWritings } from '@/lib/filteredDatas' export default function sitemap(): MetadataRoute.Sitemap { const blogs:MetadataRoute.Sitemap = rankedBlogs.map(ele => ({ url: `https://leewendao.otterstack.cn${ele.slug}`, lastModified: ele.date, changeFrequency: 'weekly', priority: 0.5, })) const essays:MetadataRoute.Sitemap = rankedEssays.map(ele => ({ url: `https://leewendao.otterstack.cn${ele.slug}`, lastModified: ele.date, changeFrequency: 'weekly', priority: 0.5, })) const [MASK] :MetadataRoute.Sitemap = rankedTranslations.map(ele => ({ url: `https://leewendao.otterstack.cn${ele.slug}`, lastModified: ele.date, changeFrequency: 'weekly', priority: 0.3, })) const notes:MetadataRoute.Sitemap = rankedNotes.map(ele => ({ url: `https://leewendao.otterstack.cn${ele.slug}`, lastModified: ele.date, changeFrequency: 'weekly', priority: 0.3, })) const story:MetadataRoute.Sitemap = rankedStory.map(ele => ({ url: `https://leewendao.otterstack.cn${ele.slug}`, lastModified: ele.date, changeFrequency: 'weekly', priority: 0.3, })) return [ { url: 'https://leewendao.otterstack.cn/', lastModified: new Date(), changeFrequency: 'daily', priority: 1, }, { url: 'https://leewendao.otterstack.cn/writings', lastModified: new Date(), changeFrequency: 'daily', priority: 1, }, ...blogs, ...essays, ... [MASK] , ...notes, ...story, ] }",translations 129,"/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ import httpRequest from '@/api/request' import type { Catalog, Database, Table, Schema, Manifest, Snapshot, Datafile, TableQuery } from './types' import type { ResponseOptions } from '@/api/types' export * from './types' // #region catalog-controller /** * # Get all catalog */ export const getAllCatalogs = () => { return httpRequest.get>('/catalog/getAllCatalogs') } /** * # Get database by catalog id */ export const getDatabasesByCatalogId = (id: number) => { return httpRequest.get>(`/database/list?catalogId=${id}`) } /** * # Get table by catalog id and database name */ export const getTables = ( [MASK] : TableQuery) => { return httpRequest.post>(`/table/list`, [MASK] ) } /** * # Get schema */ export const getSchema = () => { return httpRequest.createHooks!({ url: '/metadata/query/schema', method: 'post', }) } /** * # Get manifest */ export const getManifest = () => { return httpRequest.createHooks!({ url: '/metadata/query/manifest', method: 'post', }) } /** * # Get data file */ export const getDataFile = () => { return httpRequest.createHooks!({ url: '/metadata/query/dataFile', method: 'post', }) } /** * # Get snapshot */ export const getSnapshot = () => { return httpRequest.createHooks!({ url: '/metadata/query/snapshot', method: 'post', }) } // #endregion ",params 130,"import validateObject, { isArrayOf, isEqualTo, isNumber, isString, isOneOf } from ""./validateObject"" export type WorkspaceGrid = { name: string Nx: number Ny: number Nz: number x0: number y0: number z0: number dx: number dy: number dz: number } const isWorkspaceGridData = (x: any): x is WorkspaceGrid => { return validateObject(x, { name: isString, Nx: isNumber, Ny: isNumber, Nz: isNumber, x0: isNumber, y0: isNumber, z0: isNumber, dx: isNumber, dy: isNumber, dz: isNumber }, {allowAdditionalFields: true}) } export type WorkspaceSurface = { name: string vertices: number[][] faces: number[][] } const isWorkspaceSurfaceData = (x: any): x is WorkspaceSurface => { return validateObject(x, { name: isString, vertices: () => (true), faces: () => (true) }, {allowAdditionalFields: true}) } export type WorkspaceGridVectorField = { name: string gridName: string data: number[][][][] } const isWorkspaceGridVectorFieldData = (x: any): x is WorkspaceGridVectorField => { return validateObject(x, { name: isString, gridName: isString, data: () => (true) }, {allowAdditionalFields: true}) } export type WorkspaceGridScalarField = { name: string gridName: string data: number[][][] } const isWorkspaceGridScalarFieldData = (x: any): x is WorkspaceGridScalarField => { return validateObject(x, { name: isString, gridName: isString, data: () => (true) }, {allowAdditionalFields: true}) } type WorkspaceGridRegion = { name: string gridName: string data: number[][][] } const isWorkspaceGridRegionData = (x: any): x is WorkspaceGridRegion => { return validateObject(x, { name: isString, gridName: isString, data: () => (true) }, {allowAdditionalFields: true}) } export type WorkspaceSurfaceVectorField = { name: string surfaceName: string data: number[][] } const isWorkspaceSurfaceVectorFieldData = (x: any): x is WorkspaceSurfaceVectorField => { return validateObject(x, { name: isString, surfaceName: isString, data: () => (true) }, {allowAdditionalFields: true}) } export type WorkspaceSurfaceScalarField = { name: string surfaceName: string data: number[] } const isWorkspaceSurfaceScalarFieldData = (x: any): x is WorkspaceSurfaceScalarField => { return validateObject(x, { name: isString, surfaceName: isString, data: () => (true) }, {allowAdditionalFields: true}) } type WorkspaceSurfaceRegion = { name: string surfaceName: string data: number[] } const isWorkspaceSurfaceRegionData = (x: any): x is WorkspaceSurfaceRegion => { return validateObject(x, { name: isString, surfaceName: isString, data: () => (true) }, {allowAdditionalFields: true}) } export type WorkspaceViewData = { type: 'workspace', grids: WorkspaceGrid[], surfaces: WorkspaceSurface[], gridVectorFields: WorkspaceGridVectorField[], gridScalarFields: WorkspaceGridScalarField[], gridRegions: WorkspaceGridRegion[], surfaceVectorFields: WorkspaceSurfaceVectorField[], surfaceScalarFields: WorkspaceSurfaceScalarField[], surfaceRegions: WorkspaceSurfaceRegion[] } type VolumeViewData = { type: 'volume' dataUri: string dataShape: number[] componentNames: string[] } | { type: 'vector_field' dataUri: string } | { type: 'surface' numVertices: number numFaces: number vertices: number[][] faces: number[][] } | WorkspaceViewData export const isVolumeViewData = (x: any): x is VolumeViewData => { const isVolumeData = (x: any) => { return validateObject(x, { type: isEqualTo('volume'), dataUri: isString, dataShape: isArrayOf(isNumber), componentNames: isArrayOf(isString) }, {allowAdditionalFields: true}) } const isVectorFieldData = (x: any) => { return validateObject(x, { type: isEqualTo('vector_field'), dataUri: isString, dataShape: isArrayOf(isNumber) }, {allowAdditionalFields: true}) } const [MASK] = (x: any) => { return validateObject(x, { type: isEqualTo('surface'), numVertices: isNumber, numFaces: isNumber, vertices: () => (true), faces: () => (true) }, {allowAdditionalFields: true}) } const isWorkspaceData = (x: any) => { return validateObject(x, { type: isEqualTo('workspace'), grids: isArrayOf(isWorkspaceGridData), surfaces: isArrayOf(isWorkspaceSurfaceData), gridVectorFields: isArrayOf(isWorkspaceGridVectorFieldData), gridScalarFields: isArrayOf(isWorkspaceGridScalarFieldData), gridRegions: isArrayOf(isWorkspaceGridRegionData), surfaceVectorFields: isArrayOf(isWorkspaceSurfaceVectorFieldData), surfaceScalarFields: isArrayOf(isWorkspaceSurfaceScalarFieldData), surfaceRegions: isArrayOf(isWorkspaceSurfaceRegionData) }, {allowAdditionalFields: true}) } return isOneOf([isVolumeData, isVectorFieldData, [MASK] , isWorkspaceData])(x) } export default VolumeViewData",isSurfaceData 131,"import ReactDOM from 'react-dom'; import { Portal } from './portal'; import ConfirmBox from './confirm'; import React from 'react'; import { mountRootId } from './config'; import { Options } from './types'; export const confirm = async (message: string, options?: Options): Promise => { const mount = await document.getElementById(mountRootId); if (!mount) { const rootMount = await document.createElement('div'); await rootMount.setAttribute('id', mountRootId); document.body.appendChild(rootMount); } return new Promise((resolve) => { const ConfirmBoxEl = React.createElement(ConfirmBox, { resolver: resolve, message, options, }); const [MASK] = React.createElement(Portal, null, ConfirmBoxEl); ReactDOM.render( [MASK] , document.getElementById(mountRootId)); }); }; ",PortalEl 132,"import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { UserService } from '../services/user.service'; @Injectable() export class JwtInterceptor implements HttpInterceptor { constructor(private userServiec: UserService) { } intercept( [MASK] : HttpRequest, next: HttpHandler): Observable> { let accessToken = localStorage.getItem('Access-Token'); if (accessToken != null) { [MASK] = [MASK] .clone({ setHeaders: { Authorization: `Bearer ${accessToken}` } }); } return next.handle( [MASK] ).pipe(catchError(err => { if (err.status === 401) { this.userServiec.setLoggedIn(false); } const error = err.error.message || err.statusText; return throwError(error); })); } }",request 133,"import express from 'express'; import routers from './routers'; import config from './config'; import log4js, { Configuration } from 'log4js'; import mongoose, { ConnectOptions } from 'mongoose'; type EnvType = 'dev' | 'prod'; let env: EnvType = 'prod'; if (String(process.env.NODE_ENV).trim() === 'dev') { env = 'dev'; } const mongoAddress = 'mongodb://localhost:27017/Genres'; export default async () => { const app = express(); log4js.configure(config.log4js as Configuration); // to disable caching of requests returning 304 instead of 200 app.disable('etag'); app.use(express.json({ limit: '1mb' })); app.use((req, _, next) => { const [MASK] = (_: string, value: unknown) => { if (value && typeof value === 'string') { const dateRegex = /^\d{2}-\d{2}-\d{4}$/; if (dateRegex.test(value)) { return new Date(value); } } return value; }; req.body = JSON.parse(JSON.stringify(req.body), [MASK] ); next(); }); app.use('/', routers); const port = env === 'dev' ? 3000 : 8888; const address = '0.0.0.0'; app.listen(port, address, () => { log4js.getLogger().info(`Example app listening on port ${address}:${port}`); }); await mongoose.connect(mongoAddress, { useNewUrlParser: true, useUnifiedTopology: true, socketTimeoutMS: 30000, } as ConnectOptions) .then(() => { console.log('Connected to MongoDB'); }) .catch((err) => { console.error('Error connecting to MongoDB:', err); }); return app; }; ",dateReviver 134,"import {Component, OnInit} from '@angular/core'; import {IdResponseDto, PolicyDefinitionResponseDto, PolicyService} from ""../../../mgmt-api-client""; import {BehaviorSubject, Observable, Observer, of} from ""rxjs""; import {first, map, switchMap} from ""rxjs/operators""; import {MatDialog} from ""@angular/material/dialog""; import {NewPolicyDialogComponent} from ""../new-policy-dialog/new-policy-dialog.component""; import {NotificationService} from ""../../services/notification.service""; import {ConfirmationDialogComponent, ConfirmDialogModel} from ""../confirmation-dialog/confirmation-dialog.component""; @Component({ selector: 'app-policy-view', templateUrl: './policy-view.component.html', styleUrls: ['./policy-view.component.scss'] }) export class PolicyViewComponent implements OnInit { filteredPolicies$: Observable = of([]); searchText: string = ''; private fetch$ = new BehaviorSubject(null); private readonly errorOrUpdateSubscriber: Observer; constructor(private policyService: PolicyService, private notificationService: NotificationService, private readonly dialog: MatDialog) { this.errorOrUpdateSubscriber = { next: x => this.fetch$.next(null), error: err => this.showError(err, ""An error occurred.""), complete: () => { this.notificationService.showInfo(""Successfully completed"") }, } } ngOnInit(): void { this.filteredPolicies$ = this.fetch$.pipe( switchMap(() => { const policyDefinitions = this.policyService.queryAllPolicies(); return !!this.searchText ? policyDefinitions.pipe(map(policies => policies.filter(policy => this.isFiltered(policy, this.searchText)))) : policyDefinitions; })); } onSearch() { this.fetch$.next(null); } onCreate() { const dialogRef = this.dialog.open(NewPolicyDialogComponent); dialogRef.afterClosed().pipe(first()).subscribe({ next: ( [MASK] : PolicyDefinitionResponseDto) => { if ( [MASK] ) { this.policyService.createPolicy( [MASK] ).subscribe( { next: (response: IdResponseDto) => this.errorOrUpdateSubscriber.next(response), error: (error: Error) => this.showError(error, ""An error occurred while creating the policy."") } ); } } }); } /** * simple full-text search - serialize to JSON and see if ""searchText"" * is contained */ private isFiltered(policy: PolicyDefinitionResponseDto, searchText: string) { return JSON.stringify(policy).includes(searchText); } delete(policy: PolicyDefinitionResponseDto) { let policyId = policy['@id']!; const dialogData = ConfirmDialogModel.forDelete(""policy"", policyId); const ref = this.dialog.open(ConfirmationDialogComponent, {maxWidth: '20%', data: dialogData}); ref.afterClosed().subscribe({ next: (res: any) => { if (res) { this.policyService.deletePolicy(policyId).subscribe( { next: (response: IdResponseDto) => this.errorOrUpdateSubscriber.next(response), error: (error: Error) => this.showError(error, ""An error occurred while deleting the policy."") } ); } } }); } private showError(error: Error, errorMessage: string) { console.error(error); this.notificationService.showError(errorMessage); } } ",result 135,"import { IncomingMessage, ServerResponse } from 'http'; import { getAllItems, getItemById, createItem, updateItem, deleteItem } from '../controllers/shoppingList.controller'; export const routes = (req: IncomingMessage, [MASK] : ServerResponse): void => { const url = new URL(req.url || '', `http://${req.headers.host}`); const path = url.pathname; const method = req.method; if (path === '/items' && method === 'GET') { getAllItems(req, [MASK] ); } else if (path.match(/^\/items\/\d+$/) && method === 'GET') { const id = path.split('/')[2]; req.params = { id }; getItemById(req, [MASK] ); } else if (path === '/items' && method === 'POST') { createItem(req, [MASK] ); } else if (path.match(/^\/items\/\d+$/) && method === 'PUT') { const id = path.split('/')[2]; req.params = { id }; updateItem(req, [MASK] ); } else if (path.match(/^\/items\/\d+$/) && method === 'DELETE') { const id = path.split('/')[2]; req.params = { id }; deleteItem(req, [MASK] ); } else { [MASK] .writeHead(404, { 'Content-Type': 'application/json' }); [MASK] .end(JSON.stringify({ message: 'Ruta no encontrada' })); } }; // Extender IncomingMessage para incluir params declare module 'http' { interface IncomingMessage { params?: { [key: string]: string }; } } ",res 136,"import React from 'react' import { renderToNodeStream } from 'react-dom/server' import intoStream from 'into-stream' import multistream from 'multistream' import { PassThrough } from 'stream' export interface RenderContext { afterContent?: intoStream.Input beforeContent?: intoStream.Input bodyProps?: intoStream.Input description?: intoStream.Input head?: intoStream.Input htmlProps?: intoStream.Input title?: intoStream.Input } export const render = ({ content, context = {} }: { content?: React.ElementType context?: RenderContext } = {}) => { const [MASK] = new PassThrough() const pieces: multistream.Streams = [ intoStream(` `) ) if (context.title) { pieces.push( intoStream(''), intoStream(context.title), intoStream('') ) } if (context.description) { pieces.push( intoStream('') ) } pieces.push( intoStream( '' ) ) if (context.head) { pieces.push(intoStream(context.head)) } pieces.push( intoStream(` `) ) if (context.beforeContent) { pieces.push(intoStream(context.beforeContent)) } if (content) { pieces.push(renderToNodeStream(React.createElement(content))) } if (context.afterContent) { pieces.push(intoStream(context.afterContent)) } pieces.push( intoStream(` `) ) multistream(pieces).pipe( [MASK] ) return [MASK] } ",passThrough 137,"import { defineEventHandler, readBody, setResponseStatus } from 'h3' import { useRuntimeConfig } from '#imports' import { signIn } from '~/services/auth/supabase_auth' export default defineEventHandler(async (event) => { if (event.method !== 'POST') { setResponseStatus(event, 405) return } const [MASK] = useRuntimeConfig() if ( [MASK] .ENABLE_AUTH !== 'true') { setResponseStatus(event, 400) return { msg: 'Auth disabled' } } const { email, password } = await readBody(event) try { const data = await signIn(email, password) if (data?.user) { return { msg: 'Logged in!' } } setResponseStatus(event, 400) return { msg: 'Invalid creds' } } catch (err: any) { setResponseStatus(event, 500) return { msg: `${err}` } } }) ",cfg 138,"import { APIDashboard, APIProfilo, Profilo } from ""../types/Types.js""; import { ArgoClient } from ""./ArgoClient""; export class Argo { private client: ArgoClient; private profiloSelezionato: { profilo: APIProfilo; token: string; } | undefined; constructor(client: ArgoClient) { this.client = client; } /** * Ottieni i dati scolastici (compiti, voti, agenda...), potrebbe diventare una richiesta molto pesante (a livello di body di risposta) nel corso dell'anno scolastico */ public async getDashboard(): Promise { if (!this.client.dataAggiornaData) this.client.dataAggiornaData = this.client.utilities.formattaDataUltimoAggiornamento(new Date(`${new Date().getFullYear()}-09-01:00:00:00.000Z`)); if (!this.profiloSelezionato) throw new Error(""Profilo non selezionato, si prega di selezionarne uno con il metodo client.argo.selectUser()""); return (await this.client.sendArgoRequest(""/dashboard/dashboard"", ""POST"", true, JSON.stringify({ dataultimoaggiornamento: this.client.dataAggiornaData, opzioni: ""{\""ORARIO_SCOLASTICO\"":true,\""PAGELLINO_ONLINE\"":true,\""VALUTAZIONI_PERIODICHE\"":true,\""VALUTAZIONI_GIORNALIERE\"":true,\""COMPITI_ASSEGNATI\"":true,\""IGNORA_OPZIONE_VOTI_DOCENTI\"":false,\""DOCENTI_CLASSE\"":true,\""RENDI_VISIBILE_CURRICULUM\"":true,\""RICHIESTA_CERTIFICATI\"":false,\""MODIFICA_RECAPITI\"":true,\""CONSIGLIO_DI_ISTITUTO\"":true,\""NOTE_DISCIPLINARI\"":true,\""GIUDIZI\"":true,\""GIUSTIFICAZIONI_ASSENZE\"":true,\""TABELLONE_PERIODI_INTERMEDI\"":true,\""PAGELLE_ONLINE\"":true,\""ASSENZE_PER_DATA\"":true,\""ARGOMENTI_LEZIONE\"":true,\""NASCONDI_DIDUP_FAMIGLIA\"":true,\""ALILITA_BSMART_FAMIGLIA\"":false,\""VOTI_GIUDIZI\"":true,\""ABILITA_AUTOCERTIFICAZIONE_FAM\"":false,\""MOSTRA_MEDIA_GENERALE\"":true,\""TABELLONE_SCRUTINIO_FINALE\"":true,\""PIN_VOTI\"":true,\""DISABILITA_ACCESSO_FAMIGLIA\"":true,\""TASSE_SCOLASTICHE\"":true,\""PROMEMORIA_CLASSE\"":true,\""PRENOTAZIONE_ALUNNI\"":true,\""CONSIGLIO_DI_CLASSE\"":true}"" }), { ""x-auth-token"": this.profiloSelezionato?.token })).response.data as APIDashboard; } /** * Seleziona l'utente salvando il mobile token di esso (obbligatorio per richieste come getDashboard() * @param nomeCognome Nome e cognome dell'utente da selezionare * @example ```js * client.argo.selectUser(""Antonio"", ""Cavaliere""); * ``` */ public async selectUser(nome: string, cognome: string): Promise<{ profilo: APIProfilo; token: string; }> { const profili = await this.getProfili(); const profilo = profili.find(profilo => profilo.profilo.alunno.nominativo.toLowerCase() === `${cognome.toLowerCase()} ${nome.toLowerCase()}`); if (!profilo) throw new Error(""Profilo non trovato""); this.profiloSelezionato = profilo; return profilo; } /** * */ public async getProfili(): Promise<{ profilo: APIProfilo; token: string; }[]> { const res = await this.client.sendArgoRequest(""/login"", ""POST"", true, JSON.stringify({ ""lista-opzioni-notifiche"": ""{}"", ""lista-x-auth-token"": ""[]"", clientID: ""d8MtQX5fR3yS9I7k-5OXUs:APA91bErrU-H7wGQ8yLastE_xS2JHDrVrfReRY2mnWQ9aVd-ohWYDTSLVRrKUsO2-25mBN1aduh5sPnZjFstg0Ixqiuoh5wCC38BB6NEveqWI_d6ZpM5DN3nvyVS8vDtwLS9caWeCmEK"" })) let profili: { profilo: APIProfilo; token: string; }[] = [] for (let profile of res.response.data) { const profileReq = await this.client.sendArgoRequest(""/profilo"", ""GET"", true, undefined, { ""x-auth-token"": profile.token }) const profileData = profileReq.response.data as APIProfilo; profili.push({ profilo: profileData, token: profile.token }); } return profili; } /** * Aggiorna la data di aggiornamento dei dati, necessario per alcune richieste come `what` e `/dashboard/dashboard` * @param data Data da cui aggiornare i dati */ public async aggiornaData(data: Date): Promise { const [MASK] = await this.client.sendArgoRequest(""/dashboard/aggiornadata"", ""POST"", false, JSON.stringify({ dataultimoaggiornamento: this.client.utilities.formattaDataUltimoAggiornamento(data) })) if ( [MASK] .status === 200) { this.client.dataAggiornaData = this.client.utilities.formattaDataUltimoAggiornamento(data); return true; } return false; } }",req 139,"import { addToSeen, AlternateModeDiagnostics, append, arrayFrom, ArrayLiteralExpression, arrayToMap, assign, BuildOptions, cast, changeExtension, CharacterCodes, combinePaths, CommandLineOption, CommandLineOptionOfCustomType, CommandLineOptionOfListType, CompilerOptions, CompilerOptionsValue, computedOptions, ConfigFileSpecs, containsPath, convertToRelativePath, createCompilerDiagnostic, createDiagnosticForNodeInSourceFile, createGetCanonicalFileName, Debug, Diagnostic, DiagnosticArguments, DiagnosticMessage, Diagnostics, DidYouMeanOptionsDiagnostics, directorySeparator, emptyArray, endsWith, ensureTrailingDirectorySeparator, every, Expression, extend, Extension, FileExtensionInfo, fileExtensionIs, fileExtensionIsOneOf, filter, filterMutate, find, findIndex, flatten, forEach, forEachEntry, forEachTsConfigPropArray, getBaseFileName, getDirectoryPath, getFileMatcherPatterns, getLocaleSpecificMessage, getNormalizedAbsolutePath, getOwnKeys, getRegexFromPattern, getRegularExpressionForWildcard, getRegularExpressionsForWildcards, getRelativePathFromFile, getSpellingSuggestion, getSupportedExtensions, getSupportedExtensionsWithJsonIfResolveJsonModule, getTextOfPropertyName, getTsConfigPropArrayElementValue, hasExtension, hasProperty, ImportsNotUsedAsValues, isArray, isArrayLiteralExpression, isComputedNonLiteralName, isImplicitGlob, isObjectLiteralExpression, isRootedDiskPath, isString, isStringDoubleQuoted, isStringLiteral, JsonSourceFile, JsxEmit, length, map, mapDefined, mapIterator, MapLike, ModuleDetectionKind, ModuleKind, ModuleResolutionKind, NewLineKind, Node, NodeArray, nodeNextJsonConfigResolver, normalizePath, normalizeSlashes, NumericLiteral, ObjectLiteralExpression, ParseConfigHost, ParsedCommandLine, parseJsonText, Path, PollingWatchKind, PrefixUnaryExpression, ProjectReference, PropertyAssignment, PropertyName, removeTrailingDirectorySeparator, returnTrue, ScriptTarget, some, startsWith, StringLiteral, SyntaxKind, sys, toFileNameLowerCase, toPath, tracing, TsConfigOnlyOption, TsConfigSourceFile, TypeAcquisition, unescapeLeadingUnderscores, WatchDirectoryFlags, WatchDirectoryKind, WatchFileKind, WatchOptions, } from ""./_namespaces/ts.js""; const compileOnSaveCommandLineOption: CommandLineOption = { name: ""compileOnSave"", type: ""boolean"", defaultValueDescription: false, }; const jsxOptionMap = new Map(Object.entries({ ""preserve"": JsxEmit.Preserve, ""react-native"": JsxEmit.ReactNative, ""react-jsx"": JsxEmit.ReactJSX, ""react-jsxdev"": JsxEmit.ReactJSXDev, ""react"": JsxEmit.React, })); /** @internal */ export const inverseJsxOptionMap: Map = new Map(mapIterator(jsxOptionMap.entries(), ([key, value]: [string, JsxEmit]) => ["""" + value, key] as const)); // NOTE: The order here is important to default lib ordering as entries will have the same // order in the generated program (see `getDefaultLibPriority` in program.ts). This // order also affects overload resolution when a type declared in one lib is // augmented in another lib. // NOTE: We must reevaluate the target for upcoming features when each successive TC39 edition is ratified in // June of each year. This includes changes to `LanguageFeatureMinimumTarget`, `ScriptTarget`, // `ScriptTargetFeatures` transformers/esnext.ts, compiler/commandLineParser.ts, // compiler/utilitiesPublic.ts, and the contents of each lib/esnext.*.d.ts file. const libEntries: [string, string][] = [ // JavaScript only [""es5"", ""lib.es5.d.ts""], [""es6"", ""lib.es2015.d.ts""], [""es2015"", ""lib.es2015.d.ts""], [""es7"", ""lib.es2016.d.ts""], [""es2016"", ""lib.es2016.d.ts""], [""es2017"", ""lib.es2017.d.ts""], [""es2018"", ""lib.es2018.d.ts""], [""es2019"", ""lib.es2019.d.ts""], [""es2020"", ""lib.es2020.d.ts""], [""es2021"", ""lib.es2021.d.ts""], [""es2022"", ""lib.es2022.d.ts""], [""es2023"", ""lib.es2023.d.ts""], [""es2024"", ""lib.es2024.d.ts""], [""esnext"", ""lib.esnext.d.ts""], // Host only [""dom"", ""lib.dom.d.ts""], [""dom.iterable"", ""lib.dom.iterable.d.ts""], [""dom.asynciterable"", ""lib.dom.asynciterable.d.ts""], [""webworker"", ""lib.webworker.d.ts""], [""webworker.importscripts"", ""lib.webworker.importscripts.d.ts""], [""webworker.iterable"", ""lib.webworker.iterable.d.ts""], [""webworker.asynciterable"", ""lib.webworker.asynciterable.d.ts""], [""scripthost"", ""lib.scripthost.d.ts""], // ES2015 Or ESNext By-feature options [""es2015.core"", ""lib.es2015.core.d.ts""], [""es2015.collection"", ""lib.es2015.collection.d.ts""], [""es2015.generator"", ""lib.es2015.generator.d.ts""], [""es2015.iterable"", ""lib.es2015.iterable.d.ts""], [""es2015.promise"", ""lib.es2015.promise.d.ts""], [""es2015.proxy"", ""lib.es2015.proxy.d.ts""], [""es2015.reflect"", ""lib.es2015.reflect.d.ts""], [""es2015.symbol"", ""lib.es2015.symbol.d.ts""], [""es2015.symbol.wellknown"", ""lib.es2015.symbol.wellknown.d.ts""], [""es2016.array.include"", ""lib.es2016.array.include.d.ts""], [""es2016.intl"", ""lib.es2016.intl.d.ts""], [""es2017.arraybuffer"", ""lib.es2017.arraybuffer.d.ts""], [""es2017.date"", ""lib.es2017.date.d.ts""], [""es2017.object"", ""lib.es2017.object.d.ts""], [""es2017.sharedmemory"", ""lib.es2017.sharedmemory.d.ts""], [""es2017.string"", ""lib.es2017.string.d.ts""], [""es2017.intl"", ""lib.es2017.intl.d.ts""], [""es2017.typedarrays"", ""lib.es2017.typedarrays.d.ts""], [""es2018.asyncgenerator"", ""lib.es2018.asyncgenerator.d.ts""], [""es2018.asynciterable"", ""lib.es2018.asynciterable.d.ts""], [""es2018.intl"", ""lib.es2018.intl.d.ts""], [""es2018.promise"", ""lib.es2018.promise.d.ts""], [""es2018.regexp"", ""lib.es2018.regexp.d.ts""], [""es2019.array"", ""lib.es2019.array.d.ts""], [""es2019.object"", ""lib.es2019.object.d.ts""], [""es2019.string"", ""lib.es2019.string.d.ts""], [""es2019.symbol"", ""lib.es2019.symbol.d.ts""], [""es2019.intl"", ""lib.es2019.intl.d.ts""], [""es2020.bigint"", ""lib.es2020.bigint.d.ts""], [""es2020.date"", ""lib.es2020.date.d.ts""], [""es2020.promise"", ""lib.es2020.promise.d.ts""], [""es2020.sharedmemory"", ""lib.es2020.sharedmemory.d.ts""], [""es2020.string"", ""lib.es2020.string.d.ts""], [""es2020.symbol.wellknown"", ""lib.es2020.symbol.wellknown.d.ts""], [""es2020.intl"", ""lib.es2020.intl.d.ts""], [""es2020.number"", ""lib.es2020.number.d.ts""], [""es2021.promise"", ""lib.es2021.promise.d.ts""], [""es2021.string"", ""lib.es2021.string.d.ts""], [""es2021.weakref"", ""lib.es2021.weakref.d.ts""], [""es2021.intl"", ""lib.es2021.intl.d.ts""], [""es2022.array"", ""lib.es2022.array.d.ts""], [""es2022.error"", ""lib.es2022.error.d.ts""], [""es2022.intl"", ""lib.es2022.intl.d.ts""], [""es2022.object"", ""lib.es2022.object.d.ts""], [""es2022.string"", ""lib.es2022.string.d.ts""], [""es2022.regexp"", ""lib.es2022.regexp.d.ts""], [""es2023.array"", ""lib.es2023.array.d.ts""], [""es2023.collection"", ""lib.es2023.collection.d.ts""], [""es2023.intl"", ""lib.es2023.intl.d.ts""], [""es2024.arraybuffer"", ""lib.es2024.arraybuffer.d.ts""], [""es2024.collection"", ""lib.es2024.collection.d.ts""], [""es2024.object"", ""lib.es2024.object.d.ts""], [""es2024.promise"", ""lib.es2024.promise.d.ts""], [""es2024.regexp"", ""lib.es2024.regexp.d.ts""], [""es2024.sharedmemory"", ""lib.es2024.sharedmemory.d.ts""], [""es2024.string"", ""lib.es2024.string.d.ts""], [""esnext.array"", ""lib.es2023.array.d.ts""], [""esnext.collection"", ""lib.esnext.collection.d.ts""], [""esnext.symbol"", ""lib.es2019.symbol.d.ts""], [""esnext.asynciterable"", ""lib.es2018.asynciterable.d.ts""], [""esnext.intl"", ""lib.esnext.intl.d.ts""], [""esnext.disposable"", ""lib.esnext.disposable.d.ts""], [""esnext.bigint"", ""lib.es2020.bigint.d.ts""], [""esnext.string"", ""lib.es2022.string.d.ts""], [""esnext.promise"", ""lib.es2024.promise.d.ts""], [""esnext.weakref"", ""lib.es2021.weakref.d.ts""], [""esnext.decorators"", ""lib.esnext.decorators.d.ts""], [""esnext.object"", ""lib.es2024.object.d.ts""], [""esnext.array"", ""lib.esnext.array.d.ts""], [""esnext.regexp"", ""lib.es2024.regexp.d.ts""], [""esnext.string"", ""lib.es2024.string.d.ts""], [""esnext.iterator"", ""lib.esnext.iterator.d.ts""], [""esnext.promise"", ""lib.esnext.promise.d.ts""], [""esnext.float16"", ""lib.esnext.float16.d.ts""], [""esnext.error"", ""lib.esnext.error.d.ts""], [""esnext.sharedmemory"", ""lib.esnext.sharedmemory.d.ts""], [""decorators"", ""lib.decorators.d.ts""], [""decorators.legacy"", ""lib.decorators.legacy.d.ts""], ]; /** * An array of supported ""lib"" reference file names used to determine the order for inclusion * when referenced, as well as for spelling suggestions. This ensures the correct ordering for * overload resolution when a type declared in one lib is extended by another. * * @internal */ export const libs: string[] = libEntries.map(entry => entry[0]); /** * A map of lib names to lib files. This map is used both for parsing the ""lib"" command line * option as well as for resolving lib reference directives. * * @internal */ export const libMap: Map = new Map(libEntries); // Watch related options // Do not delete this without updating the website's tsconfig generation. /** @internal */ export const optionsForWatch: CommandLineOption[] = [ { name: ""watchFile"", type: new Map(Object.entries({ fixedpollinginterval: WatchFileKind.FixedPollingInterval, prioritypollinginterval: WatchFileKind.PriorityPollingInterval, dynamicprioritypolling: WatchFileKind.DynamicPriorityPolling, fixedchunksizepolling: WatchFileKind.FixedChunkSizePolling, usefsevents: WatchFileKind.UseFsEvents, usefseventsonparentdirectory: WatchFileKind.UseFsEventsOnParentDirectory, })), category: Diagnostics.Watch_and_Build_Modes, description: Diagnostics.Specify_how_the_TypeScript_watch_mode_works, defaultValueDescription: WatchFileKind.UseFsEvents, }, { name: ""watchDirectory"", type: new Map(Object.entries({ usefsevents: WatchDirectoryKind.UseFsEvents, fixedpollinginterval: WatchDirectoryKind.FixedPollingInterval, dynamicprioritypolling: WatchDirectoryKind.DynamicPriorityPolling, fixedchunksizepolling: WatchDirectoryKind.FixedChunkSizePolling, })), category: Diagnostics.Watch_and_Build_Modes, description: Diagnostics.Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality, defaultValueDescription: WatchDirectoryKind.UseFsEvents, }, { name: ""fallbackPolling"", type: new Map(Object.entries({ fixedinterval: PollingWatchKind.FixedInterval, priorityinterval: PollingWatchKind.PriorityInterval, dynamicpriority: PollingWatchKind.DynamicPriority, fixedchunksize: PollingWatchKind.FixedChunkSize, })), category: Diagnostics.Watch_and_Build_Modes, description: Diagnostics.Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers, defaultValueDescription: PollingWatchKind.PriorityInterval, }, { name: ""synchronousWatchDirectory"", type: ""boolean"", category: Diagnostics.Watch_and_Build_Modes, description: Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively, defaultValueDescription: false, }, { name: ""excludeDirectories"", type: ""list"", element: { name: ""excludeDirectory"", type: ""string"", isFilePath: true, extraValidation: specToDiagnostic, }, allowConfigDirTemplateSubstitution: true, category: Diagnostics.Watch_and_Build_Modes, description: Diagnostics.Remove_a_list_of_directories_from_the_watch_process, }, { name: ""excludeFiles"", type: ""list"", element: { name: ""excludeFile"", type: ""string"", isFilePath: true, extraValidation: specToDiagnostic, }, allowConfigDirTemplateSubstitution: true, category: Diagnostics.Watch_and_Build_Modes, description: Diagnostics.Remove_a_list_of_files_from_the_watch_mode_s_processing, }, ]; /** @internal */ export const commonOptionsWithBuild: CommandLineOption[] = [ { name: ""help"", shortName: ""h"", type: ""boolean"", showInSimplifiedHelpView: true, isCommandLineOnly: true, category: Diagnostics.Command_line_Options, description: Diagnostics.Print_this_message, defaultValueDescription: false, }, { name: ""help"", shortName: ""?"", type: ""boolean"", isCommandLineOnly: true, category: Diagnostics.Command_line_Options, defaultValueDescription: false, }, { name: ""watch"", shortName: ""w"", type: ""boolean"", showInSimplifiedHelpView: true, isCommandLineOnly: true, category: Diagnostics.Command_line_Options, description: Diagnostics.Watch_input_files, defaultValueDescription: false, }, { name: ""preserveWatchOutput"", type: ""boolean"", showInSimplifiedHelpView: false, category: Diagnostics.Output_Formatting, description: Diagnostics.Disable_wiping_the_console_in_watch_mode, defaultValueDescription: false, }, { name: ""listFiles"", type: ""boolean"", category: Diagnostics.Compiler_Diagnostics, description: Diagnostics.Print_all_of_the_files_read_during_the_compilation, defaultValueDescription: false, }, { name: ""explainFiles"", type: ""boolean"", category: Diagnostics.Compiler_Diagnostics, description: Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included, defaultValueDescription: false, }, { name: ""listEmittedFiles"", type: ""boolean"", category: Diagnostics.Compiler_Diagnostics, description: Diagnostics.Print_the_names_of_emitted_files_after_a_compilation, defaultValueDescription: false, }, { name: ""pretty"", type: ""boolean"", showInSimplifiedHelpView: true, category: Diagnostics.Output_Formatting, description: Diagnostics.Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read, defaultValueDescription: true, }, { name: ""traceResolution"", type: ""boolean"", category: Diagnostics.Compiler_Diagnostics, description: Diagnostics.Log_paths_used_during_the_moduleResolution_process, defaultValueDescription: false, }, { name: ""diagnostics"", type: ""boolean"", category: Diagnostics.Compiler_Diagnostics, description: Diagnostics.Output_compiler_performance_information_after_building, defaultValueDescription: false, }, { name: ""extendedDiagnostics"", type: ""boolean"", category: Diagnostics.Compiler_Diagnostics, description: Diagnostics.Output_more_detailed_compiler_performance_information_after_building, defaultValueDescription: false, }, { name: ""generateCpuProfile"", type: ""string"", isFilePath: true, paramType: Diagnostics.FILE_OR_DIRECTORY, category: Diagnostics.Compiler_Diagnostics, description: Diagnostics.Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging, defaultValueDescription: ""profile.cpuprofile"", }, { name: ""generateTrace"", type: ""string"", isFilePath: true, paramType: Diagnostics.DIRECTORY, category: Diagnostics.Compiler_Diagnostics, description: Diagnostics.Generates_an_event_trace_and_a_list_of_types, }, { name: ""incremental"", shortName: ""i"", type: ""boolean"", category: Diagnostics.Projects, description: Diagnostics.Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects, transpileOptionValue: undefined, defaultValueDescription: Diagnostics.false_unless_composite_is_set, }, { name: ""declaration"", shortName: ""d"", type: ""boolean"", // Not setting affectsEmit because we calculate this flag might not affect full emit affectsBuildInfo: true, showInSimplifiedHelpView: true, category: Diagnostics.Emit, transpileOptionValue: undefined, description: Diagnostics.Generate_d_ts_files_from_TypeScript_and_JavaScript_files_in_your_project, defaultValueDescription: Diagnostics.false_unless_composite_is_set, }, { name: ""declarationMap"", type: ""boolean"", // Not setting affectsEmit because we calculate this flag might not affect full emit affectsBuildInfo: true, showInSimplifiedHelpView: true, category: Diagnostics.Emit, defaultValueDescription: false, description: Diagnostics.Create_sourcemaps_for_d_ts_files, }, { name: ""emitDeclarationOnly"", type: ""boolean"", // Not setting affectsEmit because we calculate this flag might not affect full emit affectsBuildInfo: true, showInSimplifiedHelpView: true, category: Diagnostics.Emit, description: Diagnostics.Only_output_d_ts_files_and_not_JavaScript_files, transpileOptionValue: undefined, defaultValueDescription: false, }, { name: ""sourceMap"", type: ""boolean"", // Not setting affectsEmit because we calculate this flag might not affect full emit affectsBuildInfo: true, showInSimplifiedHelpView: true, category: Diagnostics.Emit, defaultValueDescription: false, description: Diagnostics.Create_source_map_files_for_emitted_JavaScript_files, }, { name: ""inlineSourceMap"", type: ""boolean"", // Not setting affectsEmit because we calculate this flag might not affect full emit affectsBuildInfo: true, category: Diagnostics.Emit, description: Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript, defaultValueDescription: false, }, { name: ""noCheck"", type: ""boolean"", showInSimplifiedHelpView: false, category: Diagnostics.Compiler_Diagnostics, description: Diagnostics.Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported, transpileOptionValue: true, defaultValueDescription: false, // Not setting affectsSemanticDiagnostics or affectsBuildInfo because we dont want all diagnostics to go away, its handled in builder }, { name: ""noEmit"", type: ""boolean"", showInSimplifiedHelpView: true, category: Diagnostics.Emit, description: Diagnostics.Disable_emitting_files_from_a_compilation, transpileOptionValue: undefined, defaultValueDescription: false, }, { name: ""assumeChangesOnlyAffectDirectDependencies"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsEmit: true, affectsBuildInfo: true, category: Diagnostics.Watch_and_Build_Modes, description: Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, defaultValueDescription: false, }, { name: ""locale"", type: ""string"", category: Diagnostics.Command_line_Options, isCommandLineOnly: true, description: Diagnostics.Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit, defaultValueDescription: Diagnostics.Platform_specific, }, ]; /** @internal */ export const targetOptionDeclaration: CommandLineOptionOfCustomType = { name: ""target"", shortName: ""t"", type: new Map(Object.entries({ es3: ScriptTarget.ES3, es5: ScriptTarget.ES5, es6: ScriptTarget.ES2015, es2015: ScriptTarget.ES2015, es2016: ScriptTarget.ES2016, es2017: ScriptTarget.ES2017, es2018: ScriptTarget.ES2018, es2019: ScriptTarget.ES2019, es2020: ScriptTarget.ES2020, es2021: ScriptTarget.ES2021, es2022: ScriptTarget.ES2022, es2023: ScriptTarget.ES2023, es2024: ScriptTarget.ES2024, esnext: ScriptTarget.ESNext, })), affectsSourceFile: true, affectsModuleResolution: true, affectsEmit: true, affectsBuildInfo: true, deprecatedKeys: new Set([""es3""]), paramType: Diagnostics.VERSION, showInSimplifiedHelpView: true, category: Diagnostics.Language_and_Environment, description: Diagnostics.Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations, defaultValueDescription: ScriptTarget.ES5, }; /** @internal */ export const moduleOptionDeclaration: CommandLineOptionOfCustomType = { name: ""module"", shortName: ""m"", type: new Map(Object.entries({ none: ModuleKind.None, commonjs: ModuleKind.CommonJS, amd: ModuleKind.AMD, system: ModuleKind.System, umd: ModuleKind.UMD, es6: ModuleKind.ES2015, es2015: ModuleKind.ES2015, es2020: ModuleKind.ES2020, es2022: ModuleKind.ES2022, esnext: ModuleKind.ESNext, node16: ModuleKind.Node16, node18: ModuleKind.Node18, node20: ModuleKind.Node20, nodenext: ModuleKind.NodeNext, preserve: ModuleKind.Preserve, })), affectsSourceFile: true, affectsModuleResolution: true, affectsEmit: true, affectsBuildInfo: true, paramType: Diagnostics.KIND, showInSimplifiedHelpView: true, category: Diagnostics.Modules, description: Diagnostics.Specify_what_module_code_is_generated, defaultValueDescription: undefined, }; const commandOptionsWithoutBuild: CommandLineOption[] = [ // CommandLine only options { name: ""all"", type: ""boolean"", showInSimplifiedHelpView: true, category: Diagnostics.Command_line_Options, description: Diagnostics.Show_all_compiler_options, defaultValueDescription: false, }, { name: ""version"", shortName: ""v"", type: ""boolean"", showInSimplifiedHelpView: true, category: Diagnostics.Command_line_Options, description: Diagnostics.Print_the_compiler_s_version, defaultValueDescription: false, }, { name: ""init"", type: ""boolean"", showInSimplifiedHelpView: true, category: Diagnostics.Command_line_Options, description: Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, defaultValueDescription: false, }, { name: ""project"", shortName: ""p"", type: ""string"", isFilePath: true, showInSimplifiedHelpView: true, category: Diagnostics.Command_line_Options, paramType: Diagnostics.FILE_OR_DIRECTORY, description: Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json, }, { name: ""showConfig"", type: ""boolean"", showInSimplifiedHelpView: true, category: Diagnostics.Command_line_Options, isCommandLineOnly: true, description: Diagnostics.Print_the_final_configuration_instead_of_building, defaultValueDescription: false, }, { name: ""listFilesOnly"", type: ""boolean"", category: Diagnostics.Command_line_Options, isCommandLineOnly: true, description: Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, defaultValueDescription: false, }, // Basic targetOptionDeclaration, moduleOptionDeclaration, { name: ""lib"", type: ""list"", element: { name: ""lib"", type: libMap, defaultValueDescription: undefined, }, affectsProgramStructure: true, showInSimplifiedHelpView: true, category: Diagnostics.Language_and_Environment, description: Diagnostics.Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment, transpileOptionValue: undefined, }, { name: ""allowJs"", type: ""boolean"", allowJsFlag: true, affectsBuildInfo: true, showInSimplifiedHelpView: true, category: Diagnostics.JavaScript_Support, description: Diagnostics.Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these_files, defaultValueDescription: false, }, { name: ""checkJs"", type: ""boolean"", affectsModuleResolution: true, affectsSemanticDiagnostics: true, affectsBuildInfo: true, showInSimplifiedHelpView: true, category: Diagnostics.JavaScript_Support, description: Diagnostics.Enable_error_reporting_in_type_checked_JavaScript_files, defaultValueDescription: false, }, { name: ""jsx"", type: jsxOptionMap, affectsSourceFile: true, affectsEmit: true, affectsBuildInfo: true, affectsModuleResolution: true, // The checker emits an error when it sees JSX but this option is not set in compilerOptions. // This is effectively a semantic error, so mark this option as affecting semantic diagnostics // so we know to refresh errors when this option is changed. affectsSemanticDiagnostics: true, paramType: Diagnostics.KIND, showInSimplifiedHelpView: true, category: Diagnostics.Language_and_Environment, description: Diagnostics.Specify_what_JSX_code_is_generated, defaultValueDescription: undefined, }, { name: ""outFile"", type: ""string"", affectsEmit: true, affectsBuildInfo: true, affectsDeclarationPath: true, isFilePath: true, paramType: Diagnostics.FILE, showInSimplifiedHelpView: true, category: Diagnostics.Emit, description: Diagnostics.Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designates_a_file_that_bundles_all_d_ts_output, transpileOptionValue: undefined, }, { name: ""outDir"", type: ""string"", affectsEmit: true, affectsBuildInfo: true, affectsDeclarationPath: true, isFilePath: true, paramType: Diagnostics.DIRECTORY, showInSimplifiedHelpView: true, category: Diagnostics.Emit, description: Diagnostics.Specify_an_output_folder_for_all_emitted_files, }, { name: ""rootDir"", type: ""string"", affectsEmit: true, affectsBuildInfo: true, affectsDeclarationPath: true, isFilePath: true, paramType: Diagnostics.LOCATION, category: Diagnostics.Modules, description: Diagnostics.Specify_the_root_folder_within_your_source_files, defaultValueDescription: Diagnostics.Computed_from_the_list_of_input_files, }, { name: ""composite"", type: ""boolean"", // Not setting affectsEmit because we calculate this flag might not affect full emit affectsBuildInfo: true, isTSConfigOnly: true, category: Diagnostics.Projects, transpileOptionValue: undefined, defaultValueDescription: false, description: Diagnostics.Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references, }, { name: ""tsBuildInfoFile"", type: ""string"", affectsEmit: true, affectsBuildInfo: true, isFilePath: true, paramType: Diagnostics.FILE, category: Diagnostics.Projects, transpileOptionValue: undefined, defaultValueDescription: "".tsbuildinfo"", description: Diagnostics.Specify_the_path_to_tsbuildinfo_incremental_compilation_file, }, { name: ""removeComments"", type: ""boolean"", affectsEmit: true, affectsBuildInfo: true, showInSimplifiedHelpView: true, category: Diagnostics.Emit, defaultValueDescription: false, description: Diagnostics.Disable_emitting_comments, }, { name: ""importHelpers"", type: ""boolean"", affectsEmit: true, affectsBuildInfo: true, affectsSourceFile: true, category: Diagnostics.Emit, description: Diagnostics.Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file, defaultValueDescription: false, }, { name: ""importsNotUsedAsValues"", type: new Map(Object.entries({ remove: ImportsNotUsedAsValues.Remove, preserve: ImportsNotUsedAsValues.Preserve, error: ImportsNotUsedAsValues.Error, })), affectsEmit: true, affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Backwards_Compatibility, description: Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types, defaultValueDescription: ImportsNotUsedAsValues.Remove, }, { name: ""downlevelIteration"", type: ""boolean"", affectsEmit: true, affectsBuildInfo: true, category: Diagnostics.Emit, description: Diagnostics.Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration, defaultValueDescription: false, }, { name: ""isolatedModules"", type: ""boolean"", category: Diagnostics.Interop_Constraints, description: Diagnostics.Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports, transpileOptionValue: true, defaultValueDescription: false, }, { name: ""verbatimModuleSyntax"", type: ""boolean"", affectsEmit: true, affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Interop_Constraints, description: Diagnostics.Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_in_the_output_file_s_format_based_on_the_module_setting, defaultValueDescription: false, }, { name: ""isolatedDeclarations"", type: ""boolean"", category: Diagnostics.Interop_Constraints, description: Diagnostics.Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files, defaultValueDescription: false, affectsBuildInfo: true, affectsSemanticDiagnostics: true, }, { name: ""erasableSyntaxOnly"", type: ""boolean"", category: Diagnostics.Interop_Constraints, description: Diagnostics.Do_not_allow_runtime_constructs_that_are_not_part_of_ECMAScript, defaultValueDescription: false, affectsBuildInfo: true, affectsSemanticDiagnostics: true, }, { name: ""libReplacement"", type: ""boolean"", affectsProgramStructure: true, category: Diagnostics.Language_and_Environment, description: Diagnostics.Enable_lib_replacement, defaultValueDescription: true, }, // Strict Type Checks { name: ""strict"", type: ""boolean"", // Though this affects semantic diagnostics, affectsSemanticDiagnostics is not set here // The value of each strictFlag depends on own strictFlag value or this and never accessed directly. // But we need to store `strict` in builf info, even though it won't be examined directly, so that the // flags it controls (e.g. `strictNullChecks`) will be retrieved correctly affectsBuildInfo: true, showInSimplifiedHelpView: true, category: Diagnostics.Type_Checking, description: Diagnostics.Enable_all_strict_type_checking_options, defaultValueDescription: false, }, { name: ""noImplicitAny"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type, defaultValueDescription: Diagnostics.false_unless_strict_is_set, }, { name: ""strictNullChecks"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.When_type_checking_take_into_account_null_and_undefined, defaultValueDescription: Diagnostics.false_unless_strict_is_set, }, { name: ""strictFunctionTypes"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible, defaultValueDescription: Diagnostics.false_unless_strict_is_set, }, { name: ""strictBindCallApply"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function, defaultValueDescription: Diagnostics.false_unless_strict_is_set, }, { name: ""strictPropertyInitialization"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor, defaultValueDescription: Diagnostics.false_unless_strict_is_set, }, { name: ""strictBuiltinIteratorReturn"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Built_in_iterators_are_instantiated_with_a_TReturn_type_of_undefined_instead_of_any, defaultValueDescription: Diagnostics.false_unless_strict_is_set, }, { name: ""noImplicitThis"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Enable_error_reporting_when_this_is_given_the_type_any, defaultValueDescription: Diagnostics.false_unless_strict_is_set, }, { name: ""useUnknownInCatchVariables"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Default_catch_clause_variables_as_unknown_instead_of_any, defaultValueDescription: Diagnostics.false_unless_strict_is_set, }, { name: ""alwaysStrict"", type: ""boolean"", affectsSourceFile: true, affectsEmit: true, affectsBuildInfo: true, strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Ensure_use_strict_is_always_emitted, defaultValueDescription: Diagnostics.false_unless_strict_is_set, }, // Additional Checks { name: ""noUnusedLocals"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Type_Checking, description: Diagnostics.Enable_error_reporting_when_local_variables_aren_t_read, defaultValueDescription: false, }, { name: ""noUnusedParameters"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Type_Checking, description: Diagnostics.Raise_an_error_when_a_function_parameter_isn_t_read, defaultValueDescription: false, }, { name: ""exactOptionalPropertyTypes"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Type_Checking, description: Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, defaultValueDescription: false, }, { name: ""noImplicitReturns"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Type_Checking, description: Diagnostics.Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function, defaultValueDescription: false, }, { name: ""noFallthroughCasesInSwitch"", type: ""boolean"", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Type_Checking, description: Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, defaultValueDescription: false, }, { name: ""noUncheckedIndexedAccess"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Type_Checking, description: Diagnostics.Add_undefined_to_a_type_when_accessed_using_an_index, defaultValueDescription: false, }, { name: ""noImplicitOverride"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Type_Checking, description: Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, defaultValueDescription: false, }, { name: ""noPropertyAccessFromIndexSignature"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, showInSimplifiedHelpView: false, category: Diagnostics.Type_Checking, description: Diagnostics.Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type, defaultValueDescription: false, }, // Module Resolution { name: ""moduleResolution"", type: new Map(Object.entries({ // N.B. The first entry specifies the value shown in `tsc --init` node10: ModuleResolutionKind.Node10, node: ModuleResolutionKind.Node10, classic: ModuleResolutionKind.Classic, node16: ModuleResolutionKind.Node16, nodenext: ModuleResolutionKind.NodeNext, bundler: ModuleResolutionKind.Bundler, })), deprecatedKeys: new Set([""node""]), affectsSourceFile: true, affectsModuleResolution: true, paramType: Diagnostics.STRATEGY, category: Diagnostics.Modules, description: Diagnostics.Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier, defaultValueDescription: Diagnostics.module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node, }, { name: ""baseUrl"", type: ""string"", affectsModuleResolution: true, isFilePath: true, category: Diagnostics.Modules, description: Diagnostics.Specify_the_base_directory_to_resolve_non_relative_module_names, }, { // this option can only be specified in tsconfig.json // use type = object to copy the value as-is name: ""paths"", type: ""object"", affectsModuleResolution: true, allowConfigDirTemplateSubstitution: true, isTSConfigOnly: true, category: Diagnostics.Modules, description: Diagnostics.Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations, transpileOptionValue: undefined, }, { // this option can only be specified in tsconfig.json // use type = object to copy the value as-is name: ""rootDirs"", type: ""list"", isTSConfigOnly: true, element: { name: ""rootDirs"", type: ""string"", isFilePath: true, }, affectsModuleResolution: true, allowConfigDirTemplateSubstitution: true, category: Diagnostics.Modules, description: Diagnostics.Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules, transpileOptionValue: undefined, defaultValueDescription: Diagnostics.Computed_from_the_list_of_input_files, }, { name: ""typeRoots"", type: ""list"", element: { name: ""typeRoots"", type: ""string"", isFilePath: true, }, affectsModuleResolution: true, allowConfigDirTemplateSubstitution: true, category: Diagnostics.Modules, description: Diagnostics.Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types, }, { name: ""types"", type: ""list"", element: { name: ""types"", type: ""string"", }, affectsProgramStructure: true, showInSimplifiedHelpView: true, category: Diagnostics.Modules, description: Diagnostics.Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file, transpileOptionValue: undefined, }, { name: ""allowSyntheticDefaultImports"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Interop_Constraints, description: Diagnostics.Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export, defaultValueDescription: Diagnostics.module_system_or_esModuleInterop, }, { name: ""esModuleInterop"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsEmit: true, affectsBuildInfo: true, showInSimplifiedHelpView: true, category: Diagnostics.Interop_Constraints, description: Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility, defaultValueDescription: false, }, { name: ""preserveSymlinks"", type: ""boolean"", category: Diagnostics.Interop_Constraints, description: Diagnostics.Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node, defaultValueDescription: false, }, { name: ""allowUmdGlobalAccess"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Modules, description: Diagnostics.Allow_accessing_UMD_globals_from_modules, defaultValueDescription: false, }, { name: ""moduleSuffixes"", type: ""list"", element: { name: ""suffix"", type: ""string"", }, listPreserveFalsyValues: true, affectsModuleResolution: true, category: Diagnostics.Modules, description: Diagnostics.List_of_file_name_suffixes_to_search_when_resolving_a_module, }, { name: ""allowImportingTsExtensions"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Modules, description: Diagnostics.Allow_imports_to_include_TypeScript_file_extensions_Requires_moduleResolution_bundler_and_either_noEmit_or_emitDeclarationOnly_to_be_set, defaultValueDescription: false, transpileOptionValue: undefined, }, { name: ""rewriteRelativeImportExtensions"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Modules, description: Diagnostics.Rewrite_ts_tsx_mts_and_cts_file_extensions_in_relative_import_paths_to_their_JavaScript_equivalent_in_output_files, defaultValueDescription: false, }, { name: ""resolvePackageJsonExports"", type: ""boolean"", affectsModuleResolution: true, category: Diagnostics.Modules, description: Diagnostics.Use_the_package_json_exports_field_when_resolving_package_imports, defaultValueDescription: Diagnostics.true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false, }, { name: ""resolvePackageJsonImports"", type: ""boolean"", affectsModuleResolution: true, category: Diagnostics.Modules, description: Diagnostics.Use_the_package_json_imports_field_when_resolving_imports, defaultValueDescription: Diagnostics.true_when_moduleResolution_is_node16_nodenext_or_bundler_otherwise_false, }, { name: ""customConditions"", type: ""list"", element: { name: ""condition"", type: ""string"", }, affectsModuleResolution: true, category: Diagnostics.Modules, description: Diagnostics.Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports, }, { name: ""noUncheckedSideEffectImports"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Modules, description: Diagnostics.Check_side_effect_imports, defaultValueDescription: false, }, // Source Maps { name: ""sourceRoot"", type: ""string"", affectsEmit: true, affectsBuildInfo: true, paramType: Diagnostics.LOCATION, category: Diagnostics.Emit, description: Diagnostics.Specify_the_root_path_for_debuggers_to_find_the_reference_source_code, }, { name: ""mapRoot"", type: ""string"", affectsEmit: true, affectsBuildInfo: true, paramType: Diagnostics.LOCATION, category: Diagnostics.Emit, description: Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, }, { name: ""inlineSources"", type: ""boolean"", affectsEmit: true, affectsBuildInfo: true, category: Diagnostics.Emit, description: Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript, defaultValueDescription: false, }, // Experimental { name: ""experimentalDecorators"", type: ""boolean"", affectsEmit: true, affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Language_and_Environment, description: Diagnostics.Enable_experimental_support_for_legacy_experimental_decorators, defaultValueDescription: false, }, { name: ""emitDecoratorMetadata"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsEmit: true, affectsBuildInfo: true, category: Diagnostics.Language_and_Environment, description: Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, defaultValueDescription: false, }, // Advanced { name: ""jsxFactory"", type: ""string"", category: Diagnostics.Language_and_Environment, description: Diagnostics.Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h, defaultValueDescription: ""`React.createElement`"", }, { name: ""jsxFragmentFactory"", type: ""string"", category: Diagnostics.Language_and_Environment, description: Diagnostics.Specify_the_JSX_Fragment_reference_used_for_fragments_when_targeting_React_JSX_emit_e_g_React_Fragment_or_Fragment, defaultValueDescription: ""React.Fragment"", }, { name: ""jsxImportSource"", type: ""string"", affectsSemanticDiagnostics: true, affectsEmit: true, affectsBuildInfo: true, affectsModuleResolution: true, affectsSourceFile: true, category: Diagnostics.Language_and_Environment, description: Diagnostics.Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk, defaultValueDescription: ""react"", }, { name: ""resolveJsonModule"", type: ""boolean"", affectsModuleResolution: true, category: Diagnostics.Modules, description: Diagnostics.Enable_importing_json_files, defaultValueDescription: false, }, { name: ""allowArbitraryExtensions"", type: ""boolean"", affectsProgramStructure: true, category: Diagnostics.Modules, description: Diagnostics.Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present, defaultValueDescription: false, }, { name: ""out"", type: ""string"", affectsEmit: true, affectsBuildInfo: true, affectsDeclarationPath: true, isFilePath: false, // This is intentionally broken to support compatibility with existing tsconfig files // for correct behaviour, please use outFile category: Diagnostics.Backwards_Compatibility, paramType: Diagnostics.FILE, transpileOptionValue: undefined, description: Diagnostics.Deprecated_setting_Use_outFile_instead, }, { name: ""reactNamespace"", type: ""string"", affectsEmit: true, affectsBuildInfo: true, category: Diagnostics.Language_and_Environment, description: Diagnostics.Specify_the_object_invoked_for_createElement_This_only_applies_when_targeting_react_JSX_emit, defaultValueDescription: ""`React`"", }, { name: ""skipDefaultLibCheck"", type: ""boolean"", // We need to store these to determine whether `lib` files need to be rechecked affectsBuildInfo: true, category: Diagnostics.Completeness, description: Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript, defaultValueDescription: false, }, { name: ""charset"", type: ""string"", category: Diagnostics.Backwards_Compatibility, description: Diagnostics.No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files, defaultValueDescription: ""utf8"", }, { name: ""emitBOM"", type: ""boolean"", affectsEmit: true, affectsBuildInfo: true, category: Diagnostics.Emit, description: Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files, defaultValueDescription: false, }, { name: ""newLine"", type: new Map(Object.entries({ crlf: NewLineKind.CarriageReturnLineFeed, lf: NewLineKind.LineFeed, })), affectsEmit: true, affectsBuildInfo: true, paramType: Diagnostics.NEWLINE, category: Diagnostics.Emit, description: Diagnostics.Set_the_newline_character_for_emitting_files, defaultValueDescription: ""lf"", }, { name: ""noErrorTruncation"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Output_Formatting, description: Diagnostics.Disable_truncating_types_in_error_messages, defaultValueDescription: false, }, { name: ""noLib"", type: ""boolean"", category: Diagnostics.Language_and_Environment, affectsProgramStructure: true, description: Diagnostics.Disable_including_any_library_files_including_the_default_lib_d_ts, // We are not returning a sourceFile for lib file when asked by the program, // so pass --noLib to avoid reporting a file not found error. transpileOptionValue: true, defaultValueDescription: false, }, { name: ""noResolve"", type: ""boolean"", affectsModuleResolution: true, category: Diagnostics.Modules, description: Diagnostics.Disallow_import_s_require_s_or_reference_s_from_expanding_the_number_of_files_TypeScript_should_add_to_a_project, // We are not doing a full typecheck, we are not resolving the whole context, // so pass --noResolve to avoid reporting missing file errors. transpileOptionValue: true, defaultValueDescription: false, }, { name: ""stripInternal"", type: ""boolean"", affectsEmit: true, affectsBuildInfo: true, category: Diagnostics.Emit, description: Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, defaultValueDescription: false, }, { name: ""disableSizeLimit"", type: ""boolean"", affectsProgramStructure: true, category: Diagnostics.Editor_Support, description: Diagnostics.Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server, defaultValueDescription: false, }, { name: ""disableSourceOfProjectReferenceRedirect"", type: ""boolean"", isTSConfigOnly: true, category: Diagnostics.Projects, description: Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects, defaultValueDescription: false, }, { name: ""disableSolutionSearching"", type: ""boolean"", isTSConfigOnly: true, category: Diagnostics.Projects, description: Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing, defaultValueDescription: false, }, { name: ""disableReferencedProjectLoad"", type: ""boolean"", isTSConfigOnly: true, category: Diagnostics.Projects, description: Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript, defaultValueDescription: false, }, { name: ""noImplicitUseStrict"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Backwards_Compatibility, description: Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files, defaultValueDescription: false, }, { name: ""noEmitHelpers"", type: ""boolean"", affectsEmit: true, affectsBuildInfo: true, category: Diagnostics.Emit, description: Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output, defaultValueDescription: false, }, { name: ""noEmitOnError"", type: ""boolean"", affectsEmit: true, affectsBuildInfo: true, category: Diagnostics.Emit, transpileOptionValue: undefined, description: Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported, defaultValueDescription: false, }, { name: ""preserveConstEnums"", type: ""boolean"", affectsEmit: true, affectsBuildInfo: true, category: Diagnostics.Emit, description: Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, defaultValueDescription: false, }, { name: ""declarationDir"", type: ""string"", affectsEmit: true, affectsBuildInfo: true, affectsDeclarationPath: true, isFilePath: true, paramType: Diagnostics.DIRECTORY, category: Diagnostics.Emit, transpileOptionValue: undefined, description: Diagnostics.Specify_the_output_directory_for_generated_declaration_files, }, { name: ""skipLibCheck"", type: ""boolean"", // We need to store these to determine whether `lib` files need to be rechecked affectsBuildInfo: true, category: Diagnostics.Completeness, description: Diagnostics.Skip_type_checking_all_d_ts_files, defaultValueDescription: false, }, { name: ""allowUnusedLabels"", type: ""boolean"", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Type_Checking, description: Diagnostics.Disable_error_reporting_for_unused_labels, defaultValueDescription: undefined, }, { name: ""allowUnreachableCode"", type: ""boolean"", affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Type_Checking, description: Diagnostics.Disable_error_reporting_for_unreachable_code, defaultValueDescription: undefined, }, { name: ""suppressExcessPropertyErrors"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Backwards_Compatibility, description: Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals, defaultValueDescription: false, }, { name: ""suppressImplicitAnyIndexErrors"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Backwards_Compatibility, description: Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures, defaultValueDescription: false, }, { name: ""forceConsistentCasingInFileNames"", type: ""boolean"", affectsModuleResolution: true, category: Diagnostics.Interop_Constraints, description: Diagnostics.Ensure_that_casing_is_correct_in_imports, defaultValueDescription: true, }, { name: ""maxNodeModuleJsDepth"", type: ""number"", affectsModuleResolution: true, category: Diagnostics.JavaScript_Support, description: Diagnostics.Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicable_with_allowJs, defaultValueDescription: 0, }, { name: ""noStrictGenericChecks"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsBuildInfo: true, category: Diagnostics.Backwards_Compatibility, description: Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, defaultValueDescription: false, }, { name: ""useDefineForClassFields"", type: ""boolean"", affectsSemanticDiagnostics: true, affectsEmit: true, affectsBuildInfo: true, category: Diagnostics.Language_and_Environment, description: Diagnostics.Emit_ECMAScript_standard_compliant_class_fields, defaultValueDescription: Diagnostics.true_for_ES2022_and_above_including_ESNext, }, { name: ""preserveValueImports"", type: ""boolean"", affectsEmit: true, affectsBuildInfo: true, category: Diagnostics.Backwards_Compatibility, description: Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, defaultValueDescription: false, }, { name: ""keyofStringsOnly"", type: ""boolean"", category: Diagnostics.Backwards_Compatibility, description: Diagnostics.Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option, defaultValueDescription: false, }, { // A list of plugins to load in the language service name: ""plugins"", type: ""list"", isTSConfigOnly: true, element: { name: ""plugin"", type: ""object"", }, description: Diagnostics.Specify_a_list_of_language_service_plugins_to_include, category: Diagnostics.Editor_Support, }, { name: ""moduleDetection"", type: new Map(Object.entries({ auto: ModuleDetectionKind.Auto, legacy: ModuleDetectionKind.Legacy, force: ModuleDetectionKind.Force, })), affectsSourceFile: true, affectsModuleResolution: true, description: Diagnostics.Control_what_method_is_used_to_detect_module_format_JS_files, category: Diagnostics.Language_and_Environment, defaultValueDescription: Diagnostics.auto_Colon_Treat_files_with_imports_exports_import_meta_jsx_with_jsx_Colon_react_jsx_or_esm_format_with_module_Colon_node16_as_modules, }, { name: ""ignoreDeprecations"", type: ""string"", defaultValueDescription: undefined, }, ]; // Do not delete this without updating the website's tsconfig generation. /** @internal */ export const optionDeclarations: CommandLineOption[] = [ ...commonOptionsWithBuild, ...commandOptionsWithoutBuild, ]; /** @internal */ export const semanticDiagnosticsOptionDeclarations: readonly CommandLineOption[] = optionDeclarations.filter(option => !!option.affectsSemanticDiagnostics); /** @internal */ export const affectsEmitOptionDeclarations: readonly CommandLineOption[] = optionDeclarations.filter(option => !!option.affectsEmit); /** @internal */ export const affectsDeclarationPathOptionDeclarations: readonly CommandLineOption[] = optionDeclarations.filter(option => !!option.affectsDeclarationPath); /** @internal */ export const moduleResolutionOptionDeclarations: readonly CommandLineOption[] = optionDeclarations.filter(option => !!option.affectsModuleResolution); /** @internal */ export const sourceFileAffectingCompilerOptions: readonly CommandLineOption[] = optionDeclarations.filter(option => !!option.affectsSourceFile || !!option.affectsBindDiagnostics); /** @internal */ export const optionsAffectingProgramStructure: readonly CommandLineOption[] = optionDeclarations.filter(option => !!option.affectsProgramStructure); /** @internal */ export const transpileOptionValueCompilerOptions: readonly CommandLineOption[] = optionDeclarations.filter(option => hasProperty(option, ""transpileOptionValue"")); const configDirTemplateSubstitutionOptions: readonly CommandLineOption[] = optionDeclarations.filter( option => option.allowConfigDirTemplateSubstitution || (!option.isCommandLineOnly && option.isFilePath), ); const configDirTemplateSubstitutionWatchOptions: readonly CommandLineOption[] = optionsForWatch.filter( option => option.allowConfigDirTemplateSubstitution || (!option.isCommandLineOnly && option.isFilePath), ); /** @internal */ export const commandLineOptionOfCustomType: readonly CommandLineOptionOfCustomType[] = optionDeclarations.filter(isCommandLineOptionOfCustomType); function isCommandLineOptionOfCustomType(option: CommandLineOption): option is CommandLineOptionOfCustomType { return !isString(option.type); } /** @internal */ export const tscBuildOption: CommandLineOption = { name: ""build"", type: ""boolean"", shortName: ""b"", showInSimplifiedHelpView: true, category: Diagnostics.Command_line_Options, description: Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date, defaultValueDescription: false, }; // Build related options /** @internal */ export const optionsForBuild: CommandLineOption[] = [ tscBuildOption, { name: ""verbose"", shortName: ""v"", category: Diagnostics.Command_line_Options, description: Diagnostics.Enable_verbose_logging, type: ""boolean"", defaultValueDescription: false, }, { name: ""dry"", shortName: ""d"", category: Diagnostics.Command_line_Options, description: Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, type: ""boolean"", defaultValueDescription: false, }, { name: ""force"", shortName: ""f"", category: Diagnostics.Command_line_Options, description: Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, type: ""boolean"", defaultValueDescription: false, }, { name: ""clean"", category: Diagnostics.Command_line_Options, description: Diagnostics.Delete_the_outputs_of_all_projects, type: ""boolean"", defaultValueDescription: false, }, { name: ""stopBuildOnErrors"", category: Diagnostics.Command_line_Options, description: Diagnostics.Skip_building_downstream_projects_on_error_in_upstream_project, type: ""boolean"", defaultValueDescription: false, }, ]; /** @internal */ export const buildOpts: CommandLineOption[] = [ ...commonOptionsWithBuild, ...optionsForBuild, ]; // Do not delete this without updating the website's tsconfig generation. /** @internal */ export const typeAcquisitionDeclarations: CommandLineOption[] = [ { name: ""enable"", type: ""boolean"", defaultValueDescription: false, }, { name: ""include"", type: ""list"", element: { name: ""include"", type: ""string"", }, }, { name: ""exclude"", type: ""list"", element: { name: ""exclude"", type: ""string"", }, }, { name: ""disableFilenameBasedTypeAcquisition"", type: ""boolean"", defaultValueDescription: false, }, ]; /** @internal */ export interface OptionsNameMap { optionsNameMap: Map; shortOptionNames: Map; } /** @internal */ export function createOptionNameMap(optionDeclarations: readonly CommandLineOption[]): OptionsNameMap { const optionsNameMap = new Map(); const shortOptionNames = new Map(); forEach(optionDeclarations, option => { optionsNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); return { optionsNameMap, shortOptionNames }; } let optionsNameMapCache: OptionsNameMap; /** @internal */ export function getOptionsNameMap(): OptionsNameMap { return optionsNameMapCache ||= createOptionNameMap(optionDeclarations); } const compilerOptionsAlternateMode: AlternateModeDiagnostics = { diagnostic: Diagnostics.Compiler_option_0_may_only_be_used_with_build, getOptionsNameMap: getBuildOptionsNameMap, }; // Do not delete this without updating the website's tsconfig generation. /** @internal @knipignore */ export const defaultInitCompilerOptions: CompilerOptions = { module: ModuleKind.CommonJS, target: ScriptTarget.ES2016, strict: true, esModuleInterop: true, forceConsistentCasingInFileNames: true, skipLibCheck: true, }; /** @internal */ export function createCompilerDiagnosticForInvalidCustomType(opt: CommandLineOptionOfCustomType): Diagnostic { return createDiagnosticForInvalidCustomType(opt, createCompilerDiagnostic); } function createDiagnosticForInvalidCustomType(opt: CommandLineOptionOfCustomType, createDiagnostic: (message: DiagnosticMessage, ...args: DiagnosticArguments) => Diagnostic): Diagnostic { const namesOfType = arrayFrom(opt.type.keys()); const stringNames = (opt.deprecatedKeys ? namesOfType.filter(k => !opt.deprecatedKeys!.has(k)) : namesOfType).map(key => `'${key}'`).join("", ""); return createDiagnostic(Diagnostics.Argument_for_0_option_must_be_Colon_1, `--${opt.name}`, stringNames); } /** @internal */ export function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string | undefined, errors: Diagnostic[]): string | number | undefined { return convertJsonOptionOfCustomType(opt, (value ?? """").trim(), errors); } /** @internal */ export function parseListTypeOption(opt: CommandLineOptionOfListType, value = """", errors: Diagnostic[]): string | (string | number)[] | undefined { value = value.trim(); if (startsWith(value, ""-"")) { return undefined; } if (opt.type === ""listOrElement"" && !value.includes("","")) { return validateJsonOptionValue(opt, value, errors); } if (value === """") { return []; } const values = value.split("",""); switch (opt.element.type) { case ""number"": return mapDefined(values, v => validateJsonOptionValue(opt.element, parseInt(v), errors)); case ""string"": return mapDefined(values, v => validateJsonOptionValue(opt.element, v || """", errors)); case ""boolean"": case ""object"": return Debug.fail(`List of ${opt.element.type} is not yet supported.`); default: return mapDefined(values, v => parseCustomTypeOption(opt.element as CommandLineOptionOfCustomType, v, errors)); } } /** @internal */ export interface OptionsBase { [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined; } /** @internal */ export interface BaseParsedCommandLine { options: OptionsBase; watchOptions: WatchOptions | undefined; fileNames: string[]; errors: Diagnostic[]; } /** @internal */ export interface ParseCommandLineWorkerDiagnostics extends DidYouMeanOptionsDiagnostics { getOptionsNameMap: () => OptionsNameMap; optionTypeMismatchDiagnostic: DiagnosticMessage; } function getOptionName(option: CommandLineOption) { return option.name; } function createUnknownOptionError( unknownOption: string, diagnostics: DidYouMeanOptionsDiagnostics, unknownOptionErrorText?: string, node?: PropertyName, sourceFile?: TsConfigSourceFile, ) { const otherOption = diagnostics.alternateMode?.getOptionsNameMap().optionsNameMap.get(unknownOption.toLowerCase()); if (otherOption) { return createDiagnosticForNodeInSourceFileOrCompilerDiagnostic( sourceFile, node, otherOption !== tscBuildOption ? diagnostics.alternateMode!.diagnostic : Diagnostics.Option_build_must_be_the_first_command_line_argument, unknownOption, ); } const possibleOption = getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName); return possibleOption ? createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption); } /** @internal */ export function parseCommandLineWorker( diagnostics: ParseCommandLineWorkerDiagnostics, commandLine: readonly string[], readFile?: (path: string) => string | undefined, ): BaseParsedCommandLine { const options = {} as OptionsBase; let watchOptions: WatchOptions | undefined; const fileNames: string[] = []; const errors: Diagnostic[] = []; parseStrings(commandLine); return { options, watchOptions, fileNames, errors, }; function parseStrings(args: readonly string[]) { let i = 0; while (i < args.length) { const s = args[i]; i++; if (s.charCodeAt(0) === CharacterCodes.at) { parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === CharacterCodes.minus) { const inputOptionName = s.slice(s.charCodeAt(1) === CharacterCodes.minus ? 2 : 1); const opt = getOptionDeclarationFromName(diagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true); if (opt) { i = parseOptionValue(args, i, diagnostics, opt, options, errors); } else { const watchOpt = getOptionDeclarationFromName(watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true); if (watchOpt) { i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors); } else { errors.push(createUnknownOptionError(inputOptionName, diagnostics, s)); } } } else { fileNames.push(s); } } } function parseResponseFile(fileName: string) { const text = tryReadFile(fileName, readFile || (fileName => sys.readFile(fileName))); if (!isString(text)) { errors.push(text); return; } const args: string[] = []; let pos = 0; while (true) { while (pos < text.length && text.charCodeAt(pos) <= CharacterCodes.space) pos++; if (pos >= text.length) break; const start = pos; if (text.charCodeAt(start) === CharacterCodes.doubleQuote) { pos++; while (pos < text.length && text.charCodeAt(pos) !== CharacterCodes.doubleQuote) pos++; if (pos < text.length) { args.push(text.substring(start + 1, pos)); pos++; } else { errors.push(createCompilerDiagnostic(Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName)); } } else { while (text.charCodeAt(pos) > CharacterCodes.space) pos++; args.push(text.substring(start, pos)); } } parseStrings(args); } } function parseOptionValue( args: readonly string[], i: number, diagnostics: ParseCommandLineWorkerDiagnostics, opt: CommandLineOption, options: OptionsBase, errors: Diagnostic[], ) { if (opt.isTSConfigOnly) { const optValue = args[i]; if (optValue === ""null"") { options[opt.name] = undefined; i++; } else if (opt.type === ""boolean"") { if (optValue === ""false"") { options[opt.name] = validateJsonOptionValue(opt, /*value*/ false, errors); i++; } else { if (optValue === ""true"") i++; errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line, opt.name)); } } else { errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line, opt.name)); if (optValue && !startsWith(optValue, ""-"")) i++; } } else { // Check to see if no argument was provided (e.g. ""--locale"" is the last command-line argument). if (!args[i] && opt.type !== ""boolean"") { errors.push(createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt))); } if (args[i] !== ""null"") { switch (opt.type) { case ""number"": options[opt.name] = validateJsonOptionValue(opt, parseInt(args[i]), errors); i++; break; case ""boolean"": // boolean flag has optional value true, false, others const optValue = args[i]; options[opt.name] = validateJsonOptionValue(opt, optValue !== ""false"", errors); // consume next argument as boolean flag value if (optValue === ""false"" || optValue === ""true"") { i++; } break; case ""string"": options[opt.name] = validateJsonOptionValue(opt, args[i] || """", errors); i++; break; case ""list"": const result = parseListTypeOption(opt, args[i], errors); options[opt.name] = result || []; if (result) { i++; } break; case ""listOrElement"": Debug.fail(""listOrElement not supported here""); break; // If not a primitive, the possible types are specified in what is effectively a map of options. default: options[opt.name] = parseCustomTypeOption(opt as CommandLineOptionOfCustomType, args[i], errors); i++; break; } } else { options[opt.name] = undefined; i++; } } return i; } /** @internal */ export const compilerOptionsDidYouMeanDiagnostics: ParseCommandLineWorkerDiagnostics = { alternateMode: compilerOptionsAlternateMode, getOptionsNameMap, optionDeclarations, unknownOptionDiagnostic: Diagnostics.Unknown_compiler_option_0, unknownDidYouMeanDiagnostic: Diagnostics.Unknown_compiler_option_0_Did_you_mean_1, optionTypeMismatchDiagnostic: Diagnostics.Compiler_option_0_expects_an_argument, }; export function parseCommandLine(commandLine: readonly string[], readFile?: (path: string) => string | undefined): ParsedCommandLine { return parseCommandLineWorker(compilerOptionsDidYouMeanDiagnostics, commandLine, readFile); } /** @internal */ export function getOptionFromName(optionName: string, allowShort?: boolean): CommandLineOption | undefined { return getOptionDeclarationFromName(getOptionsNameMap, optionName, allowShort); } function getOptionDeclarationFromName(getOptionNameMap: () => OptionsNameMap, optionName: string, allowShort = false): CommandLineOption | undefined { optionName = optionName.toLowerCase(); const { optionsNameMap, shortOptionNames } = getOptionNameMap(); // Try to translate short option names to their full equivalents. if (allowShort) { const short = shortOptionNames.get(optionName); if (short !== undefined) { optionName = short; } } return optionsNameMap.get(optionName); } /** Parsed command line for build */ export interface ParsedBuildCommand { buildOptions: BuildOptions; watchOptions: WatchOptions | undefined; projects: string[]; errors: Diagnostic[]; } let buildOptionsNameMapCache: OptionsNameMap; function getBuildOptionsNameMap(): OptionsNameMap { return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(buildOpts)); } const buildOptionsAlternateMode: AlternateModeDiagnostics = { diagnostic: Diagnostics.Compiler_option_0_may_not_be_used_with_build, getOptionsNameMap, }; const buildOptionsDidYouMeanDiagnostics: ParseCommandLineWorkerDiagnostics = { alternateMode: buildOptionsAlternateMode, getOptionsNameMap: getBuildOptionsNameMap, optionDeclarations: buildOpts, unknownOptionDiagnostic: Diagnostics.Unknown_build_option_0, unknownDidYouMeanDiagnostic: Diagnostics.Unknown_build_option_0_Did_you_mean_1, optionTypeMismatchDiagnostic: Diagnostics.Build_option_0_requires_a_value_of_type_1, }; export function parseBuildCommand(commandLine: readonly string[]): ParsedBuildCommand { const { options, watchOptions, fileNames: projects, errors } = parseCommandLineWorker( buildOptionsDidYouMeanDiagnostics, commandLine, ); const buildOptions = options as BuildOptions; if (projects.length === 0) { // tsc -b invoked with no extra arguments; act as if invoked with ""tsc -b ."" projects.push("".""); } // Nonsensical combinations if (buildOptions.clean && buildOptions.force) { errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, ""clean"", ""force"")); } if (buildOptions.clean && buildOptions.verbose) { errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, ""clean"", ""verbose"")); } if (buildOptions.clean && buildOptions.watch) { errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, ""clean"", ""watch"")); } if (buildOptions.watch && buildOptions.dry) { errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, ""watch"", ""dry"")); } return { buildOptions, watchOptions, projects, errors }; } /** @internal */ export function getDiagnosticText(message: DiagnosticMessage, ...args: any[]): string { return cast(createCompilerDiagnostic(message, ...args).messageText, isString); } export type DiagnosticReporter = (diagnostic: Diagnostic) => void; /** * Reports config file diagnostics */ export interface ConfigFileDiagnosticsReporter { /** * Reports unrecoverable error when parsing config file */ onUnRecoverableConfigFileDiagnostic: DiagnosticReporter; } /** * Interface extending ParseConfigHost to support ParseConfigFile that reads config file and reports errors */ export interface ParseConfigFileHost extends ParseConfigHost, ConfigFileDiagnosticsReporter { getCurrentDirectory(): string; } /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ export function getParsedCommandLineOfConfigFile( configFileName: string, optionsToExtend: CompilerOptions | undefined, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[], ): ParsedCommandLine | undefined { const configFileText = tryReadFile(configFileName, fileName => host.readFile(fileName)); if (!isString(configFileText)) { host.onUnRecoverableConfigFileDiagnostic(configFileText); return undefined; } const result = parseJsonText(configFileName, configFileText); const cwd = host.getCurrentDirectory(); result.path = toPath(configFileName, cwd, createGetCanonicalFileName(host.useCaseSensitiveFileNames)); result.resolvedPath = result.path; result.originalFileName = result.fileName; return parseJsonSourceFileConfigFileContent( result, host, getNormalizedAbsolutePath(getDirectoryPath(configFileName), cwd), optionsToExtend, getNormalizedAbsolutePath(configFileName, cwd), /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend, ); } /** * Read tsconfig.json file * @param fileName The path to the config file */ export function readConfigFile(fileName: string, readFile: (path: string) => string | undefined): { config?: any; error?: Diagnostic; } { const textOrDiagnostic = tryReadFile(fileName, readFile); return isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; } /** * Parse the text of the tsconfig.json file * @param fileName The path to the config file * @param jsonText The text of the config file */ export function parseConfigFileTextToJson(fileName: string, jsonText: string): { config?: any; error?: Diagnostic; } { const jsonSourceFile = parseJsonText(fileName, jsonText); return { config: convertConfigFileToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics, /*jsonConversionNotifier*/ undefined), error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined, }; } /** * Read tsconfig.json file * @param fileName The path to the config file */ export function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile { const textOrDiagnostic = tryReadFile(fileName, readFile); return isString(textOrDiagnostic) ? parseJsonText(fileName, textOrDiagnostic) : { fileName, parseDiagnostics: [textOrDiagnostic] } as TsConfigSourceFile; } /** @internal */ export function tryReadFile(fileName: string, readFile: (path: string) => string | undefined): string | Diagnostic { let text: string | undefined; try { text = readFile(fileName); } catch (e) { return createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); } return text === undefined ? createCompilerDiagnostic(Diagnostics.Cannot_read_file_0, fileName) : text; } function commandLineOptionsToMap(options: readonly CommandLineOption[]) { return arrayToMap(options, getOptionName); } const typeAcquisitionDidYouMeanDiagnostics: DidYouMeanOptionsDiagnostics = { optionDeclarations: typeAcquisitionDeclarations, unknownOptionDiagnostic: Diagnostics.Unknown_type_acquisition_option_0, unknownDidYouMeanDiagnostic: Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1, }; let watchOptionsNameMapCache: OptionsNameMap; function getWatchOptionsNameMap(): OptionsNameMap { return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(optionsForWatch)); } const watchOptionsDidYouMeanDiagnostics: ParseCommandLineWorkerDiagnostics = { getOptionsNameMap: getWatchOptionsNameMap, optionDeclarations: optionsForWatch, unknownOptionDiagnostic: Diagnostics.Unknown_watch_option_0, unknownDidYouMeanDiagnostic: Diagnostics.Unknown_watch_option_0_Did_you_mean_1, optionTypeMismatchDiagnostic: Diagnostics.Watch_option_0_requires_a_value_of_type_1, }; let commandLineCompilerOptionsMapCache: Map; function getCommandLineCompilerOptionsMap() { return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(optionDeclarations)); } let commandLineWatchOptionsMapCache: Map; function getCommandLineWatchOptionsMap() { return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(optionsForWatch)); } let commandLineTypeAcquisitionMapCache: Map; function getCommandLineTypeAcquisitionMap() { return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(typeAcquisitionDeclarations)); } const extendsOptionDeclaration: CommandLineOptionOfListType = { name: ""extends"", type: ""listOrElement"", element: { name: ""extends"", type: ""string"", }, category: Diagnostics.File_Management, disallowNullOrUndefined: true, }; const compilerOptionsDeclaration: TsConfigOnlyOption = { name: ""compilerOptions"", type: ""object"", elementOptions: getCommandLineCompilerOptionsMap(), extraKeyDiagnostics: compilerOptionsDidYouMeanDiagnostics, }; const watchOptionsDeclaration: TsConfigOnlyOption = { name: ""watchOptions"", type: ""object"", elementOptions: getCommandLineWatchOptionsMap(), extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics, }; const typeAcquisitionDeclaration: TsConfigOnlyOption = { name: ""typeAcquisition"", type: ""object"", elementOptions: getCommandLineTypeAcquisitionMap(), extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics, }; let _tsconfigRootOptions: TsConfigOnlyOption; function getTsconfigRootOptionsMap() { if (_tsconfigRootOptions === undefined) { _tsconfigRootOptions = { name: undefined!, // should never be needed since this is root type: ""object"", elementOptions: commandLineOptionsToMap([ compilerOptionsDeclaration, watchOptionsDeclaration, typeAcquisitionDeclaration, extendsOptionDeclaration, { name: ""references"", type: ""list"", element: { name: ""references"", type: ""object"", }, category: Diagnostics.Projects, }, { name: ""files"", type: ""list"", element: { name: ""files"", type: ""string"", }, category: Diagnostics.File_Management, }, { name: ""include"", type: ""list"", element: { name: ""include"", type: ""string"", }, category: Diagnostics.File_Management, defaultValueDescription: Diagnostics.if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk, }, { name: ""exclude"", type: ""list"", element: { name: ""exclude"", type: ""string"", }, category: Diagnostics.File_Management, defaultValueDescription: Diagnostics.node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified, }, compileOnSaveCommandLineOption, ]), }; } return _tsconfigRootOptions; } /** @internal */ export interface JsonConversionNotifier { rootOptions: TsConfigOnlyOption; onPropertySet( keyText: string, value: any, propertyAssignment: PropertyAssignment, parentOption: TsConfigOnlyOption | undefined, option: CommandLineOption | undefined, ): void; } function convertConfigFileToObject( sourceFile: JsonSourceFile, errors: Diagnostic[], jsonConversionNotifier: JsonConversionNotifier | undefined, ): any { const rootExpression: Expression | undefined = sourceFile.statements[0]?.expression; if (rootExpression && rootExpression.kind !== SyntaxKind.ObjectLiteralExpression) { errors.push(createDiagnosticForNodeInSourceFile( sourceFile, rootExpression, Diagnostics.The_root_value_of_a_0_file_must_be_an_object, getBaseFileName(sourceFile.fileName) === ""jsconfig.json"" ? ""jsconfig.json"" : ""tsconfig.json"", )); // Last-ditch error recovery. Somewhat useful because the JSON parser will recover from some parse errors by // synthesizing a top-level array literal expression. There's a reasonable chance the first element of that // array is a well-formed configuration object, made into an array element by stray characters. if (isArrayLiteralExpression(rootExpression)) { const firstObject = find(rootExpression.elements, isObjectLiteralExpression); if (firstObject) { return convertToJson(sourceFile, firstObject, errors, /*returnValue*/ true, jsonConversionNotifier); } } return {}; } return convertToJson(sourceFile, rootExpression, errors, /*returnValue*/ true, jsonConversionNotifier); } /** * Convert the json syntax tree into the json value */ export function convertToObject(sourceFile: JsonSourceFile, errors: Diagnostic[]): any { return convertToJson(sourceFile, sourceFile.statements[0]?.expression, errors, /*returnValue*/ true, /*jsonConversionNotifier*/ undefined); } /** * Convert the json syntax tree into the json value and report errors * This returns the json value (apart from checking errors) only if returnValue provided is true. * Otherwise it just checks the errors and returns undefined * * @internal */ export function convertToJson( sourceFile: JsonSourceFile, rootExpression: Expression | undefined, errors: Diagnostic[], returnValue: boolean, jsonConversionNotifier: JsonConversionNotifier | undefined, ): any { if (!rootExpression) { return returnValue ? {} : undefined; } return convertPropertyValueToJson(rootExpression, jsonConversionNotifier?.rootOptions); function convertObjectLiteralExpressionToJson( node: ObjectLiteralExpression, objectOption: TsConfigOnlyOption | undefined, ): any { const result: any = returnValue ? {} : undefined; for (const element of node.properties) { if (element.kind !== SyntaxKind.PropertyAssignment) { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, element, Diagnostics.Property_assignment_expected)); continue; } if (element.questionToken) { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ""?"")); } if (!isDoubleQuotedString(element.name)) { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, element.name, Diagnostics.String_literal_with_double_quotes_expected)); } const textOfKey = isComputedNonLiteralName(element.name) ? undefined : getTextOfPropertyName(element.name); const keyText = textOfKey && unescapeLeadingUnderscores(textOfKey); const option = keyText ? objectOption?.elementOptions?.get(keyText) : undefined; const value = convertPropertyValueToJson(element.initializer, option); if (typeof keyText !== ""undefined"") { if (returnValue) { result[keyText] = value; } // Notify key value set, if user asked for it jsonConversionNotifier?.onPropertySet(keyText, value, element, objectOption, option); } } return result; } function convertArrayLiteralExpressionToJson( elements: NodeArray, elementOption: CommandLineOption | undefined, ) { if (!returnValue) { elements.forEach(element => convertPropertyValueToJson(element, elementOption)); return undefined; } // Filter out invalid values return filter(elements.map(element => convertPropertyValueToJson(element, elementOption)), v => v !== undefined); } function convertPropertyValueToJson(valueExpression: Expression, option: CommandLineOption | undefined): any { switch (valueExpression.kind) { case SyntaxKind.TrueKeyword: return true; case SyntaxKind.FalseKeyword: return false; case SyntaxKind.NullKeyword: return null; // eslint-disable-line no-restricted-syntax case SyntaxKind.StringLiteral: if (!isDoubleQuotedString(valueExpression)) { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.String_literal_with_double_quotes_expected)); } return (valueExpression as StringLiteral).text; case SyntaxKind.NumericLiteral: return Number((valueExpression as NumericLiteral).text); case SyntaxKind.PrefixUnaryExpression: if ((valueExpression as PrefixUnaryExpression).operator !== SyntaxKind.MinusToken || (valueExpression as PrefixUnaryExpression).operand.kind !== SyntaxKind.NumericLiteral) { break; // not valid JSON syntax } return -Number(((valueExpression as PrefixUnaryExpression).operand as NumericLiteral).text); case SyntaxKind.ObjectLiteralExpression: const objectLiteralExpression = valueExpression as ObjectLiteralExpression; // Currently having element option declaration in the tsconfig with type ""object"" // determines if it needs onSetValidOptionKeyValueInParent callback or not // At moment there are only ""compilerOptions"", ""typeAcquisition"" and ""typingOptions"" // that satisfies it and need it to modify options set in them (for normalizing file paths) // vs what we set in the json // If need arises, we can modify this interface and callbacks as needed return convertObjectLiteralExpressionToJson(objectLiteralExpression, option as TsConfigOnlyOption); case SyntaxKind.ArrayLiteralExpression: return convertArrayLiteralExpressionToJson( (valueExpression as ArrayLiteralExpression).elements, option && (option as CommandLineOptionOfListType).element, ); } // Not in expected format if (option) { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); } else { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); } return undefined; } function isDoubleQuotedString(node: Node): boolean { return isStringLiteral(node) && isStringDoubleQuoted(node, sourceFile); } } function getCompilerOptionValueTypeString(option: CommandLineOption): string { return (option.type === ""listOrElement"") ? `${getCompilerOptionValueTypeString(option.element)} or Array` : option.type === ""list"" ? ""Array"" : isString(option.type) ? option.type : ""string""; } function isCompilerOptionsValue(option: CommandLineOption | undefined, value: any): value is CompilerOptionsValue { if (option) { if (isNullOrUndefined(value)) return !option.disallowNullOrUndefined; // All options are undefinable/nullable if (option.type === ""list"") { return isArray(value); } if (option.type === ""listOrElement"") { return isArray(value) || isCompilerOptionsValue(option.element, value); } const expectedType = isString(option.type) ? option.type : ""string""; return typeof value === expectedType; } return false; } /** @internal */ export interface TSConfig { compilerOptions: CompilerOptions; compileOnSave: boolean | undefined; exclude?: readonly string[]; files: readonly string[] | undefined; include?: readonly string[]; references: readonly ProjectReference[] | undefined; } /** @internal */ export interface ConvertToTSConfigHost { getCurrentDirectory(): string; useCaseSensitiveFileNames: boolean; } /** * Generate an uncommented, complete tsconfig for use with ""--showConfig"" * @param configParseResult options to be generated into tsconfig.json * @param configFileName name of the parsed config file - output paths will be generated relative to this * @param host provides current directory and case sensitivity services * * @internal */ export function convertToTSConfig(configParseResult: ParsedCommandLine, configFileName: string, host: ConvertToTSConfigHost): TSConfig { const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); const files = map( filter( configParseResult.fileNames, !configParseResult.options.configFile?.configFileSpecs?.validatedIncludeSpecs ? returnTrue : matchesSpecs( configFileName, configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs, configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs, host, ), ), f => getRelativePathFromFile(getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName), ); const pathOptions = { configFilePath: getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }; const optionMap = serializeCompilerOptions(configParseResult.options, pathOptions); const watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions); const config: TSConfig & { watchOptions?: object; } = { compilerOptions: { ...optionMapToObject(optionMap), showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined, build: undefined, version: undefined, }, watchOptions: watchOptionMap && optionMapToObject(watchOptionMap), references: map(configParseResult.projectReferences, r => ({ ...r, path: r.originalPath ? r.originalPath : """", originalPath: undefined })), files: length(files) ? files : undefined, ...(configParseResult.options.configFile?.configFileSpecs ? { include: filterSameAsDefaultInclude(configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs), exclude: configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs, } : {}), compileOnSave: !!configParseResult.compileOnSave ? true : undefined, }; const providedKeys = new Set(optionMap.keys()); const impliedCompilerOptions: Record = {}; for (const option in computedOptions) { if (!providedKeys.has(option) && optionDependsOn(option, providedKeys)) { const implied = computedOptions[option].computeValue(configParseResult.options); const defaultValue = computedOptions[option].computeValue({}); if (implied !== defaultValue) { impliedCompilerOptions[option] = computedOptions[option].computeValue(configParseResult.options); } } } assign(config.compilerOptions, optionMapToObject(serializeCompilerOptions(impliedCompilerOptions, pathOptions))); return config; } function optionDependsOn(option: string, dependsOn: Set): boolean { const seen = new Set(); return optionDependsOnRecursive(option); function optionDependsOnRecursive(option: string): boolean { if (addToSeen(seen, option)) { return some(computedOptions[option]?.dependencies, dep => dependsOn.has(dep) || optionDependsOnRecursive(dep)); } return false; } } /** @internal */ export function optionMapToObject(optionMap: Map): object { return Object.fromEntries(optionMap); } function filterSameAsDefaultInclude(specs: readonly string[] | undefined) { if (!length(specs)) return undefined; if (length(specs) !== 1) return specs; if (specs![0] === defaultIncludeSpec) return undefined; return specs; } function matchesSpecs(path: string, includeSpecs: readonly string[] | undefined, excludeSpecs: readonly string[] | undefined, host: ConvertToTSConfigHost): (path: string) => boolean { if (!includeSpecs) return returnTrue; const patterns = getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory()); const excludeRe = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames); const includeRe = patterns.includeFilePattern && getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { return path => !(includeRe.test(path) && !excludeRe.test(path)); } return path => !includeRe.test(path); } if (excludeRe) { return path => excludeRe.test(path); } return returnTrue; } function getCustomTypeMapOfCommandLineOption(optionDefinition: CommandLineOption): Map | undefined { switch (optionDefinition.type) { case ""string"": case ""number"": case ""boolean"": case ""object"": // this is of a type CommandLineOptionOfPrimitiveType return undefined; case ""list"": case ""listOrElement"": return getCustomTypeMapOfCommandLineOption(optionDefinition.element); default: return optionDefinition.type; } } /** @internal */ export function getNameOfCompilerOptionValue(value: CompilerOptionsValue, customTypeMap: Map): string | undefined { // There is a typeMap associated with this command-line option so use it to map value back to its name return forEachEntry(customTypeMap, (mapValue, key) => { if (mapValue === value) { return key; } }); } /** @internal */ export function serializeCompilerOptions( options: CompilerOptions, pathOptions?: { configFilePath: string; useCaseSensitiveFileNames: boolean; }, ): Map { return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions); } function serializeWatchOptions(options: WatchOptions) { return serializeOptionBaseObject(options, getWatchOptionsNameMap()); } function serializeOptionBaseObject( options: OptionsBase, { optionsNameMap }: OptionsNameMap, pathOptions?: { configFilePath: string; useCaseSensitiveFileNames: boolean; }, ): Map { const result = new Map(); const getCanonicalFileName = pathOptions && createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); for (const name in options) { if (hasProperty(options, name)) { // tsconfig only options cannot be specified via command line, // so we can assume that only types that can appear here string | number | boolean if (optionsNameMap.has(name) && (optionsNameMap.get(name)!.category === Diagnostics.Command_line_Options || optionsNameMap.get(name)!.category === Diagnostics.Output_Formatting)) { continue; } const value = options[name] as CompilerOptionsValue; const optionDefinition = optionsNameMap.get(name.toLowerCase()); if (optionDefinition) { Debug.assert(optionDefinition.type !== ""listOrElement""); const customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); if (!customTypeMap) { // There is no map associated with this compiler option then use the value as-is // This is the case if the value is expect to be string, number, boolean or list of string if (pathOptions && optionDefinition.isFilePath) { result.set(name, getRelativePathFromFile(pathOptions.configFilePath, getNormalizedAbsolutePath(value as string, getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName!)); } else if (pathOptions && optionDefinition.type === ""list"" && optionDefinition.element.isFilePath) { result.set(name, (value as string[]).map(v => getRelativePathFromFile(pathOptions.configFilePath, getNormalizedAbsolutePath(v, getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName!))); } else { result.set(name, value); } } else { if (optionDefinition.type === ""list"") { result.set(name, (value as readonly (string | number)[]).map(element => getNameOfCompilerOptionValue(element, customTypeMap)!)); // TODO: GH#18217 } else { // There is a typeMap associated with this command-line option so use it to map value back to its name result.set(name, getNameOfCompilerOptionValue(value, customTypeMap)); } } } } } return result; } /** * Generate tsconfig configuration when running command line ""--init"" * @param options commandlineOptions to be generated into tsconfig.json * @internal */ export function generateTSConfig(options: CompilerOptions, newLine: string): string { type PresetValue = string | number | boolean | (string | number | boolean)[]; const tab = "" ""; const result: string[] = []; const allSetOptions = Object.keys(options).filter(k => k !== ""init"" && k !== ""help"" && k !== ""watch""); result.push(`{`); result.push(`${tab}// ${getLocaleSpecificMessage(Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file)}`); result.push(`${tab}""compilerOptions"": {`); emitHeader(Diagnostics.File_Layout); emitOption(""rootDir"", ""./src"", ""optional""); emitOption(""outDir"", ""./dist"", ""optional""); newline(); emitHeader(Diagnostics.Environment_Settings); emitHeader(Diagnostics.See_also_https_Colon_Slash_Slashaka_ms_Slashtsconfig_Slashmodule); emitOption(""module"", ModuleKind.NodeNext); emitOption(""target"", ScriptTarget.ESNext); emitOption(""types"", []); if (options.lib) { emitOption(""lib"", options.lib); } emitHeader(Diagnostics.For_nodejs_Colon); result.push(`${tab}${tab}// ""lib"": [""esnext""],`); result.push(`${tab}${tab}// ""types"": [""node""],`); emitHeader(Diagnostics.and_npm_install_D_types_Slashnode); newline(); emitHeader(Diagnostics.Other_Outputs); emitOption(""sourceMap"", /*defaultValue*/ true); emitOption(""declaration"", /*defaultValue*/ true); emitOption(""declarationMap"", /*defaultValue*/ true); newline(); emitHeader(Diagnostics.Stricter_Typechecking_Options); emitOption(""noUncheckedIndexedAccess"", /*defaultValue*/ true); emitOption(""exactOptionalPropertyTypes"", /*defaultValue*/ true); newline(); emitHeader(Diagnostics.Style_Options); emitOption(""noImplicitReturns"", /*defaultValue*/ true, ""optional""); emitOption(""noImplicitOverride"", /*defaultValue*/ true, ""optional""); emitOption(""noUnusedLocals"", /*defaultValue*/ true, ""optional""); emitOption(""noUnusedParameters"", /*defaultValue*/ true, ""optional""); emitOption(""noFallthroughCasesInSwitch"", /*defaultValue*/ true, ""optional""); emitOption(""noPropertyAccessFromIndexSignature"", /*defaultValue*/ true, ""optional""); newline(); emitHeader(Diagnostics.Recommended_Options); emitOption(""strict"", /*defaultValue*/ true); emitOption(""jsx"", JsxEmit.ReactJSX); emitOption(""verbatimModuleSyntax"", /*defaultValue*/ true); emitOption(""isolatedModules"", /*defaultValue*/ true); emitOption(""noUncheckedSideEffectImports"", /*defaultValue*/ true); emitOption(""moduleDetection"", ModuleDetectionKind.Force); emitOption(""skipLibCheck"", /*defaultValue*/ true); // Write any user-provided options we haven't already if (allSetOptions.length > 0) { newline(); while (allSetOptions.length > 0) { emitOption(allSetOptions[0], options[allSetOptions[0]]); } } function newline() { result.push(""""); } function emitHeader(header: DiagnosticMessage) { result.push(`${tab}${tab}// ${getLocaleSpecificMessage(header)}`); } // commented = 'always': Always comment this out, even if it's on commandline // commented = 'optional': Comment out unless it's on commandline // commented = 'never': Never comment this out function emitOption(setting: K, defaultValue: CompilerOptions[K], commented: ""always"" | ""optional"" | ""never"" = ""never"") { const existingOptionIndex = allSetOptions.indexOf(setting); if (existingOptionIndex >= 0) { allSetOptions.splice(existingOptionIndex, 1); } let comment: boolean; if (commented === ""always"") { comment = true; } else if (commented === ""never"") { comment = false; } else { comment = !hasProperty(options, setting); } const value = (options[setting] ?? defaultValue) as PresetValue; if (comment) { result.push(`${tab}${tab}// ""${setting}"": ${formatValueOrArray(setting, value)},`); } else { result.push(`${tab}${tab}""${setting}"": ${formatValueOrArray(setting, value)},`); } } function formatValueOrArray(settingName: string, value: PresetValue): string { const option = optionDeclarations.filter(c => c.name === settingName)[0]; if (!option) Debug.fail(`No option named ${settingName}?`); const map = (option.type instanceof Map) ? option.type : undefined; if (isArray(value)) { // eslint-disable-next-line local/no-in-operator const map = (""element"" in option && (option.element.type instanceof Map)) ? option.element.type : undefined; return `[${value.map(v => formatSingleValue(v, map)).join("", "")}]`; } else { return formatSingleValue(value, map); } } function formatSingleValue(value: PresetValue, map: Map | undefined) { if (map) { value = getNameOfCompilerOptionValue(value as string | number, map) ?? Debug.fail(`No matching value of ${value}`); } return JSON.stringify(value); } result.push(`${tab}}`); result.push(`}`); result.push(``); return result.join(newLine); } /** @internal */ export function convertToOptionsWithAbsolutePaths(options: CompilerOptions, toAbsolutePath: (path: string) => string): CompilerOptions { const result: CompilerOptions = {}; const optionsNameMap = getOptionsNameMap().optionsNameMap; for (const name in options) { if (hasProperty(options, name)) { result[name] = convertToOptionValueWithAbsolutePaths( optionsNameMap.get(name.toLowerCase()), options[name] as CompilerOptionsValue, toAbsolutePath, ); } } if (result.configFilePath) { result.configFilePath = toAbsolutePath(result.configFilePath); } return result; } function convertToOptionValueWithAbsolutePaths(option: CommandLineOption | undefined, value: CompilerOptionsValue, toAbsolutePath: (path: string) => string) { if (option && !isNullOrUndefined(value)) { if (option.type === ""list"") { const values = value as readonly string[]; if (option.element.isFilePath && values.length) { return values.map(toAbsolutePath); } } else if (option.isFilePath) { return toAbsolutePath(value as string); } Debug.assert(option.type !== ""listOrElement""); } return value; } /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse * @param host Instance of ParseConfigHost used to enumerate files in folder. * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: readonly FileExtensionInfo[], extendedConfigCache?: Map, existingWatchOptions?: WatchOptions): ParsedCommandLine { return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache); } /** * Parse the contents of a config file (tsconfig.json). * @param jsonNode The contents of the config file to parse * @param host Instance of ParseConfigHost used to enumerate files in folder. * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ export function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: readonly FileExtensionInfo[], extendedConfigCache?: Map, existingWatchOptions?: WatchOptions): ParsedCommandLine { tracing?.push(tracing.Phase.Parse, ""parseJsonSourceFileConfigFileContent"", { path: sourceFile.fileName }); const result = parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache); tracing?.pop(); return result; } /** @internal */ export function setConfigFileInOptions(options: CompilerOptions, configFile: TsConfigSourceFile | undefined): void { if (configFile) { Object.defineProperty(options, ""configFile"", { enumerable: false, writable: false, value: configFile }); } } function isNullOrUndefined(x: any): x is null | undefined { // eslint-disable-line no-restricted-syntax return x === undefined || x === null; // eslint-disable-line no-restricted-syntax } function directoryOfCombinedPath(fileName: string, basePath: string) { // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical // until consistent casing errors are reported return getDirectoryPath(getNormalizedAbsolutePath(fileName, basePath)); } const defaultIncludeSpec = ""**/*""; /** * Parse the contents of a config file from json or json source file (tsconfig.json). * @param json The contents of the config file to parse * @param sourceFile sourceFile corresponding to the Json * @param host Instance of ParseConfigHost used to enumerate files in folder. * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir * @param resolutionStack Only present for backwards-compatibility. Should be empty. */ function parseJsonConfigFileContentWorker( json: any, sourceFile: TsConfigSourceFile | undefined, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, existingWatchOptions: WatchOptions | undefined, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: readonly FileExtensionInfo[] = [], extendedConfigCache?: Map, ): ParsedCommandLine { Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); const errors: Diagnostic[] = []; const parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache); const { raw } = parsedConfig; const options = handleOptionConfigDirTemplateSubstitution( extend(existingOptions, parsedConfig.options || {}), configDirTemplateSubstitutionOptions, basePath, ) as CompilerOptions; const watchOptions = handleWatchOptionsConfigDirTemplateSubstitution( existingWatchOptions && parsedConfig.watchOptions ? extend(existingWatchOptions, parsedConfig.watchOptions) : parsedConfig.watchOptions || existingWatchOptions, basePath, ); options.configFilePath = configFileName && normalizeSlashes(configFileName); const basePathForFileNames = normalizePath(configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath); const configFileSpecs = getConfigFileSpecs(); if (sourceFile) sourceFile.configFileSpecs = configFileSpecs; setConfigFileInOptions(options, sourceFile); return { options, watchOptions, fileNames: getFileNames(basePathForFileNames), projectReferences: getProjectReferences(basePathForFileNames), typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), raw, errors, // Wildcard directories (provided as part of a wildcard path) are stored in a // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. wildcardDirectories: getWildcardDirectories(configFileSpecs, basePathForFileNames, host.useCaseSensitiveFileNames), compileOnSave: !!raw.compileOnSave, }; function getConfigFileSpecs(): ConfigFileSpecs { const referencesOfRaw = getPropFromRaw(""references"", element => typeof element === ""object"", ""object""); const filesSpecs = toPropValue(getSpecsFromRaw(""files"")); if (filesSpecs) { const hasZeroOrNoReferences = referencesOfRaw === ""no-prop"" || isArray(referencesOfRaw) && referencesOfRaw.length === 0; const hasExtends = hasProperty(raw, ""extends""); if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { if (sourceFile) { const fileName = configFileName || ""tsconfig.json""; const diagnosticMessage = Diagnostics.The_files_list_in_config_file_0_is_empty; const nodeValue = forEachTsConfigPropArray(sourceFile, ""files"", property => property.initializer); const error = createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, nodeValue, diagnosticMessage, fileName); errors.push(error); } else { createCompilerDiagnosticOnlyIfJson(Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || ""tsconfig.json""); } } } let includeSpecs = toPropValue(getSpecsFromRaw(""include"")); const excludeOfRaw = getSpecsFromRaw(""exclude""); let isDefaultIncludeSpec = false; let excludeSpecs = toPropValue(excludeOfRaw); if (excludeOfRaw === ""no-prop"") { const outDir = options.outDir; const declarationDir = options.declarationDir; if (outDir || declarationDir) { excludeSpecs = filter([outDir, declarationDir], d => !!d) as string[]; } } if (filesSpecs === undefined && includeSpecs === undefined) { includeSpecs = [defaultIncludeSpec]; isDefaultIncludeSpec = true; } let validatedIncludeSpecsBeforeSubstitution: readonly string[] | undefined, validatedExcludeSpecsBeforeSubstitution: readonly string[] | undefined; let validatedIncludeSpecs: readonly string[] | undefined, validatedExcludeSpecs: readonly string[] | undefined; // The exclude spec list is converted into a regular expression, which allows us to quickly // test whether a file or directory should be excluded before recursively traversing the // file system. if (includeSpecs) { validatedIncludeSpecsBeforeSubstitution = validateSpecs(includeSpecs, errors, /*disallowTrailingRecursion*/ true, sourceFile, ""include""); validatedIncludeSpecs = getSubstitutedStringArrayWithConfigDirTemplate( validatedIncludeSpecsBeforeSubstitution, basePathForFileNames, ) || validatedIncludeSpecsBeforeSubstitution; } if (excludeSpecs) { validatedExcludeSpecsBeforeSubstitution = validateSpecs(excludeSpecs, errors, /*disallowTrailingRecursion*/ false, sourceFile, ""exclude""); validatedExcludeSpecs = getSubstitutedStringArrayWithConfigDirTemplate( validatedExcludeSpecsBeforeSubstitution, basePathForFileNames, ) || validatedExcludeSpecsBeforeSubstitution; } const validatedFilesSpecBeforeSubstitution = filter(filesSpecs, isString); const validatedFilesSpec = getSubstitutedStringArrayWithConfigDirTemplate( validatedFilesSpecBeforeSubstitution, basePathForFileNames, ) || validatedFilesSpecBeforeSubstitution; return { filesSpecs, includeSpecs, excludeSpecs, validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs, validatedFilesSpecBeforeSubstitution, validatedIncludeSpecsBeforeSubstitution, validatedExcludeSpecsBeforeSubstitution, isDefaultIncludeSpec, }; } function getFileNames(basePath: string): string[] { const fileNames = getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, extraFileExtensions); if (shouldReportNoInputFiles(fileNames, canJsonReportNoInputFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); } return fileNames; } function getProjectReferences(basePath: string): readonly ProjectReference[] | undefined { let projectReferences: ProjectReference[] | undefined; const referencesOfRaw = getPropFromRaw(""references"", element => typeof element === ""object"", ""object""); if (isArray(referencesOfRaw)) { for (const ref of referencesOfRaw) { if (typeof ref.path !== ""string"") { createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, ""reference.path"", ""string""); } else { (projectReferences || (projectReferences = [])).push({ path: getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, circular: ref.circular, }); } } } return projectReferences; } type PropOfRaw = readonly T[] | ""not-array"" | ""no-prop""; function toPropValue(specResult: PropOfRaw) { return isArray(specResult) ? specResult : undefined; } function getSpecsFromRaw(prop: ""files"" | ""include"" | ""exclude""): PropOfRaw { return getPropFromRaw(prop, isString, ""string""); } function getPropFromRaw(prop: ""files"" | ""include"" | ""exclude"" | ""references"", validateElement: (value: unknown) => boolean, elementTypeName: string): PropOfRaw { if (hasProperty(raw, prop) && !isNullOrUndefined(raw[prop])) { if (isArray(raw[prop])) { const result = raw[prop] as T[]; if (!sourceFile && !every(result, validateElement)) { errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, elementTypeName)); } return result; } else { createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, ""Array""); return ""not-array""; } } return ""no-prop""; } function createCompilerDiagnosticOnlyIfJson(message: DiagnosticMessage, ...args: DiagnosticArguments) { if (!sourceFile) { errors.push(createCompilerDiagnostic(message, ...args)); } } } /** @internal */ export function handleWatchOptionsConfigDirTemplateSubstitution( watchOptions: WatchOptions | undefined, basePath: string, ) { return handleOptionConfigDirTemplateSubstitution(watchOptions, configDirTemplateSubstitutionWatchOptions, basePath) as WatchOptions | undefined; } function handleOptionConfigDirTemplateSubstitution( options: OptionsBase | undefined, optionDeclarations: readonly CommandLineOption[], basePath: string, ) { if (!options) return options; let result: OptionsBase | undefined; for (const option of optionDeclarations) { if (options[option.name] !== undefined) { const value = options[option.name]; switch (option.type) { case ""string"": Debug.assert(option.isFilePath); if (startsWithConfigDirTemplate(value)) { setOptionValue(option, getSubstitutedPathWithConfigDirTemplate(value, basePath)); } break; case ""list"": Debug.assert(option.element.isFilePath); const listResult = getSubstitutedStringArrayWithConfigDirTemplate(value as string[], basePath); if (listResult) setOptionValue(option, listResult); break; case ""object"": Debug.assert(option.name === ""paths""); const objectResult = getSubstitutedMapLikeOfStringArrayWithConfigDirTemplate(value as MapLike, basePath); if (objectResult) setOptionValue(option, objectResult); break; default: Debug.fail(""option type not supported""); } } } return result || options; function setOptionValue(option: CommandLineOption, value: CompilerOptionsValue) { (result ??= assign({}, options))[option.name] = value; } } const configDirTemplate = `\${configDir}`; function startsWithConfigDirTemplate(value: any): value is string { return isString(value) && startsWith(value, configDirTemplate, /*ignoreCase*/ true); } function getSubstitutedPathWithConfigDirTemplate(value: string, basePath: string) { return getNormalizedAbsolutePath(value.replace(configDirTemplate, ""./""), basePath); } function getSubstitutedStringArrayWithConfigDirTemplate(list: readonly string[] | undefined, basePath: string) { if (!list) return list; let result: string[] | undefined; list.forEach((element, index) => { if (!startsWithConfigDirTemplate(element)) return; (result ??= list.slice())[index] = getSubstitutedPathWithConfigDirTemplate(element, basePath); }); return result; } function getSubstitutedMapLikeOfStringArrayWithConfigDirTemplate(mapLike: MapLike, basePath: string) { let result: MapLike | undefined; const ownKeys = getOwnKeys(mapLike); ownKeys.forEach(key => { if (!isArray(mapLike[key])) return; const subStitution = getSubstitutedStringArrayWithConfigDirTemplate(mapLike[key], basePath); if (!subStitution) return; (result ??= assign({}, mapLike))[key] = subStitution; }); return result; } function isErrorNoInputFiles(error: Diagnostic) { return error.code === Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } function getErrorForNoInputFiles({ includeSpecs, excludeSpecs }: ConfigFileSpecs, configFileName: string | undefined) { return createCompilerDiagnostic( Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || ""tsconfig.json"", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []), ); } function shouldReportNoInputFiles(fileNames: string[], canJsonReportNoInutFiles: boolean, resolutionStack?: Path[]) { return fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); } /** @internal */ export function isSolutionConfig(config: ParsedCommandLine): boolean { return !config.fileNames.length && hasProperty(config.raw, ""references""); } /** @internal */ export function canJsonReportNoInputFiles(raw: any): boolean { return !hasProperty(raw, ""files"") && !hasProperty(raw, ""references""); } /** @internal */ export function updateErrorForNoInputFiles( fileNames: string[], configFileName: string, configFileSpecs: ConfigFileSpecs, configParseDiagnostics: Diagnostic[], canJsonReportNoInutFiles: boolean, ): boolean { const existingErrors = configParseDiagnostics.length; if (shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles)) { configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); } else { filterMutate(configParseDiagnostics, error => !isErrorNoInputFiles(error)); } return existingErrors !== configParseDiagnostics.length; } export interface ParsedTsconfig { raw: any; options?: CompilerOptions; watchOptions?: WatchOptions; typeAcquisition?: TypeAcquisition; /** * Note that the case of the config path has not yet been normalized, as no files have been imported into the project yet */ extendedConfigPath?: string | string[]; } function isSuccessfulParsedTsconfig(value: ParsedTsconfig) { return !!value.options; } interface ExtendsResult { options: CompilerOptions; watchOptions?: WatchOptions; watchOptionsCopied?: boolean; include?: string[]; exclude?: string[]; files?: string[]; compileOnSave?: boolean; extendedSourceFiles?: Set; } /** * This *just* extracts options/include/exclude/files out of a config file. * It does *not* resolve the included files. */ function parseConfig( json: any, sourceFile: TsConfigSourceFile | undefined, host: ParseConfigHost, basePath: string, configFileName: string | undefined, resolutionStack: string[], errors: Diagnostic[], extendedConfigCache?: Map, ): ParsedTsconfig { basePath = normalizeSlashes(basePath); const resolvedPath = getNormalizedAbsolutePath(configFileName || """", basePath); if (resolutionStack.includes(resolvedPath)) { errors.push(createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join("" -> ""))); return { raw: json || convertToObject(sourceFile!, errors) }; } const ownConfig = json ? parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : parseOwnConfigOfJsonSourceFile(sourceFile!, host, basePath, configFileName, errors); if (ownConfig.options?.paths) { // If we end up needing to resolve relative paths from 'paths' relative to // the config file location, we'll need to know where that config file was. // Since 'paths' can be inherited from an extended config in another directory, // we wouldn't know which directory to use unless we store it here. ownConfig.options.pathsBasePath = basePath; } if (ownConfig.extendedConfigPath) { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); const result: ExtendsResult = { options: {} }; if (isString(ownConfig.extendedConfigPath)) { applyExtendedConfig(result, ownConfig.extendedConfigPath); } else { ownConfig.extendedConfigPath.forEach(extendedConfigPath => applyExtendedConfig(result, extendedConfigPath)); } if (result.include) ownConfig.raw.include = result.include; if (result.exclude) ownConfig.raw.exclude = result.exclude; if (result.files) ownConfig.raw.files = result.files; if (ownConfig.raw.compileOnSave === undefined && result.compileOnSave) ownConfig.raw.compileOnSave = result.compileOnSave; if (sourceFile && result.extendedSourceFiles) sourceFile.extendedSourceFiles = arrayFrom(result.extendedSourceFiles.keys()); ownConfig.options = assign(result.options, ownConfig.options); ownConfig.watchOptions = ownConfig.watchOptions && result.watchOptions ? assignWatchOptions(result, ownConfig.watchOptions) : ownConfig.watchOptions || result.watchOptions; } return ownConfig; function applyExtendedConfig(result: ExtendsResult, extendedConfigPath: string) { const extendedConfig = getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache, result); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { const extendsRaw = extendedConfig.raw; let relativeDifference: string | undefined; const setPropertyInResultIfNotUndefined = ( [MASK] : ""include"" | ""exclude"" | ""files"") => { if (ownConfig.raw[ [MASK] ]) return; // No need to calculate if already set in own config if (extendsRaw[ [MASK] ]) { result[ [MASK] ] = map(extendsRaw[ [MASK] ], (path: string) => startsWithConfigDirTemplate(path) || isRootedDiskPath(path) ? path : combinePaths( relativeDifference ||= convertToRelativePath(getDirectoryPath(extendedConfigPath), basePath, createGetCanonicalFileName(host.useCaseSensitiveFileNames)), path, )); } }; setPropertyInResultIfNotUndefined(""include""); setPropertyInResultIfNotUndefined(""exclude""); setPropertyInResultIfNotUndefined(""files""); if (extendsRaw.compileOnSave !== undefined) { result.compileOnSave = extendsRaw.compileOnSave; } assign(result.options, extendedConfig.options); result.watchOptions = result.watchOptions && extendedConfig.watchOptions ? assignWatchOptions(result, extendedConfig.watchOptions) : result.watchOptions || extendedConfig.watchOptions; // TODO extend type typeAcquisition } } function assignWatchOptions(result: ExtendsResult, watchOptions: WatchOptions) { if (result.watchOptionsCopied) return assign(result.watchOptions!, watchOptions); result.watchOptionsCopied = true; return assign({}, result.watchOptions, watchOptions); } } function parseOwnConfigOfJson( json: any, host: ParseConfigHost, basePath: string, configFileName: string | undefined, errors: Diagnostic[], ): ParsedTsconfig { if (hasProperty(json, ""excludes"")) { errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } const options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); const typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition, basePath, errors, configFileName); const watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors); json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); const extendedConfigPath = json.extends || json.extends === """" ? getExtendsConfigPathOrArray(json.extends, host, basePath, configFileName, errors) : undefined; return { raw: json, options, watchOptions, typeAcquisition, extendedConfigPath }; } function getExtendsConfigPathOrArray( value: CompilerOptionsValue, host: ParseConfigHost, basePath: string, configFileName: string | undefined, errors: Diagnostic[], propertyAssignment?: PropertyAssignment, valueExpression?: Expression, sourceFile?: JsonSourceFile, ) { let extendedConfigPath: string | string[] | undefined; const newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; if (isString(value)) { extendedConfigPath = getExtendsConfigPath( value, host, newBase, errors, valueExpression, sourceFile, ); } else if (isArray(value)) { extendedConfigPath = []; for (let index = 0; index < (value as unknown[]).length; index++) { const fileName = (value as unknown[])[index]; if (isString(fileName)) { extendedConfigPath = append( extendedConfigPath, getExtendsConfigPath( fileName, host, newBase, errors, (valueExpression as ArrayLiteralExpression | undefined)?.elements[index], sourceFile, ), ); } else { convertJsonOption(extendsOptionDeclaration.element, value, basePath, errors, propertyAssignment, (valueExpression as ArrayLiteralExpression | undefined)?.elements[index], sourceFile); } } } else { convertJsonOption(extendsOptionDeclaration, value, basePath, errors, propertyAssignment, valueExpression, sourceFile); } return extendedConfigPath; } function parseOwnConfigOfJsonSourceFile( sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, configFileName: string | undefined, errors: Diagnostic[], ): ParsedTsconfig { const options = getDefaultCompilerOptions(configFileName); let typeAcquisition: TypeAcquisition | undefined; let watchOptions: WatchOptions | undefined; let extendedConfigPath: string | string[] | undefined; let rootCompilerOptions: PropertyName[] | undefined; const rootOptions = getTsconfigRootOptionsMap(); const json = convertConfigFileToObject( sourceFile, errors, { rootOptions, onPropertySet }, ); if (!typeAcquisition) { typeAcquisition = getDefaultTypeAcquisition(configFileName); } if (rootCompilerOptions && json && json.compilerOptions === undefined) { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, rootCompilerOptions[0], Diagnostics._0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file, getTextOfPropertyName(rootCompilerOptions[0]) as string)); } return { raw: json, options, watchOptions, typeAcquisition, extendedConfigPath }; function onPropertySet( keyText: string, value: any, propertyAssignment: PropertyAssignment, parentOption: TsConfigOnlyOption | undefined, option: CommandLineOption | undefined, ) { // Ensure value is verified except for extends which is handled in its own way for error reporting if (option && option !== extendsOptionDeclaration) value = convertJsonOption(option, value, basePath, errors, propertyAssignment, propertyAssignment.initializer, sourceFile); if (parentOption?.name) { if (option) { let currentOption; if (parentOption === compilerOptionsDeclaration) currentOption = options; else if (parentOption === watchOptionsDeclaration) currentOption = watchOptions ??= {}; else if (parentOption === typeAcquisitionDeclaration) currentOption = typeAcquisition ??= getDefaultTypeAcquisition(configFileName); else Debug.fail(""Unknown option""); currentOption[option.name] = value; } else if (keyText && parentOption?.extraKeyDiagnostics) { if (parentOption.elementOptions) { errors.push(createUnknownOptionError( keyText, parentOption.extraKeyDiagnostics, /*unknownOptionErrorText*/ undefined, propertyAssignment.name, sourceFile, )); } else { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, propertyAssignment.name, parentOption.extraKeyDiagnostics.unknownOptionDiagnostic, keyText)); } } } else if (parentOption === rootOptions) { if (option === extendsOptionDeclaration) { extendedConfigPath = getExtendsConfigPathOrArray(value, host, basePath, configFileName, errors, propertyAssignment, propertyAssignment.initializer, sourceFile); } else if (!option) { if (keyText === ""excludes"") { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, propertyAssignment.name, Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } if (find(commandOptionsWithoutBuild, opt => opt.name === keyText)) { rootCompilerOptions = append(rootCompilerOptions, propertyAssignment.name); } } } } } function getExtendsConfigPath( extendedConfig: string, host: ParseConfigHost, basePath: string, errors: Diagnostic[], valueExpression: Expression | undefined, sourceFile: TsConfigSourceFile | undefined, ) { extendedConfig = normalizeSlashes(extendedConfig); if (isRootedDiskPath(extendedConfig) || startsWith(extendedConfig, ""./"") || startsWith(extendedConfig, ""../"")) { let extendedConfigPath = getNormalizedAbsolutePath(extendedConfig, basePath); if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, Extension.Json)) { extendedConfigPath = `${extendedConfigPath}.json`; if (!host.fileExists(extendedConfigPath)) { errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.File_0_not_found, extendedConfig)); return undefined; } } return extendedConfigPath; } // If the path isn't a rooted or relative path, resolve like a module const resolved = nodeNextJsonConfigResolver(extendedConfig, combinePaths(basePath, ""tsconfig.json""), host); if (resolved.resolvedModule) { return resolved.resolvedModule.resolvedFileName; } if (extendedConfig === """") { errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.Compiler_option_0_cannot_be_given_an_empty_string, ""extends"")); } else { errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.File_0_not_found, extendedConfig)); } return undefined; } export interface ExtendedConfigCacheEntry { extendedResult: TsConfigSourceFile; extendedConfig: ParsedTsconfig | undefined; } function getExtendedConfig( sourceFile: TsConfigSourceFile | undefined, extendedConfigPath: string, host: ParseConfigHost, resolutionStack: string[], errors: Diagnostic[], extendedConfigCache: Map | undefined, result: ExtendsResult, ): ParsedTsconfig | undefined { const path = host.useCaseSensitiveFileNames ? extendedConfigPath : toFileNameLowerCase(extendedConfigPath); let value: ExtendedConfigCacheEntry | undefined; let extendedResult: TsConfigSourceFile; let extendedConfig: ParsedTsconfig | undefined; if (extendedConfigCache && (value = extendedConfigCache.get(path))) { ({ extendedResult, extendedConfig } = value); } else { extendedResult = readJsonConfigFile(extendedConfigPath, path => host.readFile(path)); if (!extendedResult.parseDiagnostics.length) { extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, getDirectoryPath(extendedConfigPath), getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); } if (extendedConfigCache) { extendedConfigCache.set(path, { extendedResult, extendedConfig }); } } if (sourceFile) { (result.extendedSourceFiles ??= new Set()).add(extendedResult.fileName); if (extendedResult.extendedSourceFiles) { for (const extenedSourceFile of extendedResult.extendedSourceFiles) { result.extendedSourceFiles.add(extenedSourceFile); } } } if (extendedResult.parseDiagnostics.length) { errors.push(...extendedResult.parseDiagnostics); return undefined; } return extendedConfig!; } function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean { if (!hasProperty(jsonOption, compileOnSaveCommandLineOption.name)) { return false; } const result = convertJsonOption(compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); return typeof result === ""boolean"" && result; } export function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; } { const errors: Diagnostic[] = []; const options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); return { options, errors }; } export function convertTypeAcquisitionFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: TypeAcquisition; errors: Diagnostic[]; } { const errors: Diagnostic[] = []; const options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); return { options, errors }; } function getDefaultCompilerOptions(configFileName?: string) { const options: CompilerOptions = configFileName && getBaseFileName(configFileName) === ""jsconfig.json"" ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } : {}; return options; } function convertCompilerOptionsFromJsonWorker(jsonOptions: any, basePath: string, errors: Diagnostic[], configFileName?: string): CompilerOptions { const options = getDefaultCompilerOptions(configFileName); convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, compilerOptionsDidYouMeanDiagnostics, errors); if (configFileName) { options.configFilePath = normalizeSlashes(configFileName); } return options; } function getDefaultTypeAcquisition(configFileName?: string): TypeAcquisition { return { enable: !!configFileName && getBaseFileName(configFileName) === ""jsconfig.json"", include: [], exclude: [] }; } function convertTypeAcquisitionFromJsonWorker(jsonOptions: any, basePath: string, errors: Diagnostic[], configFileName?: string): TypeAcquisition { const options = getDefaultTypeAcquisition(configFileName); convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), jsonOptions, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors); return options; } function convertWatchOptionsFromJsonWorker(jsonOptions: any, basePath: string, errors: Diagnostic[]): WatchOptions | undefined { return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors); } function convertOptionsFromJson(optionsNameMap: Map, jsonOptions: any, basePath: string, defaultOptions: undefined, diagnostics: DidYouMeanOptionsDiagnostics, errors: Diagnostic[]): WatchOptions | undefined; function convertOptionsFromJson(optionsNameMap: Map, jsonOptions: any, basePath: string, defaultOptions: CompilerOptions | TypeAcquisition, diagnostics: DidYouMeanOptionsDiagnostics, errors: Diagnostic[]): CompilerOptions | TypeAcquisition; function convertOptionsFromJson(optionsNameMap: Map, jsonOptions: any, basePath: string, defaultOptions: CompilerOptions | TypeAcquisition | WatchOptions | undefined, diagnostics: DidYouMeanOptionsDiagnostics, errors: Diagnostic[]) { if (!jsonOptions) { return; } for (const id in jsonOptions) { const opt = optionsNameMap.get(id); if (opt) { (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } else { errors.push(createUnknownOptionError(id, diagnostics)); } } return defaultOptions; } function createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile: TsConfigSourceFile | undefined, node: Node | undefined, message: DiagnosticMessage, ...args: DiagnosticArguments) { return sourceFile && node ? createDiagnosticForNodeInSourceFile(sourceFile, node, message, ...args) : createCompilerDiagnostic(message, ...args); } /** @internal */ export function convertJsonOption( opt: CommandLineOption, value: any, basePath: string, errors: Diagnostic[], propertyAssignment?: PropertyAssignment, valueExpression?: Expression, sourceFile?: TsConfigSourceFile, ): CompilerOptionsValue { if (opt.isCommandLineOnly) { errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, propertyAssignment?.name, Diagnostics.Option_0_can_only_be_specified_on_command_line, opt.name)); return undefined; } if (isCompilerOptionsValue(opt, value)) { const optType = opt.type; if ((optType === ""list"") && isArray(value)) { return convertJsonOptionOfListType(opt, value, basePath, errors, propertyAssignment, valueExpression as ArrayLiteralExpression | undefined, sourceFile); } else if (optType === ""listOrElement"") { return isArray(value) ? convertJsonOptionOfListType(opt, value, basePath, errors, propertyAssignment, valueExpression as ArrayLiteralExpression | undefined, sourceFile) : convertJsonOption(opt.element, value, basePath, errors, propertyAssignment, valueExpression, sourceFile); } else if (!isString(opt.type)) { return convertJsonOptionOfCustomType(opt as CommandLineOptionOfCustomType, value as string, errors, valueExpression, sourceFile); } const validatedValue = validateJsonOptionValue(opt, value, errors, valueExpression, sourceFile); return isNullOrUndefined(validatedValue) ? validatedValue : normalizeNonListOptionValue(opt, basePath, validatedValue); } else { errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); } } function normalizeNonListOptionValue(option: CommandLineOption, basePath: string, value: any): CompilerOptionsValue { if (option.isFilePath) { value = normalizeSlashes(value); value = !startsWithConfigDirTemplate(value) ? getNormalizedAbsolutePath(value, basePath) : value; if (value === """") { value = "".""; } } return value; } function validateJsonOptionValue( opt: CommandLineOption, value: T, errors: Diagnostic[], valueExpression?: Expression, sourceFile?: TsConfigSourceFile, ): T | undefined { if (isNullOrUndefined(value)) return undefined; const d = opt.extraValidation?.(value); if (!d) return value; errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, ...d)); return undefined; } function convertJsonOptionOfCustomType( opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[], valueExpression?: Expression, sourceFile?: TsConfigSourceFile, ) { if (isNullOrUndefined(value)) return undefined; const key = value.toLowerCase(); const val = opt.type.get(key); if (val !== undefined) { return validateJsonOptionValue(opt, val, errors, valueExpression, sourceFile); } else { errors.push(createDiagnosticForInvalidCustomType(opt, (message, ...args) => createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, message, ...args))); } } function convertJsonOptionOfListType( option: CommandLineOptionOfListType, values: readonly any[], basePath: string, errors: Diagnostic[], propertyAssignment: PropertyAssignment | undefined, valueExpression: ArrayLiteralExpression | undefined, sourceFile: TsConfigSourceFile | undefined, ): any[] { return filter(map(values, (v, index) => convertJsonOption(option.element, v, basePath, errors, propertyAssignment, valueExpression?.elements[index], sourceFile)), v => option.listPreserveFalsyValues ? true : !!v); } /** * Tests for a path that ends in a recursive directory wildcard. * Matches **, \**, **\, and \**\, but not a**b. * * NOTE: used \ in place of / above to avoid issues with multiline comments. * * Breakdown: * (^|\/) # matches either the beginning of the string or a directory separator. * \*\* # matches the recursive directory wildcard ""**"". * \/?$ # matches an optional trailing directory separator at the end of the string. */ const invalidTrailingRecursionPattern = /(?:^|\/)\*\*\/?$/; /** * Matches the portion of a wildcard path that does not contain wildcards. * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d. * * NOTE: used \ in place of / above to avoid issues with multiline comments. * * Breakdown: * ^ # matches the beginning of the string * [^*?]* # matches any number of non-wildcard characters * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by * # a path component that contains at least one wildcard character (* or ?). */ const wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; /** * Gets the file names from the provided config file specs that contain, files, include, exclude and * other properties needed to resolve the file names * @param configFileSpecs The config file specs extracted with file names to include, wildcards to include/exclude and other details * @param basePath The base path for any relative file specifications. * @param options Compiler options. * @param host The host used to resolve files and directories. * @param extraFileExtensions optionaly file extra file extension information from host * * @internal */ export function getFileNamesFromConfigSpecs( configFileSpecs: ConfigFileSpecs, basePath: string, options: CompilerOptions, host: ParseConfigHost, extraFileExtensions: readonly FileExtensionInfo[] = emptyArray, ): string[] { basePath = normalizePath(basePath); const keyMapper = createGetCanonicalFileName(host.useCaseSensitiveFileNames); // Literal file names (provided via the ""files"" array in tsconfig.json) are stored in a // file map with a possibly case insensitive key. We use this map later when when including // wildcard paths. const literalFileMap = new Map(); // Wildcard paths (provided via the ""includes"" array in tsconfig.json) are stored in a // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. const wildcardFileMap = new Map(); // Wildcard paths of json files (provided via the ""includes"" array in tsconfig.json) are stored in a // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard of *.json kind const wildCardJsonFileMap = new Map(); const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = configFileSpecs; // Rather than re-query this for each file and filespec, we query the supported extensions // once and store it on the expansion context. const supportedExtensions = getSupportedExtensions(options, extraFileExtensions); const supportedExtensionsWithJsonIfResolveJsonModule = getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An ""include"" or ""exclude"" specification cannot // remove a literal file. if (validatedFilesSpec) { for (const fileName of validatedFilesSpec) { const file = getNormalizedAbsolutePath(fileName, basePath); literalFileMap.set(keyMapper(file), file); } } let jsonOnlyIncludeRegexes: readonly RegExp[] | undefined; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { for (const file of host.readDirectory(basePath, flatten(supportedExtensionsWithJsonIfResolveJsonModule), validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined)) { if (fileExtensionIs(file, Extension.Json)) { // Valid only if *.json specified if (!jsonOnlyIncludeRegexes) { const includes = validatedIncludeSpecs.filter(s => endsWith(s, Extension.Json)); const includeFilePatterns = map(getRegularExpressionsForWildcards(includes, basePath, ""files""), pattern => `^${pattern}$`); jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(pattern => getRegexFromPattern(pattern, host.useCaseSensitiveFileNames)) : emptyArray; } const includeIndex = findIndex(jsonOnlyIncludeRegexes, re => re.test(file)); if (includeIndex !== -1) { const key = keyMapper(file); if (!literalFileMap.has(key) && !wildCardJsonFileMap.has(key)) { wildCardJsonFileMap.set(key, file); } } continue; } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // // This handles cases where we may encounter both .ts and // .d.ts (or .js if ""allowJs"" is enabled) in the same // directory when they are compilation outputs. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the // ""include"" array. If there is a lower priority extension in the // same directory, we should remove it. removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); const key = keyMapper(file); if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } } } const literalFiles = arrayFrom(literalFileMap.values()); const wildcardFiles = arrayFrom(wildcardFileMap.values()); return literalFiles.concat(wildcardFiles, arrayFrom(wildCardJsonFileMap.values())); } /** @internal */ export function isExcludedFile( pathToCheck: string, spec: ConfigFileSpecs, basePath: string, useCaseSensitiveFileNames: boolean, currentDirectory: string, ): boolean { const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = spec; if (!length(validatedIncludeSpecs) || !length(validatedExcludeSpecs)) return false; basePath = normalizePath(basePath); const keyMapper = createGetCanonicalFileName(useCaseSensitiveFileNames); if (validatedFilesSpec) { for (const fileName of validatedFilesSpec) { if (keyMapper(getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck) return false; } } return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath); } function invalidDotDotAfterRecursiveWildcard(s: string) { // We used to use the regex /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/ to check for this case, but // in v8, that has polynomial performance because the recursive wildcard match - **/ - // can be matched in many arbitrary positions when multiple are present, resulting // in bad backtracking (and we don't care which is matched - just that some /.. segment // comes after some **/ segment). const wildcardIndex = startsWith(s, ""**/"") ? 0 : s.indexOf(""/**/""); if (wildcardIndex === -1) { return false; } const lastDotIndex = endsWith(s, ""/.."") ? s.length : s.lastIndexOf(""/../""); return lastDotIndex > wildcardIndex; } /** @internal */ export function matchesExclude( pathToCheck: string, excludeSpecs: readonly string[] | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string, ): boolean { return matchesExcludeWorker( pathToCheck, filter(excludeSpecs, spec => !invalidDotDotAfterRecursiveWildcard(spec)), useCaseSensitiveFileNames, currentDirectory, ); } /** @internal */ export function matchesExcludeWorker( pathToCheck: string, excludeSpecs: readonly string[] | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string, basePath?: string, ): boolean { const excludePattern = getRegularExpressionForWildcard(excludeSpecs, combinePaths(normalizePath(currentDirectory), basePath), ""exclude""); const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames); if (!excludeRegex) return false; if (excludeRegex.test(pathToCheck)) return true; return !hasExtension(pathToCheck) && excludeRegex.test(ensureTrailingDirectorySeparator(pathToCheck)); } function validateSpecs(specs: readonly string[], errors: Diagnostic[], disallowTrailingRecursion: boolean, jsonSourceFile: TsConfigSourceFile | undefined, specKey: string): readonly string[] { return specs.filter(spec => { if (!isString(spec)) return false; const diag = specToDiagnostic(spec, disallowTrailingRecursion); if (diag !== undefined) { errors.push(createDiagnostic(...diag)); } return diag === undefined; }); function createDiagnostic(message: DiagnosticMessage, spec: string): Diagnostic { const element = getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec); return createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(jsonSourceFile, element, message, spec); } } function specToDiagnostic(spec: CompilerOptionsValue, disallowTrailingRecursion?: boolean): [DiagnosticMessage, string] | undefined { Debug.assert(typeof spec === ""string""); if (disallowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { return [Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec]; } else if (invalidDotDotAfterRecursiveWildcard(spec)) { return [Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec]; } } /** * Gets directories in a set of include patterns that should be watched for changes. */ function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExcludeSpecs: exclude }: ConfigFileSpecs, basePath: string, useCaseSensitiveFileNames: boolean): MapLike { // We watch a directory recursively if it contains a wildcard anywhere in a directory segment // of the pattern: // // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler // // We watch a directory without recursion if it contains a wildcard in the file segment of // the pattern: // // /a/b/* - Watch /a/b directly to catch any new file // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z const rawExcludeRegex = getRegularExpressionForWildcard(exclude, basePath, ""exclude""); const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? """" : ""i""); const wildcardDirectories: MapLike = {}; const wildCardKeyToPath = new Map(); if (include !== undefined) { const recursiveKeys: CanonicalKey[] = []; for (const file of include) { const spec = normalizePath(combinePaths(basePath, file)); if (excludeRegex && excludeRegex.test(spec)) { continue; } const match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); if (match) { const { key, path, flags } = match; const existingPath = wildCardKeyToPath.get(key); const existingFlags = existingPath !== undefined ? wildcardDirectories[existingPath] : undefined; if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[existingPath !== undefined ? existingPath : path] = flags; if (existingPath === undefined) wildCardKeyToPath.set(key, path); if (flags === WatchDirectoryFlags.Recursive) { recursiveKeys.push(key); } } } } // Remove any subpaths under an existing recursively watched directory. for (const path in wildcardDirectories) { if (hasProperty(wildcardDirectories, path)) { for (const recursiveKey of recursiveKeys) { const key = toCanonicalKey(path, useCaseSensitiveFileNames); if (key !== recursiveKey && containsPath(recursiveKey, key, basePath, !useCaseSensitiveFileNames)) { delete wildcardDirectories[path]; } } } } } return wildcardDirectories; } type CanonicalKey = string & { __canonicalKey: never; }; function toCanonicalKey(path: string, useCaseSensitiveFileNames: boolean): CanonicalKey { return (useCaseSensitiveFileNames ? path : toFileNameLowerCase(path)) as CanonicalKey; } function getWildcardDirectoryFromSpec(spec: string, useCaseSensitiveFileNames: boolean): { key: CanonicalKey; path: string; flags: WatchDirectoryFlags; } | undefined { const match = wildcardDirectoryPattern.exec(spec); if (match) { // We check this with a few `indexOf` calls because 3 `indexOf`/`lastIndexOf` calls is // less algorithmically complex (roughly O(3n) worst-case) than the regex we used to use, // \/[^/]*?[*?][^/]*\/ which was polynominal in v8, since arbitrary sequences of wildcard // characters could match any of the central patterns, resulting in bad backtracking. const questionWildcardIndex = spec.indexOf(""?""); const starWildcardIndex = spec.indexOf(""*""); const lastDirectorySeperatorIndex = spec.lastIndexOf(directorySeparator); return { key: toCanonicalKey(match[0], useCaseSensitiveFileNames), path: match[0], flags: (questionWildcardIndex !== -1 && questionWildcardIndex < lastDirectorySeperatorIndex) || (starWildcardIndex !== -1 && starWildcardIndex < lastDirectorySeperatorIndex) ? WatchDirectoryFlags.Recursive : WatchDirectoryFlags.None, }; } if (isImplicitGlob(spec.substring(spec.lastIndexOf(directorySeparator) + 1))) { const path = removeTrailingDirectorySeparator(spec); return { key: toCanonicalKey(path, useCaseSensitiveFileNames), path, flags: WatchDirectoryFlags.Recursive, }; } return undefined; } /** * Determines whether a literal or wildcard file has already been included that has a higher * extension priority. * * @param file The path to the file. */ function hasFileWithHigherPriorityExtension(file: string, literalFiles: Map, wildcardFiles: Map, extensions: readonly string[][], keyMapper: (value: string) => string) { const extensionGroup = forEach(extensions, group => fileExtensionIsOneOf(file, group) ? group : undefined); if (!extensionGroup) { return false; } for (const ext of extensionGroup) { // d.ts files match with .ts extension and with case sensitive sorting the file order for same files with ts tsx and dts extension is // d.ts, .ts, .tsx in that order so we need to handle tsx and dts of same same name case here and in remove files with same extensions // So dont match .d.ts files with .ts extension if (fileExtensionIs(file, ext) && (ext !== Extension.Ts || !fileExtensionIs(file, Extension.Dts))) { return false; } const higherPriorityPath = keyMapper(changeExtension(file, ext)); if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) { if (ext === Extension.Dts && (fileExtensionIs(file, Extension.Js) || fileExtensionIs(file, Extension.Jsx))) { // LEGACY BEHAVIOR: An off-by-one bug somewhere in the extension priority system for wildcard module loading allowed declaration // files to be loaded alongside their js(x) counterparts. We regard this as generally undesirable, but retain the behavior to // prevent breakage. continue; } return true; } } return false; } /** * Removes files included via wildcard expansion with a lower extension priority that have * already been included. * * @param file The path to the file. */ function removeWildcardFilesWithLowerPriorityExtension(file: string, wildcardFiles: Map, extensions: readonly string[][], keyMapper: (value: string) => string) { const extensionGroup = forEach(extensions, group => fileExtensionIsOneOf(file, group) ? group : undefined); if (!extensionGroup) { return; } for (let i = extensionGroup.length - 1; i >= 0; i--) { const ext = extensionGroup[i]; if (fileExtensionIs(file, ext)) { return; } const lowerPriorityPath = keyMapper(changeExtension(file, ext)); wildcardFiles.delete(lowerPriorityPath); } } /** * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed. * Also converts enum values back to strings. * * @internal */ export function convertCompilerOptionsForTelemetry(opts: CompilerOptions): CompilerOptions { const out: CompilerOptions = {}; for (const key in opts) { if (hasProperty(opts, key)) { const type = getOptionFromName(key); if (type !== undefined) { // Ignore unknown options out[key] = getOptionValueWithEmptyStrings(opts[key], type); } } } return out; } function getOptionValueWithEmptyStrings(value: any, option: CommandLineOption): {} | undefined { if (value === undefined) return value; switch (option.type) { case ""object"": // ""paths"". Can't get any useful information from the value since we blank out strings, so just return """". return """"; case ""string"": // Could be any arbitrary string -- use empty string instead. return """"; case ""number"": // Allow numbers, but be sure to check it's actually a number. return typeof value === ""number"" ? value : """"; case ""boolean"": return typeof value === ""boolean"" ? value : """"; case ""listOrElement"": if (!isArray(value)) return getOptionValueWithEmptyStrings(value, option.element); // fall through to list case ""list"": const elementType = option.element; return isArray(value) ? mapDefined(value, v => getOptionValueWithEmptyStrings(v, elementType)) : """"; default: return forEachEntry(option.type, (optionEnumValue, optionStringValue) => { if (optionEnumValue === value) { return optionStringValue; } }); } } ",propertyName 140,"import { Request, Response, NextFunction } from 'express'; import jwt from 'jsonwebtoken'; import { JWT_SECRET } from '../config/jwt.js'; // Extender el tipo Request para incluir el usuario declare global { namespace Express { interface Request { user?: { id: string; email: string; [key: string]: any; }; } } } /** * Middleware para verificar autenticación JWT * Extrae la información del usuario del token y la añade a req.user */ export const authenticateJWT = (req: Request, res: Response, next: NextFunction): void => { try { // Si es una solicitud OPTIONS, permitir pasar para habilitar CORS if (req.method === 'OPTIONS') { return next(); } const authHeader = req.headers.authorization; if (!authHeader) { res.status(401).json({ error: 'Token de autenticación requerido' }); return; } // Formato esperado: Bearer token const token = authHeader.split(' ')[1]; if (!token) { res.status(401).json({ error: 'Formato de token inválido. Use: Bearer ' }); return; } // Verificar el token jwt.verify(token, JWT_SECRET, (err, [MASK] ) => { if (err) { return res.status(403).json({ error: 'Token inválido o expirado' }); } // Añadir información del usuario al objeto de solicitud req.user = [MASK] as { id: string; email: string; [key: string]: any }; next(); }); } catch (error) { console.error('Error en la autenticación:', error); res.status(500).json({ error: 'Error interno de autenticación' }); } }; export default authenticateJWT;",decoded 141,"import { ExpressionDefinitionLogicType, ExpressionDefinition, LiteralExpressionDefinition, FunctionExpressionDefinition, FunctionExpressionDefinitionKind, generateUuid, ContextExpressionDefinition, DmnBuiltInDataType, ListExpressionDefinition, InvocationExpressionDefinition, RelationExpressionDefinition, DecisionTableExpressionDefinition, DecisionTableExpressionDefinitionHitPolicy, DecisionTableExpressionDefinitionBuiltInAggregation, ExpressionDefinitionBase, } from ""../src/api""; import { LITERAL_EXPRESSION_MIN_WIDTH, CONTEXT_ENTRY_INFO_MIN_WIDTH, DECISION_TABLE_INPUT_DEFAULT_WIDTH, DECISION_TABLE_OUTPUT_DEFAULT_WIDTH, DECISION_TABLE_ANNOTATION_DEFAULT_WIDTH, LITERAL_EXPRESSION_EXTRA_WIDTH, } from ""../src/resizing/WidthConstants""; import { DECISION_TABLE_INPUT_DEFAULT_VALUE, DECISION_TABLE_OUTPUT_DEFAULT_VALUE, } from ""../src/expressions/DecisionTableExpression""; import { INVOCATION_EXPRESSION_DEFAULT_PARAMETER_NAME, INVOCATION_EXPRESSION_DEFAULT_PARAMETER_DATA_TYPE, INVOCATION_EXPRESSION_DEFAULT_PARAMETER_LOGIC_TYPE, } from ""../src/expressions/InvocationExpression""; import { RELATION_EXPRESSION_DEFAULT_VALUE } from ""../src/expressions/RelationExpression""; export function getDefaultExpressionDefinitionByLogicType( logicType: ExpressionDefinitionLogicType, prev: ExpressionDefinitionBase, [MASK] : number ): ExpressionDefinition { if (logicType === ExpressionDefinitionLogicType.Literal) { const literalExpression: LiteralExpressionDefinition = { ...prev, logicType, width: Math.max(LITERAL_EXPRESSION_MIN_WIDTH, [MASK] - LITERAL_EXPRESSION_EXTRA_WIDTH), }; return literalExpression; } else if (logicType === ExpressionDefinitionLogicType.Function) { const functionExpression: FunctionExpressionDefinition = { ...prev, logicType, functionKind: FunctionExpressionDefinitionKind.Feel, formalParameters: [], expression: { id: generateUuid(), logicType: ExpressionDefinitionLogicType.Undefined, dataType: DmnBuiltInDataType.Undefined, }, }; return functionExpression; } else if (logicType === ExpressionDefinitionLogicType.Context) { const contextExpression: ContextExpressionDefinition = { ...prev, logicType, entryInfoWidth: CONTEXT_ENTRY_INFO_MIN_WIDTH, result: { logicType: ExpressionDefinitionLogicType.Undefined, dataType: DmnBuiltInDataType.Undefined, id: generateUuid(), }, contextEntries: [ { entryInfo: { id: generateUuid(), name: ""ContextEntry-1"", dataType: DmnBuiltInDataType.Undefined, }, entryExpression: { id: generateUuid(), name: ""ContextEntry-1"", dataType: DmnBuiltInDataType.Undefined, logicType: ExpressionDefinitionLogicType.Undefined, }, }, { entryInfo: { id: generateUuid(), name: ""ContextEntry-2"", dataType: DmnBuiltInDataType.Undefined, }, entryExpression: { id: generateUuid(), name: ""ContextEntry-2"", dataType: DmnBuiltInDataType.Undefined, logicType: ExpressionDefinitionLogicType.Undefined, }, }, ], }; return contextExpression; } else if (logicType === ExpressionDefinitionLogicType.List) { const listExpression: ListExpressionDefinition = { ...prev, logicType, items: [ { id: generateUuid(), logicType: ExpressionDefinitionLogicType.Undefined, dataType: DmnBuiltInDataType.Undefined, }, { id: generateUuid(), logicType: ExpressionDefinitionLogicType.Undefined, dataType: DmnBuiltInDataType.Undefined, }, { id: generateUuid(), logicType: ExpressionDefinitionLogicType.Undefined, dataType: DmnBuiltInDataType.Undefined, }, ], }; return listExpression; } else if (logicType === ExpressionDefinitionLogicType.Invocation) { const invocationExpression: InvocationExpressionDefinition = { ...prev, logicType, entryInfoWidth: CONTEXT_ENTRY_INFO_MIN_WIDTH, bindingEntries: [ { entryInfo: { id: generateUuid(), name: INVOCATION_EXPRESSION_DEFAULT_PARAMETER_NAME, dataType: INVOCATION_EXPRESSION_DEFAULT_PARAMETER_DATA_TYPE, }, entryExpression: { id: generateUuid(), name: INVOCATION_EXPRESSION_DEFAULT_PARAMETER_NAME, dataType: INVOCATION_EXPRESSION_DEFAULT_PARAMETER_DATA_TYPE, logicType: INVOCATION_EXPRESSION_DEFAULT_PARAMETER_LOGIC_TYPE, }, }, ], invokedFunction: { id: generateUuid(), name: ""FUNCTION"", }, }; return invocationExpression; } else if (logicType === ExpressionDefinitionLogicType.Relation) { const relationExpression: RelationExpressionDefinition = { ...prev, logicType, columns: [ { id: generateUuid(), name: ""column-1"", dataType: DmnBuiltInDataType.Undefined, width: 100, }, { id: generateUuid(), name: ""column-2"", dataType: DmnBuiltInDataType.Undefined, width: 300, }, { id: generateUuid(), name: ""column-3"", dataType: DmnBuiltInDataType.Undefined, width: 200, }, ], rows: [ { id: generateUuid(), cells: [ { id: generateUuid(), content: RELATION_EXPRESSION_DEFAULT_VALUE }, { id: generateUuid(), content: RELATION_EXPRESSION_DEFAULT_VALUE }, { id: generateUuid(), content: RELATION_EXPRESSION_DEFAULT_VALUE }, ], }, ], }; return relationExpression; } else if (logicType === ExpressionDefinitionLogicType.DecisionTable) { const decisionTableExpression: DecisionTableExpressionDefinition = { ...prev, logicType, hitPolicy: DecisionTableExpressionDefinitionHitPolicy.Unique, aggregation: DecisionTableExpressionDefinitionBuiltInAggregation[""""], input: [ { id: generateUuid(), idLiteralExpression: generateUuid(), name: ""input-1"", dataType: DmnBuiltInDataType.Undefined, width: DECISION_TABLE_INPUT_DEFAULT_WIDTH, }, { id: generateUuid(), idLiteralExpression: generateUuid(), name: ""input-2"", dataType: DmnBuiltInDataType.Undefined, width: DECISION_TABLE_INPUT_DEFAULT_WIDTH, }, ], output: [ { id: generateUuid(), name: ""output-1"", dataType: DmnBuiltInDataType.Undefined, width: DECISION_TABLE_OUTPUT_DEFAULT_WIDTH, }, { id: generateUuid(), name: ""output-2"", dataType: DmnBuiltInDataType.Undefined, width: DECISION_TABLE_OUTPUT_DEFAULT_WIDTH, }, { id: generateUuid(), name: ""output-3"", dataType: DmnBuiltInDataType.Undefined, width: DECISION_TABLE_OUTPUT_DEFAULT_WIDTH, }, ], annotations: [ { name: ""annotation-1"", width: DECISION_TABLE_ANNOTATION_DEFAULT_WIDTH, }, ], rules: [ { id: generateUuid(), inputEntries: [ { id: generateUuid(), content: DECISION_TABLE_INPUT_DEFAULT_VALUE }, { id: generateUuid(), content: DECISION_TABLE_INPUT_DEFAULT_VALUE }, ], outputEntries: [ { id: generateUuid(), content: DECISION_TABLE_OUTPUT_DEFAULT_VALUE }, { id: generateUuid(), content: DECISION_TABLE_OUTPUT_DEFAULT_VALUE }, { id: generateUuid(), content: DECISION_TABLE_OUTPUT_DEFAULT_VALUE }, ], annotationEntries: [""// Your annotations here""], }, ], }; return decisionTableExpression; } else { throw new Error(`No default expression available for ${logicType}`); } } ",containerWidth 142,"import { Component, OnInit } from '@angular/core'; import { Web3Service } from '../util/web3.service'; import { MatSnackBar } from '@angular/material'; import { environment } from '../../environments/environment'; @Component({ selector: 'app-sale', templateUrl: './sale.component.html', styleUrls: ['./sale.component.css'] }) export class SaleComponent implements OnInit { accounts: string[]; rate = 0; etherAmount: any tokenSold: Number; progressPercent: Number; admin: Boolean; tokenSaleInstance: any; calileaInstance: any; tokensAvailable = 0; model = { ether: 0, amount: 5, receiver: '', balance: 0, account: '', link: '' }; numberOfTokens: Number; // rpsten enviroment // calileaAdminAccount = '' // ganache test environment calileaAdminAccount = environment.wallet; constructor(private web3Service: Web3Service, private matSnackBar: MatSnackBar) { } async ngOnInit() { this.admin = false; this.progressPercent = 0 await this.watchAccount(); await this.getInstance(); } async getInstance() { try { console.log('Sale: getInstance....') this.tokenSaleInstance = await this.web3Service.getInstanceTokenSale() this.calileaInstance = await this.web3Service.getInstanceCalileaToken() this.rate = this.web3Service.toWei(await this.tokenSaleInstance.rate()) console.log(`rate in: ${this.rate}`) if (this.tokenSaleInstance) { this.refreshTokenBalance(); } } catch (err) { console.log('Calilea Token has not been found in this account: ' + err) } } async watchAccount() { this.web3Service.accountsObservable.subscribe((accounts) => { console.log(accounts) this.accounts = accounts; this.model.account = accounts[0]; this.admin = (this.model.account === this.calileaAdminAccount) ? true : false this.model.link = `https://ropsten.etherscan.io/address/${accounts[0]}`; }); } async refreshTokenBalance() { try { console.log('RefresRokenBalance******************') let rate = await this.tokenSaleInstance.rate(); this.tokensAvailable = Number(await this.tokenSaleInstance.tokensAvailable()); console.log('tokensAvailable:'+this.tokensAvailable) console.log(rate.toString()) let rateFormatted = rate ? this.web3Service.toEther(rate.toString()) : 0 console.log(rateFormatted) let tokenSold = Number(await this.tokenSaleInstance.tokensSold()); console.log('tokenSold: '+tokenSold) this.rate = rateFormatted this.tokenSold = tokenSold this.progressPercent = (Math.ceil(tokenSold) / this.tokensAvailable) * 100; console.log(this.progressPercent) } catch (err) { console.log(err) } } async buyTokens() { try { console.log(`tokenSaleInstance.address: ${this.tokenSaleInstance.address}`) console.log(`tokensAvailable: ${this.tokensAvailable}`) let rateBN = await this.tokenSaleInstance.rate(); let rate= Number(rateBN.toString()); console.log(rate) let etherValue =Number(this.numberOfTokens) * rate; console.log('etherValue: '+etherValue) let receipt = await this.tokenSaleInstance.buyTokens(this.model.account, { from: this.model.account, value: etherValue, gas: 500000 }) this.numberOfTokens = 0 this.setStatus('Tokens bought successfully!!!') } catch (err) { this.setStatus('Error in sale process, please, try again') console.log(err) } } setStatus(status) { this.matSnackBar.open(status, null, { duration: 3000 }); } calculateEther(): any { this.etherAmount = Number(this.numberOfTokens) * this.rate; } async startIco() { let wallet = await this.tokenSaleInstance.wallet() console.log('wallet:' + wallet) let initialTokenAvailable = 5000000 let [MASK] = this.web3Service.toWei(initialTokenAvailable.toString()) await this.tokenSaleInstance.initializeIco(initialTokenAvailable, { from: wallet, }) console.log('this.tokenSaleInstance.address:' + this.tokenSaleInstance.address) console.log('this.tokenSaleInstance.address:' + this.tokenSaleInstance.address) await this.calileaInstance.transfer(this.tokenSaleInstance.address, [MASK] , { from: wallet, gas: 500000 }); } } ",initialTokenAvailableWei 143,"import * as cdk from 'aws-cdk-lib'; import { Construct } from 'constructs'; import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager'; const projectName = `multi-agent`; const region = process.env.CDK_DEFAULT_REGION; const accountId = process.env.CDK_DEFAULT_ACCOUNT; export class CdkMultiAgentStack extends cdk.Stack { constructor( [MASK] : Construct, id: string, props?: cdk.StackProps) { super( [MASK] , id, props); const weatherApiSecret = new secretsmanager.Secret(this, `weather-secret-for-${projectName}`, { description: 'secret for weather api key', // openweathermap removalPolicy: cdk.RemovalPolicy.DESTROY, secretName: `openweathermap-${projectName}`, secretObjectValue: { project_name: cdk.SecretValue.unsafePlainText(projectName), weather_api_key: cdk.SecretValue.unsafePlainText(''), }, }); // Secret const langsmithApiSecret = new secretsmanager.Secret(this, `langsmith-secret-for-${projectName}`, { description: 'secret for lamgsmith api key', // lamgsmith removalPolicy: cdk.RemovalPolicy.DESTROY, secretName: `langsmithapikey-${projectName}`, secretObjectValue: { langchain_project: cdk.SecretValue.unsafePlainText(projectName), langsmith_api_key: cdk.SecretValue.unsafePlainText(''), }, }); const tavilyApiSecret = new secretsmanager.Secret(this, `tavily-secret-for-${projectName}`, { description: 'secret for tavily api key', // tavily removalPolicy: cdk.RemovalPolicy.DESTROY, secretName: `tavilyapikey-${projectName}`, secretObjectValue: { project_name: cdk.SecretValue.unsafePlainText(projectName), tavily_api_key: cdk.SecretValue.unsafePlainText(''), }, }); } } ",scope 144,"import { Flow } from '@vaadin/flow-frontend'; import { Route } from '@vaadin/router'; import Role from './generated/dk/mhm/hilla/data/Role'; import { appStore } from './stores/app-store'; import './views/helloworldpublic/hello-world-public-view'; import './views/main-layout'; const { serverSideRoutes } = new Flow({ imports: () => import('../target/frontend/generated-flow-imports'), }); export type ViewRoute = Route & { title?: string; icon?: string; requiresLogin?: boolean; rolesAllowed?: Role[]; children?: ViewRoute[]; }; export const hasAccess = (route: Route) => { const [MASK] = route as ViewRoute; if ( [MASK] .requiresLogin && !appStore.loggedIn) { return false; } if ( [MASK] .rolesAllowed) { return [MASK] .rolesAllowed.some((role) => appStore.isUserInRole(role)); } return true; }; export const views: ViewRoute[] = [ // place routes below (more info https://hilla.dev/docs/routing) { path: '', component: 'hello-world-public-view', icon: '', title: '', }, { path: 'hello-world-public', component: 'hello-world-public-view', icon: 'la la-globe', title: 'Hello World Public', }, { path: 'hello-world-user', component: 'hello-world-user-view', rolesAllowed: [Role.USER], icon: 'la la-globe', title: 'Hello World User', action: async (_context, _command) => { if (!hasAccess(_context.route)) { return _command.redirect('login'); } await import('./views/helloworlduser/hello-world-user-view'); return; }, }, { path: 'hello-world-admin', component: 'hello-world-admin-view', rolesAllowed: [Role.ADMIN], icon: 'la la-globe', title: 'Hello World Admin', action: async (_context, _command) => { if (!hasAccess(_context.route)) { return _command.redirect('login'); } await import('./views/helloworldadmin/hello-world-admin-view'); return; }, }, ]; export const routes: ViewRoute[] = [ { path: 'login', component: 'login-view', icon: '', title: 'Login', action: async (_context, _command) => { await import('./views/login/login-view'); return; }, }, { path: '', component: 'main-layout', children: [ ...views, // for server-side, the next magic line sends all unmatched routes: ...serverSideRoutes, // IMPORTANT: this must be the last entry in the array ], }, ]; ",viewRoute 145,"import axios from 'axios'; import { message } from 'antd'; export interface Result { code: number; message: string; data: T; } export enum OrderTypes { DESC, ASC, } export interface PaginationOptions { pageNum: number; pageSize: number; orderColumn: string; orderType: OrderTypes; } export interface PaginationResult { data: T[]; total: number; pageNum: number; pageSize: number; maxPage: number; } // let BASE_API = ''; // if (process.env['NODE_ENV'] !== 'development') { // BASE_API = process.env.REACT_APP_API as string; // } /** * 设置默认Content-Type */ axios.defaults.headers.post['Content-Type'] = 'application/json'; // axios.defaults.baseURL = BASE_API; axios.defaults.baseURL = 'api'; /** * request拦截器 */ axios.interceptors.request.use( ( [MASK] ) => { const TOKEN = localStorage.getItem('TOKEN'); if (TOKEN) { [MASK] .headers && ( [MASK] .headers['Authorization'] = `Bearer ${TOKEN}`); } else { [MASK] .headers && delete [MASK] .headers['Authorization']; } return [MASK] ; }, (error) => { return Promise.reject(error?.response?.data); } ); /** * response拦截器 */ axios.interceptors.response.use( async (res) => { return res?.data?.data; }, async (err) => { if (err?.response?.status === 401) { localStorage.removeItem('TOKEN'); message.error(err?.response?.data?.message ?? '请重新登录'); window.location.reload(); } return Promise.reject(err?.response?.data ?? err); } ); /** * 封装get方法 * @param url * @param params */ export const GET = async

( url: string, params?: P ): Promise => { return await axios.get(url, { params }); }; /** * 封装post请求 * @param url * @param data */ export const POST = async

( url: string, data?: P ): Promise => { return await axios.post(url, data); }; ",config 146,"import ResourceBundle from ""sap/base/i18n/ResourceBundle""; import Device from ""sap/ui/Device""; import UIComponent from ""sap/ui/core/UIComponent""; import JSONModel from ""sap/ui/model/json/JSONModel""; import ResourceModel from ""sap/ui/model/resource/ResourceModel""; /** * @namespace de.regatta_hd.infoportal */ export default class Component extends UIComponent { private contentDensityClass: string; private resourceBundle: ResourceBundle; private regattaModel?: JSONModel; private filtersModel?: JSONModel; private regattaModelPromise?: Promise; private filtersModelPromise?: Promise; static readonly metadata = { manifest: ""json"", interfaces: [""sap.ui.core.IAsyncContentCreation""] }; async getActiveRegatta(): Promise { if (this.regattaModelPromise) { return this.regattaModelPromise; } if (!this.regattaModel) { this.regattaModelPromise = this.loadActiveRegatta(); this.regattaModel = await this.regattaModelPromise; delete this.regattaModelPromise; } else { console.debug(""Active regatta already loaded""); } return Promise.resolve(this.regattaModel); } async getFilters(): Promise { if (this.filtersModelPromise) { return this.filtersModelPromise; } if (!this.filtersModel) { this.filtersModelPromise = this.loadFilters(); this.filtersModel = await this.filtersModelPromise; delete this.filtersModelPromise; } else { console.debug(""Filters already loaded""); } return Promise.resolve(this.filtersModel); } init(): void { super.init(); // create the views based on the url/hash super.getRouter().initialize(); // set regatta and filters model this.getActiveRegatta().then((model: JSONModel) => { super.setModel(model, ""regatta""); this.getFilters().then((model: JSONModel) => { super.setModel(model, ""filters""); }); }) // set device model super.setModel(new JSONModel(Device).setDefaultBindingMode(""OneWay""), ""device""); // set identity model const identityModel: JSONModel = new JSONModel({ authenticated: false, username: ""anonymous"", roles: [] }).setDefaultBindingMode(""OneWay""); super.setModel(identityModel, ""identity""); // set initial heat model, required for navigation over heats super.setModel(new JSONModel(), ""heat""); // set initial race model, required for navigation over races super.setModel(new JSONModel(), ""race""); window.addEventListener('beforeunload', (event: BeforeUnloadEvent) => { // Cancel the event as stated by the standard. event.preventDefault(); }); const bundle: ResourceBundle | Promise = (super.getModel(""i18n"") as ResourceModel).getResourceBundle(); if (bundle instanceof ResourceBundle) { this.resourceBundle = bundle; } else { bundle.then((bundle: ResourceBundle) => { this.resourceBundle = bundle; }); } } /** * Returns the content density class according to the current device. * @returns {string} the content density class */ getContentDensityClass(): string { if (!this.contentDensityClass) { if (!Device.support.touch) { this.contentDensityClass = ""sapUiSizeCompact""; } else { this.contentDensityClass = ""sapUiSizeCozy""; } } return this.contentDensityClass; } /** * Getter for the resource bundle. * @returns {sap.base.i18n.ResourceBundle} the resourceModel of the component */ getResourceBundle(): ResourceBundle { return this.resourceBundle; } /** * Loads the active regatta into a JSONModel from the server and returns it as a Promise. * @returns {Promise} the active regatta model as a Promise */ private async loadActiveRegatta(): Promise { console.debug(""Loading active regatta""); const model: JSONModel = new JSONModel(); await model.loadData(""/api/active_regatta""); console.debug(""Active regatta loaded""); return model; } /** * Loads the filters into a JSONModel for the active regatta from the server and returns it as a Promise. * @returns {Promise} the filters model as a Promise */ private async loadFilters(): Promise { await this.getActiveRegatta(); console.debug(""Loading filters""); const model: JSONModel = new JSONModel(); const [MASK] = this.regattaModel?.getData().id ?? -1; await model.loadData(`/api/regattas/${ [MASK] }/filters`); console.debug(""Filters loaded""); return model } }",regattaId 147,"import {json, Router} from 'express'; import { PendingOperations } from '../services/agent-state'; import { MakeAsyncSafe } from '../utils/async'; export function CreateAcknowledgeRouter(services: Services) { const router = MakeAsyncSafe(Router()); router.post(""/"", json({limit: '80MB'}), (req, res)=>{ const [MASK] = JSON.stringify(req.body); console.log(`Acknowledge size: ${ [MASK] .length} B`); const opId = req.body.operationId; const state = req.body.operationState.state; console.log(`Acknowledge operation {id: ${opId}, state: ${state}}`); const cb = PendingOperations.get(opId); PendingOperations.delete(opId); if (state === ""FULLY_APPLIED"" || state === ""NO_OPERATION"") { cb?.resolve( [MASK] ); } else { cb?.reject(req?.body?.operationState?.details); } res.end(); }) return router; }",raw_body 148,"import {Injectable} from '@angular/core'; import {select, Store} from '@ngrx/store'; import {from, Observable, of} from 'rxjs'; import {tap} from 'rxjs/operators'; import {getThemeActiveSetting, settingsFeatureKey, State} from './store/settings.reducer'; import {loaded, update} from './store/settings.action'; import {SettingModel} from '../shared/model/setting.model'; import {LocalStorageService} from 'angular-2-local-storage'; export const LANGUAGES = ['en']; // export const LANGUAGES = ['en', 'fr', 'de']; const DEFAULT_LANG = 'en'; @Injectable({ providedIn: 'root' }) export class SettingsService { constructor(private store: Store, private localStorageService: LocalStorageService) {} load(): Observable { const isDarkConfig = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; let activeThemeValue: string = isDarkConfig ? 'dark' : 'default'; let [MASK] : string = DEFAULT_LANG; if (navigator?.language) { [MASK] = navigator.language.split('-')[0]; } if (LANGUAGES.indexOf( [MASK] ) === -1) { [MASK] = DEFAULT_LANG; } if (this.localStorageService.get('themeActiveValue')) { activeThemeValue = this.localStorageService.get('themeActiveValue'); } if (this.localStorageService.get('languageActiveValue')) { [MASK] = this.localStorageService.get('languageActiveValue'); } const settings: SettingModel[] = [ {name: 'language-active', value: [MASK] }, {name: 'theme-active', value: activeThemeValue}, {name: 'results-per-page', value: '20'} ]; return of(settings).pipe(tap(sett => this.store.dispatch(loaded({settings: sett})))); } update(setting: SettingModel): Observable { if (setting.name === 'theme-active') { this.localStorageService.set('themeActiveValue', setting.value); } if (setting.name === 'language-active') { this.localStorageService.set('languageActiveValue', setting.value); } return from(new Promise(resolve => resolve())); } dispatch(setting: SettingModel): void { this.store.dispatch(update({setting})); } themeActiveSetting(): Observable { return this.store.pipe(select(getThemeActiveSetting)); } getSettings(): Observable { return this.store.pipe(select(state => state[settingsFeatureKey].settings)); } } ",activeLanguageValue 149,"import inlineAssets from ""npm:inline-assets@1.4.8""; import { DOMParser, Element } from ""https://deno.land/x/deno_dom@v0.1.36-alpha/deno-dom-wasm.ts""; import postcss from ""https://deno.land/x/postcss@8.4.16/mod.js""; import postcssImporter from ""npm:postcss-import-url@7.2.0""; import { ensureFile } from ""https://deno.land/std@0.178.0/fs/mod.ts""; export default async function minify( inputFilePath: string, [MASK] : string, ensureOutput: boolean ) { let content: string = await Deno.readTextFile(inputFilePath); // Put all assets (images, css, etc) inside the HTML itself content = inlineAssets( [MASK] , inputFilePath, content, { verbose: true, htmlmin: true, cssmin: true, jsmin: false }); const parsedDocument = (new DOMParser().parseFromString(content, ""text/html""))!; // Recursively inline all stylesheets (mostly targeting remote fonts) for (const styleTag of parsedDocument.querySelectorAll(""style"")) { styleTag.textContent = await postcss([ postcssImporter({ recursive: true, // Set user-agent string, which is useful for fetching remote fonts modernBrowser: true, dataUrls: true }) ]).process(styleTag.textContent, { from: undefined }); } // Unwrap referral links for (const linkTag of parsedDocument.querySelectorAll(""a"")) { const href = (linkTag as Element).attributes.getNamedItem(""href"") ?? null; if (href === null) { continue; } let url: URL = null!; try { url = new URL(href.value); } catch (_e) { // It's an invalid URL, probably an anchor link. continue; } if (url.href.startsWith(""https://www.google.com/url"")) { href.value = url.searchParams.get(""q""); } } // Convert document back into raw HTML plaintext // @ts-ignore (TypeScript thinks parsedDocument is null...) content = parsedDocument.documentElement.outerHTML; if (ensureOutput === true) { await ensureFile( [MASK] ); } // Save the resulting fat-html to the output location await Deno.writeTextFile( [MASK] , content); } ",outputFilePath 150,"/** * Copyright 2024 * * See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * 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 * * https://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. * * This project is based on https://github.com/google/pixelate which is licensed under the Apache 2.0 License. * * Copyright 2022 Google LLC */ import { Mode, PersistableState } from ""../editor"" import { StoreState } from ""../store/reducer"" import { HexColor, createCanvas, getContext2D, hexToRgb, min, requireNonNull } from ""../utils"" import { EditableImageData } from ""./EditableImageData"" export * from ""./EditableCanvas"" export * from ""./EditableImageData"" export function getImageData(img: HTMLImageElement): ImageData { if (!img.complete) throw new Error(""Image not loaded"") if (!img.naturalWidth || !img.naturalHeight) throw new Error(""Image has no dimensions"") const canvas = createCanvas({ height: img.naturalHeight, width: img.naturalWidth }) const ctx = getContext2D(canvas) ctx.fillStyle = ""#ffffff"" ctx.fillRect(0, 0, img.naturalWidth, img.naturalHeight); ctx.drawImage(img, 0, 0); return ctx.getImageData(0, 0, img.naturalWidth, img.naturalHeight); } export function downscale( original: EditableImageData, target: EditableImageData, colorHint: number ) { const [MASK] = original.width / target.width; // TODO: When the input image is aliased, picking the n most common color // values is not ideal. There might be dozens of shades of one color, but // each one with only a small count. const originalColors = Array.from(original.counter).sort( ([, a], [, b]) => b - a ); const selectedColors = Array.from( originalColors.slice(0, colorHint).map(([c]) => c) ); // Divide the original image of width m into n blocks, where n ≤ m. // Then, sample the center color from each block and draw the closest // color to the target image. for (let y = 0; y < target.height; y++) { for (let x = 0; x < target.width; x++) { const originalColor = original.pick( Math.min(Math.trunc((x + .5) * [MASK] ), original.width - 1), Math.min(Math.trunc((y + .5) * [MASK] ), original.height - 1) ); const color = requireNonNull( min(selectedColors, (c) => colorDistance(c, originalColor)) ); target.draw(x, y, color); } } } export function colorDistance(a: HexColor, b: HexColor) { const [ar, ag, ab] = hexToRgb(a); const [br, bg, bb] = hexToRgb(b); return Math.abs(ar - br) + Math.abs(ag - bg) + Math.abs(ab - bb); } export function hasImageData(state: PersistableState): state is StoreState { return ( state.mode === Mode.DRAW || state.mode === Mode.PREPROCESS || state.mode === Mode.ASSEMBLE ) } ",ratio 151,"import { Injectable } from '@angular/core'; import * as Cookies from ""js-cookie""; export interface CourseFilter { inst: string course: string name: string } @Injectable() export class FilterService { set minYear(val: number) { Cookies.set(""minYear"", val + """") } get minYear(): number { let val = Cookies.get(""minYear"") return val == null ? null : parseInt(val) } set maxYear(val: number) { Cookies.set(""maxYear"", val + """") } get maxYear(): number { let val = Cookies.get(""maxYear"") return val == null ? null : parseInt(val) } private _courses: CourseFilter[] get courses(): CourseFilter[] { console.log('COURSES: ', this._courses) if (this._courses == null) { let val = Cookies.get(""courses"") this._courses = val == null ? [] : JSON.parse(val) } return this._courses } getCoursesMap() { let data = {} this.courses.forEach(_ => { let [MASK] = _.inst + '-' + _.course let cName = """" for(let char of _.name) { if(char >= 'A' && char <= 'Z') cName += char } data[ [MASK] ] = { name: _.name, short: cName } }) console.log('getCoursesMap -> ', data) return data } addCourse(item: CourseFilter) { //do nothing if duplicate found for (let next of this._courses) if (item.inst == next.inst && item.course == next.course) return this._courses.push(item) Cookies.set(""courses"", JSON.stringify(this._courses)) } removeCourse(item: CourseFilter) { //find position and remove it for (let i = 0; i < this._courses.length; i++) if (item.inst == this._courses[i].inst && item.course == this._courses[i].course) { this._courses.splice(i, 1) break } Cookies.set(""courses"", JSON.stringify(this._courses)) } }",cCode 152,"import { Command, flags, Flags, DeployPayload, Config } from 'prisma-cli-engine' import { Cluster } from 'prisma-yml' import chalk from 'chalk' import * as chokidar from 'chokidar' import * as inquirer from 'inquirer' import * as path from 'path' import * as fs from 'fs-extra' import { fetchAndPrintSchema } from './printSchema' import { Seeder } from '../seed/Seeder' import * as semver from 'semver' const debug = require('debug')('deploy') import { prettyTime, concatName, defaultDockerCompose } from '../../util' import * as sillyname from 'sillyname' import { getSchemaPathFromConfig } from './getSchemaPathFromConfig' import { EndpointDialog } from '../../utils/EndpointDialog' import { spawnSync } from 'npm-run' import * as figures from 'figures' export default class Deploy extends Command { static topic = 'deploy' static description = 'Deploy service changes (or new service)' static group = 'general' static allowAnyFlags = true static help = ` ${chalk.green.bold('Examples:')} ${chalk.gray( '-', )} Deploy local changes from prisma.yml to the default service environment. ${chalk.green('$ prisma deploy')} ${chalk.gray( '-', )} Deploy local changes from default service file accepting potential data loss caused by schema changes ${chalk.green('$ prisma deploy --force')} ` static flags: Flags = { force: flags.boolean({ char: 'f', description: 'Accept data loss caused by schema changes', }), watch: flags.boolean({ char: 'w', description: 'Watch for changes', }), new: flags.boolean({ char: 'n', description: 'Force interactive mode to select the cluster', }), 'dry-run': flags.boolean({ char: 'd', description: 'Perform a dry-run of the deployment', }), 'no-seed': flags.boolean({ description: 'Disable seed on initial service deploy', }), json: flags.boolean({ char: 'j', description: 'Json Output', }), ['env-file']: flags.string({ description: 'Path to .env file to inject env vars', char: 'e', }), } private deploying: boolean = false private showedHooks: boolean = false private loggedIn: boolean = false async run() { /** * Get Args */ const { force, watch } = this.flags const interactive = this.flags.new // new is a reserved keyword, so we use interactive instead const envFile = this.flags['env-file'] const dryRun = this.flags['dry-run'] if (envFile && !fs.pathExistsSync(path.join(this.config.cwd, envFile))) { await this.out.error(`--env-file path '${envFile}' does not exist`) } /** * Get prisma.yml content */ await this.definition.load(this.flags, envFile) let serviceName = this.definition.service! let stage = this.definition.stage! /** * If no endpoint or service provided, ask for it */ let workspace: string | undefined | null = this.definition.getWorkspace() let cluster let dockerComposeYml = defaultDockerCompose if (!serviceName || !stage || interactive) { const endpointDialog = new EndpointDialog( this.out, this.client, this.env, this.config, ) const results = await endpointDialog.getEndpoint() cluster = results.cluster workspace = results.workspace serviceName = results.service stage = results.stage dockerComposeYml = results.dockerComposeYml this.definition.replaceEndpoint(results.endpoint) // Reload definition because we are changing the yml file await this.definition.load(this.flags, envFile) this.out.log( `\nWritten endpoint \`${chalk.bold( results.endpoint, )}\` to prisma.yml\n`, ) } else { cluster = this.definition.getCluster(false) } if ( cluster && cluster.local && !await cluster.isOnline() ) { throw new Error( `Could not connect to server at ${ cluster.baseUrl }. Please check if your server is running.`, ) } /** * If the cluster has been provided with the old ""cluster: "" key, check if the cluster could be found */ if (this.definition.definition!.cluster && !cluster) { this.out.log( `You're not logged in and cluster ${chalk.bold( this.definition.definition!.cluster!, )} could not be found locally. Trying to authenticate.\n`, ) // signs in and fetches clusters await this.client.login() cluster = this.definition.getCluster() } /** * Abort when no cluster is set */ if (cluster) { this.env.setActiveCluster(cluster) } else { throw new Error(`Cluster ${cluster} does not exist.`) } /** * Make sure we're logged in when a non-public cluster has been chosen */ if (cluster && !cluster.local && cluster.isPrivate) { if (!workspace) { workspace = this.definition.getWorkspace() } if ( workspace && !workspace.startsWith('public-') && (!this.env.cloudSessionKey || this.env.cloudSessionKey === '') ) { await this.client.login() cluster.clusterSecret = this.env.cloudSessionKey } } await this.client.initClusterClient(cluster, serviceName, stage, workspace!) let projectNew = false debug('checking if project exists') if (!await this.projectExists(cluster, serviceName, stage, workspace!)) { debug('adding project') await this.addProject(cluster, serviceName, stage, workspace!) projectNew = true } await this.deploy( stage, serviceName, cluster, cluster.name, force, dryRun, projectNew, workspace!, ) if (watch) { this.out.log('Watching for change...') chokidar .watch(this.config.definitionDir, { ignoreInitial: true }) .on('all', () => { setImmediate(async () => { if (!this.deploying) { await this.definition.load(this.flags) await this.deploy( stage, serviceName, cluster, cluster.name, force, dryRun, false, workspace!, ) this.out.log('Watching for change...') } }) }) } } private getSillyName() { return `${slugify(sillyname()).split('-')[0]}-${Math.round( Math.random() * 1000, )}` } private getPublicName() { return `public-${this.getSillyName()}` } private async projectExists( cluster: Cluster, name: string, stage: string, workspace: string | null, ): Promise { try { return Boolean( await this.client.getProject( concatName(cluster, name, workspace), stage, ), ) } catch (e) { return false } } private async addProject( cluster: Cluster, name: string, stage: string, workspace: string | null, ): Promise { this.out.action.start(`Creating stage ${stage} for service ${name}`) const createdProject = await this.client.addProject( concatName(cluster, name, workspace), stage, this.definition.secrets, ) this.out.action.stop() } private async deploy( stageName: string, serviceName: string, cluster: Cluster, completeClusterName: string, force: boolean, dryRun: boolean, projectNew: boolean, workspace: string | null, ): Promise { this.deploying = true let before = Date.now() const b = s => `\`${chalk.bold(s)}\`` const verb = dryRun ? 'Performing dry run for' : 'Deploying' this.out.action.start( `${verb} service ${b(serviceName)} to stage ${b(stageName)} to server ${b( completeClusterName, )}`, ) const migrationResult: DeployPayload = await this.client.deploy( concatName(cluster, serviceName, workspace), stageName, this.definition.typesString!, dryRun, this.definition.getSubscriptions(), this.definition.secrets, force, ) this.out.action.stop(prettyTime(Date.now() - before)) this.printResult(migrationResult, force) if ( migrationResult.migration && migrationResult.migration.revision > 0 && !dryRun ) { before = Date.now() this.out.action.start( `Applying changes`, this.getProgress(0, migrationResult.migration.steps.length), ) let done = false while (!done) { const revision = migrationResult.migration.revision const migration = await this.client.getMigration( concatName(cluster, serviceName, workspace), stageName, ) if (migration.errors && migration.errors.length > 0) { await this.out.error(migration.errors.join('\n')) } if (migration.applied === migrationResult.migration.steps.length) { done = true } this.out.action.status = this.getProgress( migration.applied, migrationResult.migration.steps.length, ) await new Promise(r => setTimeout(r, 500)) } this.out.action.stop(prettyTime(Date.now() - before)) } // TODO move up to if statement after testing done if (migrationResult.migration) { if ( this.definition.definition!.seed && !this.flags['no-seed'] && projectNew ) { this.printHooks() await this.seed( cluster, projectNew, serviceName, stageName, this.definition.getWorkspace(), ) } // no action required this.deploying = false if (migrationResult.migration) { this.printEndpoints( cluster, serviceName, stageName, this.definition.getWorkspace() || undefined, ) } } const hooks = this.definition.getHooks('post-deploy') if (hooks.length > 0) { this.out.log(`\n${chalk.bold('post-deploy')}:`) } for (const hook of hooks) { const splittedHook = hook.split(' ') this.out.action.start(`Running ${chalk.cyan(hook)}`) const child = spawnSync(splittedHook[0], splittedHook.slice(1)) const stderr = child.stderr && child.stderr.toString() if (stderr && stderr.length > 0) { this.out.log(chalk.red(stderr)) } const stdout = child.stdout && child.stdout.toString() if (stdout && stdout.length > 0) { this.out.log(stdout) } const { status, error } = child if (error || status != 0) { if (error) { this.out.log(chalk.red(error.message)) } this.out.action.stop(chalk.red(figures.cross)) } else { this.out.action.stop() } } } private printHooks() { if (!this.showedHooks) { this.out.log(chalk.bold(`\nHooks:`)) this.showedHooks = true } } private getProgress(applied: number, of: number) { return this.out.color.prisma(`(${applied}/${of})`) } private async seed( cluster: Cluster, projectNew: boolean, serviceName: string, stageName: string, workspace: string | null, ) { const seeder = new Seeder( this.definition, this.client, this.out, this.config, ) const before = Date.now() const from = this.definition.definition!.seed && this.definition.definition!.seed!.import ? ` from \`${this.definition.definition!.seed!.import}\`` : '' this.out.action.start(`Importing seed dataset${from}`) await seeder.seed(concatName(cluster, serviceName, workspace), stageName) this.out.action.stop(prettyTime(Date.now() - before)) } /** * Returns true if there was a change */ private async generateSchema( cluster: Cluster, serviceName: string, stageName: string, ): Promise { const schemaPath = getSchemaPathFromConfig() || this.definition.definition!.schema if (schemaPath) { this.printHooks() const schemaDir = path.dirname(schemaPath) fs.mkdirpSync(schemaDir) const token = this.definition.getToken(serviceName, stageName) const before = Date.now() this.out.action.start(`Checking, if schema file changed`) const schemaString = await fetchAndPrintSchema( this.client, concatName(cluster, serviceName, this.definition.getWorkspace()), stageName, token, ) this.out.action.stop(prettyTime(Date.now() - before)) const oldSchemaString = fs.pathExistsSync(schemaPath) ? fs.readFileSync(schemaPath, 'utf-8') : null if (schemaString !== oldSchemaString) { const beforeWrite = Date.now() this.out.action.start(`Writing database schema to \`${schemaPath}\` `) fs.writeFileSync(schemaPath, schemaString) this.out.action.stop(prettyTime(Date.now() - beforeWrite)) return true } } return false } private printResult(payload: DeployPayload, force: boolean) { if (payload.errors && payload.errors.length > 0) { this.out.log(`${chalk.bold.red('\nErrors:')}`) this.out.migration.printErrors(payload.errors) this.out.log( '\nDeployment canceled. Please fix the above errors to continue deploying.', ) this.out.log( 'Read more about deployment errors here: https://bit.ly/prisma-force-flag', ) this.out.exit(1) } if (payload.warnings && payload.warnings.length > 0) { this.out.log(`${chalk.bold.yellow('\nWarnings:')}`) this.out.migration.printWarnings(payload.warnings) if (force) { this.out.log('\nIgnoring warnings because you provided --force.') } else { this.out.log( `\nIf you want to ignore the warnings, please deploy with the --force flag: ${chalk.cyan( '$ prisma deploy --force', )}`, ) this.out.log( 'Read more about deployment warnings here: https://bit.ly/prisma-force-flag', ) this.out.exit(1) } } if (!payload.migration || payload.migration.steps.length === 0) { this.out.log('Service is already up to date.') return } if (payload.migration.steps.length > 0) { // this.out.migrati this.out.log('\n' + chalk.bold('Changes:')) this.out.migration.printMessages(payload.migration.steps) this.out.log('') } } private printEndpoints( cluster: Cluster, serviceName: string, stageName: string, workspace?: string, ) { this.out.log(`\n${chalk.bold( 'Your Prisma GraphQL database endpoint is live:', )} ${chalk.bold('HTTP:')} ${cluster.getApiEndpoint( serviceName, stageName, workspace, )} ${chalk.bold('WS:')} ${cluster.getWSEndpoint( serviceName, stageName, workspace, )} `) } private getCloudClusters(): Cluster[] { return this.env.clusters.filter(c => c.shared || c.isPrivate) } private async clusterSelection(loggedIn: boolean): Promise { debug({ loggedIn }) const choices = loggedIn ? await this.getLoggedInChoices() : this.getPublicChoices() const question = { name: 'cluster', type: 'list', message: `Please choose the cluster you want to deploy to`, choices, pageSize: 9, } const { cluster } = await this.out.prompt(question) if (cluster === 'login') { await this.client.login() this.loggedIn = true return this.clusterSelection(true) } return cluster } private getLocalClusterChoices(): string[][] { // const clusters = this.env.clusters.filter(c => !c.shared && !c.isPrivate) // const clusterNames: string[][] = clusters.map(c => { // const note = // c.baseUrl.includes('localhost') || c.baseUrl.includes('127.0.0.1') // ? 'Local cluster (requires Docker)' // : 'Self-hosted' // return [c.name, note] // }) // if (clusterNames.length === 0) { // clusterNames.push(['local', 'Local cluster (requires Docker)']) // } // return clusterNames return [['local', 'Local cluster (requires Docker)']] } private async getLoggedInChoices(): Promise { const localChoices = this.getLocalClusterChoices() // const workspaces = await this.client.getWorkspaces() // const clusters = this.env.clusters.filter( // c => c.shared && c.name !== 'shared-public-demo', // ) const combinations: string[][] = [] const [MASK] = this.env.clusters.filter( c => c.shared || c.isPrivate, ) [MASK] .forEach(cluster => { const label = this.env.sharedClusters.includes(cluster.name) ? 'Free development cluster (hosted on Prisma Cloud)' : 'Private Prisma Cluster' combinations.push([`${cluster.workspaceSlug}/${cluster.name}`, label]) }) const allCombinations = [...combinations, ...localChoices] return [ new inquirer.Separator(' '), ...this.convertChoices(allCombinations), new inquirer.Separator(' '), new inquirer.Separator( chalk.dim( `You can learn more about deployment in the docs: http://bit.ly/prisma-graphql-deployment`, ), ), ] } private convertChoices( choices: string[][], ): Array<{ value: string; name: string }> { const padded = this.out.printPadded(choices, 0, 6).split('\n') return padded.map((name, index) => ({ name, value: choices[index][0], })) } private getPublicChoices(): any[] { const publicChoices = [ [ 'prisma-eu1', 'Public development cluster (hosted in EU on Prisma Cloud)', ], [ 'prisma-us1', 'Public development cluster (hosted in US on Prisma Cloud)', ], ] const allCombinations = [...publicChoices, ...this.getLocalClusterChoices()] return [ ...this.convertChoices(allCombinations), new inquirer.Separator(' '), { value: 'login', name: 'Log in or create new account on Prisma Cloud', }, new inquirer.Separator(' '), new inquirer.Separator( chalk.dim( `Note: When not logged in, service deployments to Prisma Cloud expire after 7 days.`, ), ), new inquirer.Separator( chalk.dim( `You can learn more about deployment in the docs: http://bit.ly/prisma-graphql-deployment`, ), ), new inquirer.Separator(' '), ] } } export function isValidProjectName(projectName: string): boolean { return /^[A-Z](.*)/.test(projectName) } function slugify(text) { return text .toString() .toLowerCase() .replace(/\s+/g, '-') // Replace spaces with - .replace(/[^\w\-]+/g, '') // Remove all non-word chars .replace(/\-\-+/g, '-') // Replace multiple - with single - .replace(/^-+/, '') // Trim - from start of text .replace(/-+$/, '') // Trim - from end of text } ",remoteClusters 153,"import { Job } from 'bullmq'; import * as web3 from '@solana/web3.js'; import { PrismaClient } from '@prisma/client'; import { Transfer } from '../types/job'; import logger from '../utils/logger'; import { decryptKey } from '../utils/cryptdb'; // import config from '../config'; const SOLANA_NODE_URL = process?.env?.SOLANA_NODE_URL; const CLUSTER = process?.env?.CLUSTER; const prisma = new PrismaClient(); // eslint-disable-next-line consistent-return // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export default async (job: Job) => { // Connect to cluster const [MASK] = new web3.Connection( SOLANA_NODE_URL || (CLUSTER !== 'mainnet-beta' ? web3.clusterApiUrl('devnet') : web3.clusterApiUrl('mainnet-beta')), 'confirmed', ); try { const wallet = await prisma.wallet.findFirst({ where: { publicKey: job?.data?.from as unknown as string, }, }); if (!wallet) { throw new Error('Wallet not found'); } const decryptedKey = await decryptKey(wallet.privateKey); const privateKey = new Uint8Array(Buffer.from(decryptedKey, 'base64')); const from = web3.Keypair.fromSecretKey(privateKey); // Generate a new random public key let to = new web3.PublicKey(job.data.to); // Add transfer instruction to transaction let transaction = new web3.Transaction().add( web3.SystemProgram.transfer({ fromPubkey: from.publicKey, toPubkey: to, lamports: web3.LAMPORTS_PER_SOL / 1000, }), ); // Sign transaction, broadcast, and confirm return web3.sendAndConfirmTransaction( [MASK] , transaction, [from], ); } catch (err) { logger.error(err); throw err; } }; ",connection 154,"import { app, BrowserWindow, screen, Menu, globalShortcut } from 'electron'; import * as path from 'path'; import * as url from 'url'; const axios = require('axios'); let win; let serve; let splashWindow; const apiUrl = 'http://localhost:8080/node/'; const args = process.argv.slice(1); serve = args.some(val => val === '--serve'); const local = args.some(val => val === '--local'); function startAPI() { const exec = require('child_process').exec; const defaultJarPath = 'elrond-api-1.0-SNAPSHOT.jar'; // const macJarPath = `${__dirname}/elrond-api-1.0-SNAPSHOT.jar`; const macJarPath = `${__dirname}/Contents/elrond-api-1.0-SNAPSHOT.jar`; const [MASK] = (process.platform === 'darwin') ? macJarPath : defaultJarPath; console.log('========================='); console.log('JAR PATH: ', macJarPath); console.log('mac PATH: ', macJarPath); console.log('Dir PATH: ', __dirname); console.log('PATH: ', path); console.log('========================='); const child = exec('java -jar ' + [MASK] , function (error, stdout, stderr) { console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } }); } function createWindow() { const electronScreen = screen; const size = electronScreen.getPrimaryDisplay().workAreaSize; // Create the browser window. win = new BrowserWindow({ width: 1200, height: 600, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: false, }, backgroundColor: '#ffffff', show: false }); splashWindow = new BrowserWindow({ width: 300, height: 300, transparent: true, frame: false, alwaysOnTop: true }); splashWindow.loadURL(url.format({ pathname: path.join(__dirname, 'splash.html'), protocol: 'file:', slashes: true })); // Create the Application's main menu const template = [ { label: 'Edit', submenu: [ {label: 'Cut', accelerator: 'CmdOrCtrl+X', selector: 'cut:'}, {label: 'Copy', accelerator: 'CmdOrCtrl+C', selector: 'copy:'}, {label: 'Paste', accelerator: 'CmdOrCtrl+V', selector: 'paste:'}, ] } ]; const menu = Menu.buildFromTemplate(template); Menu.setApplicationMenu(menu); // if dev if (serve) { require('electron-reload')(__dirname, { electron: require(`${__dirname}/node_modules/electron`) }); win.loadURL('http://localhost:4200'); win.webContents.openDevTools(); // if prod } else { if (local) { win.webContents.openDevTools(); } win.loadURL(url.format({ pathname: path.join(__dirname, 'dist/index.html'), protocol: 'file:', slashes: true })); } // Show win when all is set win.once('ready-to-show', () => { setTimeout(() => { splashWindow.destroy(); win.show(); }, 1000); }); // Emitted when the window is closed. win.on('closed', () => { // Dereference the window object, usually you would store window // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. win = null; }); globalShortcut.register('f5', () => win.reload()); // startAPI(); } try { // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.on('ready', createWindow); // Quit when all windows are closed. app.on('window-all-closed', () => { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q axios.get(apiUrl + 'exit') .then(res => console.log('axios res: ', res)); if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { // On OS X it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (win === null) { createWindow(); } }); } catch (e) { // Catch Error // throw e; } ",jarPath 155,"import ""@nomiclabs/hardhat-waffle""; import ""hardhat-gas-reporter""; import ""hardhat-typechain""; import { task } from ""hardhat/config""; task(""accounts"", ""Prints the list of accounts"", async (args, [MASK] ) => { const accounts = await [MASK] .ethers.getSigners(); for (const account of accounts) { console.log(account.address); } }); // // This is a sample Buidler task. To learn how to create your own go to // // https://buidler.dev/guides/create-task.html // task(""accounts"", ""Prints the list of accounts"", async (taskArgs, bre) => { // const accounts = await bre.ethers.getSigners(); // for (const account of accounts) { // console.log(await account.getAddress()); // } // }); // You have to export an object to set up your config // This object can have the following optional entries: // defaultNetwork, networks, solc, and paths. // Go to https://buidler.dev/config/ to learn more module.exports = { // This is a sample solc configuration that specifies which version of solc to use solidity: { version: ""0.8.10"", settings: { optimizer: { enabled: true } } }, networks: { hardhat: { mining: { auto: false, interval: [3000, 6000] }, timeout: 2000000, accounts: [ { privateKey: ""0xc5e8f61d1ab959b397eecc0a37a6517b8e67a0e7cf1f4bce5591f3ed80199122"", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: ""0xee9d129c1997549ee09c0757af5939b2483d80ad649a0eda68e8b0357ad11131"", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: ""0x275cc4a2bfd4f612625204a20a2280ab53a6da2d14860c47a9f5affe58ad86d4"", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: ""0x2a8aede924268f84156a00761de73998dac7bf703408754b776ff3f873bcec60"", balance: ""4951760157141521099596496895"" }, { privateKey: ""0x8b24fd94f1ce869d81a34b95351e7f97b2cd88a891d5c00abc33d0ec9501902e"", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: ""0x28d1bfbbafe9d1d4f5a11c3c16ab6bf9084de48d99fbac4058bdfa3c80b2908e"", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" }, { privateKey: """", balance: ""4951760157141521099596496895"" } ] } }, typechain: { outDir: ""typechain"", target: ""ethers-v5"", runOnCompile: true }, gasReporter: { enabled: true }, mocha: { timeout: 2000000 } }; ",hre 156,"/* eslint-disable no-unused-vars */ import axios, { AxiosInstance } from ""axios""; import { CreateParams, CreateResult, DataProvider, DeleteManyParams, DeleteManyResult, DeleteParams, DeleteResult, GetListParams, GetListResult, GetManyParams, GetManyReferenceParams, GetManyReferenceResult, GetManyResult, GetOneParams, GetOneResult, Identifier, RaRecord, UpdateManyParams, UpdateManyResult, UpdateParams, UpdateResult } from ""react-admin""; import logger, { Logger } from 'loglevel'; import uniqueId from 'lodash/uniqueId'; export class DataProviderImpl { private static storage = new Map(); private logger: Logger = logger.getLogger('provider:' + this.resource) constructor(private readonly resource: string, private readonly http: AxiosInstance) {} public async getList(params: GetListParams): Promise> { const msg = ` [${uniqueId()}] ${DataProviderImpl.name} ${this.getList.name}` this.logger.debug('REQUEST' + msg, params); try { let response; if (params.filter && typeof params.filter === 'object' && Reflect.has(params.filter, 'q')) { response = await this.http.get(`${this.resource}/search/query?${this.getQs(params)}`); } else { response = await this.http.get(`${this.resource}?${this.getQs(params)}`); } this.logger.debug('RESPONSE' + msg, response); return { data: response.data._embedded[this.resource], total: response.data.page.totalElements }; } catch (e) { this.logger.error('ERROR' + msg, e); throw e; } } protected getQs(params: GetListParams): URLSearchParams { const qs = new URLSearchParams(); qs.append('page', `${params.pagination.page - 1}`); qs.append('size', params.pagination.perPage.toString()); qs.append('sort', `${params.sort.field},${params.sort.order.toLowerCase()}`); if (!!params.filter && typeof params.filter === 'object') { Object.entries(params.filter).forEach(([key, value]) => { if (!value) return; qs.append(key, value.toString()); }) } return qs; } public async getOne(params: GetOneParams): Promise> { const msg = ` [${uniqueId()}] ${DataProviderImpl.name} ${this.getOne.name}` this.logger.debug('REQUEST' + msg, params); try { const response = await this.http.get(`/${this.resource}/${encodeURI(params.id.toString())}`); this.logger.debug('RESPONSE' + msg, response); return { data: response.data }; } catch (e) { this.logger.error('ERROR' + msg, e); throw e; } } public async getMany(params: GetManyParams): Promise> { throw new Error('Not implemented'); } public async getManyReference(params: GetManyReferenceParams): Promise> { throw new Error('Not implemented'); } public async update(params: UpdateParams): Promise> { const msg = ` [${uniqueId()}] ${DataProviderImpl.name} ${this.update.name}` this.logger.debug('REQUEST' + msg, params); try { const response = await this.http.put(`${this.resource}/${encodeURI(params.id.toString())}`, params.data); this.logger.debug('RESPONSE' + msg, response); return { data: response.data }; } catch (e) { this.logger.error('ERROR' + msg, e); throw e; } } public async updateMany(params: UpdateManyParams): Promise> { throw new Error('Not implemented'); } public async create(params: CreateParams): Promise> { const msg = ` [${uniqueId()}] ${DataProviderImpl.name} ${this.create.name}` this.logger.debug('REQUEST' + msg, params); try { const response = await this.http.post(`${this.resource}`, params.data); this.logger.debug('RESPONSE' + msg, response); return { data: response.data }; } catch (e) { this.logger.error('ERROR' + msg, e); throw e; } } public async delete(params: DeleteParams): Promise> { const msg = ` [${uniqueId()}] ${DataProviderImpl.name} ${this.delete.name}` this.logger.debug('REQUEST' + msg, params); try { const response = await this.http.delete(`${this.resource}/${encodeURI(params.id.toString())}`); this.logger.debug('RESPONSE' + msg, response); return { data: response.data }; } catch (e) { this.logger.error('ERROR' + msg, e); throw e; } } public async deleteMany(params: DeleteManyParams): Promise> { await Promise.all(params.ids.map(id => this.delete({ id }))) return { data: params.ids }; } public static getProvider(http: AxiosInstance): DataProvider { return new Proxy({} as DataProvider, { get(_, property) { return (resource: string, ...other: unknown[]) => { if (!DataProviderImpl.storage.has(resource)) !DataProviderImpl.storage.set(resource, new DataProviderImpl(resource, http)); const [MASK] = DataProviderImpl.storage.get(resource)!; if (!Reflect.has( [MASK] , property)) throw new Error(`Method ${property.toString()} not implemented`); return Reflect.apply(Reflect.get( [MASK] , property), [MASK] , other); } } }); } } ",instance 157,"import { Socket } from 'socket.io'; import { ClientId, SessionCode, SessionId, } from '../collabTypes/collabShadowTypes'; import { CollabServerSessionState, SocketId } from './types'; export type SessionsGetter = () => Record; class SessionLookupHelper { getSessions: SessionsGetter; constructor(getSessions: SessionsGetter) { this.getSessions = getSessions; } sessionIdAndSocketIdToClientId( sessionId: SessionId, socketId: SocketId ): ClientId | null { const session = this.getSessions()[sessionId]; if (session === undefined) { console.error(`Could not find session with ID: ${sessionId}`); return null; } // TODO(chloe): O(1) lookup const clientId = Object.keys(session.sockets).find( (potentialClientId) => session.sockets[potentialClientId].id === socketId ); if (clientId === undefined) { console.error(`Could not find client ID for session: ${session}`); return null; } return clientId; } socketIdToSession(socketId: SocketId): CollabServerSessionState | null { // TODO(chloe): O(1) lookup const session = Object.values(this.getSessions()).find((potentialSession) => Object.values(potentialSession.sockets).some( (socket) => socket.id === socketId ) ); if (session === undefined) { console.error(`Could not find client ID for socket ID: ${socketId}`); return null; } return session; } socketIdToClientId(socketId: SocketId): ClientId | null { const session = this.socketIdToSession(socketId); if (session === null) { return null; } const foundClientId = Object.keys(session.sockets).find( (clientId) => session.sockets[clientId].id === socketId ); if (foundClientId === undefined) { return null; } return foundClientId; } clientIdToSocket(clientId: ClientId): Socket | null { // TODO(chloe): O(1) lookup const [MASK] = Object.values(this.getSessions()).find((session) => session.clients.some((client) => client.id === clientId) ); if ( [MASK] === undefined) { console.error(`Could not find session for client ID: ${clientId}`); return null; } const clientSocket = [MASK] .sockets[clientId]; if (clientSocket === undefined) { console.log( `Could not find socket for client ID: ${clientId} and session: ${ [MASK] }` ); return null; } return clientSocket; } findSessionByCode(sessionCode: SessionCode): CollabServerSessionState | null { // TODO(chloe): O(1) lookup const foundSession = Object.values(this.getSessions()).find( (session) => session.code === sessionCode ); return foundSession ?? null; } } export default SessionLookupHelper; ",clientSession 158,"import createDataContext from ""./createDataContext""; import * as SecureStore from 'expo-secure-store'; import weightApi from ""../api/weight""; interface ActionData { type: string, payload?: any } export interface StateData { token: string | undefined, errorMessage: string | undefined, isSignin?: boolean } type DispatchFn = (action: ActionData) => void; const authReducer = ( [MASK] : StateData, action: ActionData): StateData | undefined => { switch (action.type) { case ""clear_error"": return { ... [MASK] , errorMessage: """" } case ""add_error"": return { ... [MASK] , errorMessage: action.payload } case ""signin"": return { errorMessage: """", token: action.payload }; case ""signout"": return { errorMessage: """", token: undefined }; default: break; } } const tryLocalSignin = (dispatch: DispatchFn) => async () => { const token = await SecureStore.getItemAsync(""token"").then().catch((err) => dispatch({ type: ""add_error"", payload: err })); if (token) dispatch({ type: ""signin"", payload: token }); } const clearError = (dispatch: DispatchFn) => () => { dispatch({ type: ""clear_error"" }); } const signup = (dispatch: DispatchFn) => async (email: string, password: string) => { try { const response = await weightApi.post(""/signup"", { email, password }); await SecureStore.setItemAsync(""token"", response.data.token); dispatch({ type: ""signin"", payload: response.data.token }); } catch (err) { dispatch({ type: ""add_error"", payload: ""Something went wrong while signing up!"" }); } } const signin = (dispatch: DispatchFn) => async (email: string, password: string) => { try { const response = await weightApi.post(""/login"", { email, password }); console.log(response.data.token); await SecureStore.setItemAsync(""token"", response.data.token); dispatch({ type: ""signin"", payload: response.data.token }); } catch (err) { dispatch({ type: ""add_error"", payload: ""Something went wrong while signing in!"" }); } } const signout = (dispatch: DispatchFn) => async () => { await SecureStore.deleteItemAsync(""token""); dispatch({ type: ""signout"" }); } export const { Provider, Context } = createDataContext( authReducer, { tryLocalSignin, clearError, signup, signin, signout }, { token: undefined, errorMessage: """" } );",state 159,"import { Component, Input } from '@angular/core'; import { JobPost } from '../models/jobpost'; import { POSData } from '../models/pos'; import { NgFor, NgIf } from '@angular/common'; import { PosComponentComponent } from '../pos-component/pos-component.component'; import { KeywordDisplayComponent } from '../keyword-display/keyword-display.component'; import { EntityDisplayComponent } from '../entity-display/entity-display.component'; @Component({ selector: 'app-job-post-details', standalone: true, imports: [ NgFor, NgIf, PosComponentComponent, KeywordDisplayComponent, EntityDisplayComponent ], templateUrl: './job-post-details.component.html', styleUrl: './job-post-details.component.scss' }) export class JobPostDetailsComponent { @Input() post?: JobPost; getKeys( [MASK] : POSData | undefined): string[] { if (! [MASK] ){ return []; } return Object.keys( [MASK] ); } } ",obj 160,"/// /** * 模块System.Core * * 这儿放公有代码和扩展代码 */ module System { export class Console { static _buffer = ''; static _buflen = 80; // 立即向控制台写出一行数据 static WriteLine(buf: any) { if (this._buffer.length > 0) this.Flush(); window.console && window.console.log(buf); } // 将数据写入到一行中 // 需要调用Flush刷新缓冲区,缓冲区的长度为80,超过80后会被立刻输出 // 或者下一次调用WriteLine自动刷新缓冲区 static Write(buf: any) { do { if (this._buffer.length >= this._buflen) { this.WriteLine(this._buffer); this._buffer = ''; break; } var _tmp = buf; if ((this._buffer.length + _tmp.length) >= this._buflen) { var pos = this._buflen - this._buffer.length; this._buffer += _tmp.substr(0, pos); this.WriteLine(this._buffer); this._buffer = _tmp.substr(pos); break; } this._buffer += _tmp; } while (0); } static WriteObject( [MASK] : any) { console.log( [MASK] ); } static Flush() { var _tmp = this._buffer; // 避免堆栈递归调用. this._buffer = ''; this.WriteLine(_tmp); } } }",obj 161,"import { GoogleGenerativeAI, HarmBlockThreshold, HarmCategory, } from ""@google/generative-ai""; import type { Content, GenerateContentRequest } from ""@google/generative-ai""; import { threeDimensionalPrinter } from ""./models""; import { readFile } from ""node:fs/promises""; import { join } from ""node:path""; const apiKey = process.env.GEMINI_API_KEY; const genAI = new GoogleGenerativeAI(apiKey!); const IMAGE_DIR = ""./resources""; export const model = genAI.getGenerativeModel({ model: ""gemini-1.5-flash"", generationConfig: { temperature: 1, topP: 0.95, topK: 64, maxOutputTokens: 4096, responseMimeType: ""text/plain"", }, }); async function urlToGenerativePart(url: URL | string) { console.log(url); const result = await fetch(url.toString().trim()); const data = await result.arrayBuffer(); const mimeType = result.headers.get(""Content-Type""); return { inlineData: { mimeType, data: `data:${mimeType};base64,${Buffer.from(data).toString(""base64"")}`, }, }; } async function fileToGenerativePart(path: string, mimeType = ""image/png"") { const data = await readFile(path); return { inlineData: { mimeType, data: Buffer.from(data).toString(""base64"") }, }; } export async function geminiImagePrompt( prompt: string, [MASK] : string[], ) { const parts: Array = [ prompt ]; for (const image of [MASK] ) { parts.push( image.startsWith(""http"") ? await urlToGenerativePart(image) : await fileToGenerativePart(join(__dirname, IMAGE_DIR, image)), ); } const result = await model.generateContent({ contents: [ ...threeDimensionalPrinter, { role: ""user"", parts, } ] }); return result.response.text().trim() .replace(/`+/, """") .split(""\n""); } export async function gemini(prompt: string) { if (prompt.includes("" image-ref "")) { const [promptText, ...images] = prompt.split("" image-ref ""); return geminiImagePrompt(promptText.replace("" image-ref "", """").trim(), images); } else { console.log('No image ref: ', prompt); } const result = ( await model.generateContent({ contents: [ ...threeDimensionalPrinter, { role: ""user"", parts: [ { text: prompt, }, ], }, ], }) ).response .text() .trim() .replace(/`+/, """") .split(""\n""); return result; } ",referenceImages 162,"/* Copyright NetFoundry Inc. 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 https://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. */ import { ZitiBrowzerCore, ZITI_CONSTANTS } from '@openziti/ziti-browzer-core'; import EventEmitter from 'events'; import { InMemoryCache, ICache, CacheManager, CacheEntry, CACHE_KEY_ID_TOKEN_SUFFIX, DecodedToken, } from './cache'; import { CacheKeyManifest } from './cache/key-manifest'; import { CACHE_LOCATION_MEMORY, DEFAULT_NOW_PROVIDER, ZITI_BROWSER_CLIENT_EVENT_NO_SERVICE, ZITI_BROWSER_CLIENT_EVENT_NO_CONFIG_FOR_HOSTNAME, ZITI_BROWSER_CLIENT_EVENT_SESSION_CREATION_ERROR, } from './constants'; import { ZitiBrowserClientOptions, AuthorizationParams, CacheLocation, } from './global'; import { cacheFactory } from './ZitiBrowserClient.utils'; import pjson from '../package.json'; import { buildInfo } from './buildInfo'; declare global { interface Window { _zitiContext?: object; } } /** * ZitiBrowserClient: * * This is the main class that Web Applications should interface with */ export class ZitiBrowserClient extends EventEmitter { private readonly cacheManager: CacheManager; private readonly nowProvider: () => number | Promise; private readonly zitiBrowzerCore: ZitiBrowzerCore; // eslint-disable-next-line private readonly zitiContext: any; // eslint-disable-next-line private readonly logger: any; private readonly userCache: ICache = new InMemoryCache().enclosedCache; private readonly options: ZitiBrowserClientOptions & { authorizationParams: AuthorizationParams; }; private readonly defaultOptions: Partial = { // set some defaults logLevel: 'warn', logPrefix: 'Ziti-SDK-Browser', // set some defaults authorizationParams: { controllerHost: 'ctrl.ziti.netfoundry.io', controllerPort: 443, }, }; /** * To support the ZitiBrowserClient.ready property */ private _readyPromise: Promise; private _resolveReady!: () => void; /** * ZitiBrowserClient ctor * * @param options */ constructor(options: ZitiBrowserClientOptions) { super(); this.options = { ...this.defaultOptions, ...options, authorizationParams: { ...this.defaultOptions.authorizationParams, ...options.authorizationParams, }, }; this._readyPromise = new Promise((resolve) => { this._resolveReady = resolve; }); this.zitiBrowzerCore = new ZitiBrowzerCore({}); this.logger = this.zitiBrowzerCore.createZitiLogger({ logLevel: this.options.logLevel, suffix: this.options.logPrefix, }); this.logger.info(`ctor: start`); this.zitiContext = this.zitiBrowzerCore.createZitiContext({ logger: this.logger, controllerApi: `https://${this.options.authorizationParams.controllerHost}:${this.options.authorizationParams.controllerPort}/edge/client/v1`, sdkType: pjson.name, sdkVersion: pjson.version, sdkBranch: buildInfo.sdkBranch, sdkRevision: buildInfo.sdkRevision, token_type: 'Bearer', }); this.logger.info(`ctor: ZitiContext created`); window._zitiContext = this.zitiContext; // allow WASM to find us this.zitiContext.setKeyTypeEC(); this.zitiContext.createEnroller(); this.zitiContext.setCurrentAPISession({ token: this.options.authorizationParams.apiSessionToken, }); this.logger.info( `apiSessionToken now set to [${this.options.authorizationParams.apiSessionToken}]` ); let cacheLocation: CacheLocation | undefined; let cache: ICache; if (options.cache) { cache = options.cache; } else { cacheLocation = options.cacheLocation || CACHE_LOCATION_MEMORY; if (!cacheFactory(cacheLocation)) { throw new Error(`Invalid cache location ""${cacheLocation}""`); } cache = cacheFactory(cacheLocation)(); } this.nowProvider = this.options.nowProvider || DEFAULT_NOW_PROVIDER; this.cacheManager = new CacheManager( cache, !cache.allKeys ? new CacheKeyManifest( cache, this.options.authorizationParams.controllerHost || 'ziti-sdk-browser' ) : undefined, this.nowProvider ); this.logger.info(`ctor: completed`); setTimeout( async (self) => { self._ready(); }, 10, this ); } private async _initializeZitiContext() { await this.zitiContext.sdk_initialize_loadWASM({ jspi: true, }); } /** ----------------------------------------------------------- * PUBLIC APIs * ----------------------------------------------------------*/ /** * ```js * zitiBrowserClient.ready; * ``` * * Do not return/resolve until the SDK is fully initialized */ public get ready(): Promise { return this._readyPromise; } private async _ready() { async function zitiBrowserClientInit(zitiBrowserClient: ZitiBrowserClient) { let result = await zitiBrowserClient._init(); if (!result) { throw new Error('zitiBrowserClient was not correctly initialized.'); } } /* Test to make sure everything works. */ try { await zitiBrowserClientInit(this); } catch (err) { throw new Error('zitiBrowserClient failed to load:' + err); } this._resolveReady(); } private async _init(): Promise { // Load the WebAssembly (for various PKI and TLS functionality) try { await this.getWASMInstance(); } catch (e) { throw new Error('WebAssembly load/init failed'); } // Obtain the ephemeral x509 cert used with mTLS to edge router try { let result = await this.enroll(); } catch (err) { throw new Error('ephemeral Cert acquisition failed'); } // Set up handlers for certain browZer core events this.zitiContext.on( ZITI_CONSTANTS.ZITI_EVENT_NO_SERVICE, this._noServiceEventHandler ); this.zitiContext.on( ZITI_CONSTANTS.ZITI_EVENT_NO_CONFIG_FOR_HOSTNAME, this._noConfigForHostnameEventHandler ); this.zitiContext.on( ZITI_CONSTANTS.ZITI_EVENT_SESSION_CREATION_ERROR, this._sessionCreationErrorEventHandler ); return true; } // Propagate the event out to our listeners private _noServiceEventHandler = (noServiceEvent: any) => { this.emit(ZITI_BROWSER_CLIENT_EVENT_NO_SERVICE, noServiceEvent); }; private _noConfigForHostnameEventHandler = ( noConfigForHostnameEvent: any ) => { this.emit( ZITI_BROWSER_CLIENT_EVENT_NO_CONFIG_FOR_HOSTNAME, noConfigForHostnameEvent ); }; private _sessionCreationErrorEventHandler = (noSessionEvent: any) => { this.emit(ZITI_BROWSER_CLIENT_EVENT_SESSION_CREATION_ERROR, noSessionEvent); }; /** * ```js * const result = zitiBrowserClient.setAccessToken(); * ``` * * Set the JWT to be used to auth with Ziti Controller. */ public setAccessToken(token: string): boolean { return this._setAccessToken(token); } /** * ```js * const result = zitiBrowserClient.setAPISessionToken(); * ``` * * Set the zt-session token to be used to make REST calls to the Ziti Controller. */ public setAPISessionToken(token: string): void { this._setAPISessionToken(token); } /** * ```js * const result = zitiBrowserClient.getFreshAPISession(); * ``` * * Authenticates with Ziti Controller. */ public getFreshAPISession(): boolean { return this._getFreshAPISession(); } /** * ```js * const result = zitiBrowserClient.fetchServices(); * ``` * * Authenticates with Ziti Controller. */ public async fetchServices(): Promise { return await this._fetchServices(); } /** * ```js * const result = zitiBrowserClient.enroll(); * ``` * * Does all PKI work necessary to obtain an ephemeral Cert from Ziti Controller. */ public async enroll(): Promise { return await this._enroll(); } /** * ```js * const result = zitiBrowserClient.printEphemeralCert(); * ``` * * Prints ephemeral Cert obtained from Ziti Controller to the console. */ public async printEphemeralCert(): Promise { return await this._printEphemeralCert(); } /** * ```js * const result = zitiBrowserClient.fetch(); * ``` * * tbw... */ public async fetch( resource: string | Request, options: RequestInit | null ): Promise { return await this._fetch(resource, options); } public async getWASMInstance(): Promise { await this._initializeZitiContext(); const [MASK] = await this._getWASMInstance(); return [MASK] ; } /** * ```js * const claims = await zitiBrowserClient.generateKeyPair(); * ``` * * Does stuff... */ public async generateKeyPair(): Promise { await this._initializeZitiContext(); const keypair = await this._generateKeyPair(); return keypair; } /** * ```js * await zitiBrowserClient.logout(); * ``` * * Clears the application session. * */ public async logout(): Promise {} private async _saveEntryInCache( entry: CacheEntry & { id_token: string; decodedToken: DecodedToken } ) { const { id_token, decodedToken, ...entryWithoutIdToken } = entry; this.userCache.set(CACHE_KEY_ID_TOKEN_SUFFIX, { id_token, decodedToken, }); await this.cacheManager.setIdToken( this.options.authorizationParams.controllerHost || 'ziti-sdk-browser', entry.id_token, entry.decodedToken ); await this.cacheManager.set(entryWithoutIdToken); } private _setAccessToken(token: string): boolean { return this.zitiContext.setAccessToken(token); } private _setAPISessionToken(token: string): void { this.zitiContext.setCurrentAPISession({ token: this.options.authorizationParams.apiSessionToken, }); this.logger.info( `apiSessionToken now set to [${this.options.authorizationParams.apiSessionToken}]` ); } private _getFreshAPISession(): boolean { return this.zitiContext.getFreshAPISession(); } private async _fetchServices(): Promise { return await this.zitiContext.fetchServices(); } private async _enroll(): Promise { let result = await this.zitiContext.enroll(); // this acquires an ephemeral Cert if (!result) { this.logger.error(`ephemeral Cert acquisition failed`); // If we couldn't acquire a cert, it most likely means that the JWT from the IdP needs a refresh throw new Error( `ephemeral Cert acquisition failed; IdP might not be registered with Ziti` ); } else { this.logger.info(`ephemeral Cert acquisition succeeded`); return result; } } private async _printEphemeralCert(): Promise { await this.zitiContext.printEphemeralCert(); // prints cert to console that was obtained by _enroll() } private async _fetch( resource: string | Request, options: RequestInit | null ): Promise { return await this.zitiContext.httpFetch(resource, options); } private async _getWASMInstance() { return await this.zitiContext.getWASMInstance(); } private async _generateKeyPair() { return await this.zitiContext.generateKeyPair(); } } ",wasm 163,"import { CallHandler, ExecutionContext, Inject, Injectable, NestInterceptor } from '@nestjs/common'; import { Observable, of, throwError } from 'rxjs'; import { first, map, tap } from 'rxjs/operators'; import { IncomingMessage, ServerResponse } from 'http'; import { JwtService } from '@nestjs/jwt'; import { ApiResult, ApiResultCode } from './common/api-result'; import { UserDto } from './user/user.dto'; import { UserAuth } from './user/user-auth'; import { Request, Response } from 'express-serve-static-core'; export class AuthInterceptor implements NestInterceptor { constructor(private readonly jwtService: JwtService) { } intercept(context: ExecutionContext, [MASK] : CallHandler): Observable { const ar = new ApiResult(); const http = context.switchToHttp(); const req = http.getRequest() as Request; const res = http.getResponse() as Response; const notAuthUrlList = [ '/api/users/login', '/api/systems/install', '/api/systems/installed', ]; // 不需要认证url if (notAuthUrlList.includes(req.url)) { return [MASK] .handle(); } const accessToken = req.headers.access_token; // access_token 为空,返回access_token无效 if (!accessToken) { ar.remind(ApiResultCode['103']); return of(ar); } const userAuth = this.jwtService.decode(accessToken.toString()) as UserAuth; if (userAuth === null) { ar.remind(ApiResultCode['103']); return of(ar); } if (new Date().getTime() > userAuth.exp * 1000) { ar.remind(ApiResultCode['104']); return of(ar); } return [MASK] .handle(); } }",next 164,"import { format } from 'date-fns-tz' console.log('YouTube Metadata Extension Loading') const displayTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone const menuElement = document.createElement('div') menuElement.style.backgroundColor = '#FFFFFFCC' menuElement.style.padding = '4px 16px' menuElement.style.fontSize = '12pt' menuElement.style.display = 'flex' menuElement.style.flexDirection = 'column' menuElement.style.zIndex = '999' menuElement.style.position = 'fixed' menuElement.style.left = '0px' menuElement.style.bottom = '0px' let intervalVideoObjectId: number | null = null let intervalChannelId: number | null = null const channelIdElement = document.createElement('div') const videoIdElement = document.createElement('div') const uploadDateElement = document.createElement('div') const startTimeElement = document.createElement('div') const endTimeElement = document.createElement('div') channelIdElement.innerText = 'チャンネルID' videoIdElement.innerText = '動画ID' uploadDateElement.innerText = 'アップロード日' startTimeElement.innerText = '開始時間' endTimeElement.innerText = '終了時間' const channelIdInputElement = document.createElement('input') const videoIdInputElement = document.createElement('input') const uploadDateInputElement = document.createElement('input') const startTimeInputElement = document.createElement('input') const endTimeInputElement = document.createElement('input') function clickToSelectAllHandler(event: MouseEvent) { if (!(event.target instanceof HTMLInputElement)) { throw Error('Unexpected event target type') } event.target.select() } channelIdInputElement.addEventListener('click', clickToSelectAllHandler) videoIdInputElement.addEventListener('click', clickToSelectAllHandler) uploadDateInputElement.addEventListener('click', clickToSelectAllHandler) startTimeInputElement.addEventListener('click', clickToSelectAllHandler) endTimeInputElement.addEventListener('click', clickToSelectAllHandler) menuElement.appendChild(channelIdElement) menuElement.appendChild(channelIdInputElement) menuElement.appendChild(videoIdElement) menuElement.appendChild(videoIdInputElement) menuElement.appendChild(uploadDateElement) menuElement.appendChild(uploadDateInputElement) menuElement.appendChild(startTimeElement) menuElement.appendChild(startTimeInputElement) menuElement.appendChild(endTimeElement) menuElement.appendChild(endTimeInputElement) document.body.appendChild(menuElement) function getVideoId() { const currentUrl = new URL(location.href) const paramVideoId = currentUrl.searchParams.get('v') if (paramVideoId != null) { return paramVideoId } const urlPath = currentUrl.pathname const liveUrlMatch = urlPath.match(/^\/live\/(.+)$/) if (liveUrlMatch != null) { return liveUrlMatch[1] } return null } function getChannelId() { const infoCardChannelAnchorElement = document.querySelector( '#infocard-channel-button > ytd-button-renderer > yt-button-shape > a', ) if (infoCardChannelAnchorElement != null) { const channelAboutUrlString = infoCardChannelAnchorElement.getAttribute('href') const channelAboutUrl = new URL(channelAboutUrlString, location.href) const channelAboutUrlMatch = channelAboutUrl.pathname.match(/^\/channel\/(.+)\/about$/) if (channelAboutUrlMatch != null) { return channelAboutUrlMatch[1] } } return null } function doIntervalChannelId() { const channelId = getChannelId() if (channelId != null) { channelIdInputElement.value = channelId // stop interval if loaded clearInterval(intervalChannelId) } } function doIntervalVideoObject() { const videoObjectElement = document.querySelector('#watch7-content') if (videoObjectElement == null) return const uploadDateElement: HTMLMetaElement | null = videoObjectElement.querySelector( 'meta[itemprop=""uploadDate""]', ) const [MASK] = uploadDateElement != null ? uploadDateElement.content : null uploadDateInputElement.value = [MASK] != null ? format(new Date( [MASK] ), ""yyyy-MM-dd'T'HH:mm:ssxxx"", { timeZone: displayTimezone, }) : '' const publicationElement = videoObjectElement.querySelector('span[itemprop=""publication""]') if (publicationElement != null) { const startDateElement: HTMLMetaElement | null = publicationElement.querySelector( 'meta[itemprop=""startDate""]', ) const startDateString = startDateElement != null ? startDateElement.content : null const endDateElement: HTMLMetaElement | null = publicationElement.querySelector( 'meta[itemprop=""endDate""]', ) const endDateString = endDateElement != null ? endDateElement.content : null startTimeInputElement.value = startDateString != null ? format(new Date(startDateString), ""yyyy-MM-dd'T'HH:mm:ssxxx"", { timeZone: displayTimezone, }) : '' endTimeInputElement.value = endDateString != null ? format(new Date(endDateString), ""yyyy-MM-dd'T'HH:mm:ssxxx"", { timeZone: displayTimezone, }) : '' } // stop interval if loaded clearInterval(intervalVideoObjectId) } const videoId = getVideoId() videoIdInputElement.value = videoId != null ? videoId : null intervalChannelId = setInterval(doIntervalChannelId, 100) intervalVideoObjectId = setInterval(doIntervalVideoObject, 100) ",uploadDateString 165,"import axios, { AxiosInstance } from 'axios'; import WebSocket from 'ws'; import { EventEmitter } from 'events'; export type Status = 'pending' | 'completed' | 'error'; export interface StatusClientOptions { serverUrl: string; useWebSocket?: boolean; pollingMethod?: 'fixed' | 'exponential' | 'adaptive'; initialDelay?: number; // milliseconds maxDelay?: number; // milliseconds maxRetries?: number; timeout?: number; // milliseconds } export class StatusClient extends EventEmitter { private readonly serverUrl: string; private readonly useWebSocket: boolean; private readonly pollingMethod: 'fixed' | 'exponential' | 'adaptive'; private readonly initialDelay: number; private readonly maxDelay: number; private readonly maxRetries: number; private readonly timeout: number; private readonly axiosInstance: AxiosInstance; private ws?: WebSocket; private pollingTimer?: NodeJS.Timeout; private timeoutTimer?: NodeJS.Timeout; private retries: number = 0; private isFinished: boolean = false; private lastDelay: number; // Event listener methods public on(event: 'connected', listener: () => void): this; public on(event: 'disconnected', listener: () => void): this; public on(event: 'statusUpdate', listener: (status: Status) => void): this; public on(event: 'finished', listener: (status: Status) => void): this; public on(event: 'error', listener: (error: Error) => void): this; public on(event: 'timeout', listener: () => void): this; public on(event: string, listener: (...args: any[]) => void): this { return super.on(event, listener); } constructor( [MASK] : StatusClientOptions) { super(); if (! [MASK] .serverUrl) { throw new Error('serverUrl is required.'); } this.serverUrl = [MASK] .serverUrl; this.useWebSocket = [MASK] .useWebSocket ?? true; this.pollingMethod = [MASK] .pollingMethod ?? 'fixed'; this.initialDelay = [MASK] .initialDelay ?? 1000; // Default 1 second this.maxDelay = [MASK] .maxDelay ?? 10000; // Default 10 seconds this.maxRetries = [MASK] .maxRetries ?? 50; this.timeout = [MASK] .timeout ?? 60000; // Default 60 seconds this.lastDelay = this.initialDelay; this.axiosInstance = axios.create({ baseURL: this.serverUrl, }); } public start(): void { if (this.isFinished) { throw new Error('Cannot start after completion. Create a new instance.'); } if (this.useWebSocket) { this.initWebSocket(); } else { this.initPolling(); } this.timeoutTimer = setTimeout(() => { this.emit('timeout'); this.cleanup(); }, this.timeout); } public stop(): void { this.cleanup(); } private initWebSocket(): void { try { const wsUrl = this.serverUrl.replace(/^http/, 'ws'); this.ws = new WebSocket(wsUrl); this.ws.on('open', () => { this.emit('connected'); }); this.ws.on('message', (data: WebSocket.Data) => { try { const message = JSON.parse(data.toString()); const status: Status = message.result; this.emit('statusUpdate', status); if (status === 'completed' || status === 'error') { this.emit('finished', status); this.cleanup(); } } catch (error) { this.emit('error', new Error('Invalid message format.')); } }); this.ws.on('error', (error) => { this.emit('error', error); this.cleanup(); }); this.ws.on('close', () => { if (!this.isFinished) { this.emit('disconnected'); } this.cleanup(); }); } catch (error) { this.emit('error', error); this.initPolling(); // Fallback to polling if WebSocket fails } } private initPolling(): void { this.pollStatus(); } private async pollStatus(): Promise { if (this.isFinished) { return; } try { const response = await this.axiosInstance.get('/status'); const status: Status = response.data.result; this.emit('statusUpdate', status); if (status === 'completed' || status === 'error') { this.emit('finished', status); this.cleanup(); return; } if (this.retries >= this.maxRetries) { this.emit('error', new Error('Max retries reached.')); this.cleanup(); return; } this.retries++; const nextDelay = this.calculateNextDelay(); this.pollingTimer = setTimeout(() => { this.pollStatus(); }, nextDelay); } catch (error) { this.emit('error', error); this.cleanup(); } } private calculateNextDelay(): number { let nextDelay: number; switch (this.pollingMethod) { case 'fixed': nextDelay = this.initialDelay; break; case 'exponential': nextDelay = Math.min(this.lastDelay * 2, this.maxDelay); break; case 'adaptive': // Increase delay if status remains 'pending' for a long time if (this.retries < 5) { nextDelay = this.initialDelay; } else if (this.retries < 10) { nextDelay = this.lastDelay + 1000; } else { nextDelay = this.maxDelay; } break; default: nextDelay = this.initialDelay; break; } this.lastDelay = nextDelay; return nextDelay; } private cleanup(): void { if (this.ws) { this.ws.removeAllListeners(); this.ws.close(); this.ws = undefined; } if (this.pollingTimer) { clearTimeout(this.pollingTimer); this.pollingTimer = undefined; } if (this.timeoutTimer) { clearTimeout(this.timeoutTimer); this.timeoutTimer = undefined; } this.isFinished = true; } }",options 166,"import { WMSOptions } from 'leaflet'; export interface LayerDefinition extends WMSOptions { layerIdentifier: string; authenticated?: boolean; url: string; cql_filter?: string; zIndexAbsolute?: boolean; } interface BaseLayerItem { label: string; key: string; } export interface LayerMenuItem extends BaseLayerItem { layerDefinitionId?: string; color?: string; nodes?: never; } export interface LayerMenuGroup extends BaseLayerItem { nodes: LayerMenuEntry[]; layerDefinitionId?: never; color?: never; } export type LayerMenuEntry = LayerMenuGroup | LayerMenuItem; export function isLayerItem(layerEntry?: LayerMenuEntry): layerEntry is LayerMenuItem { return layerEntry?.layerDefinitionId !== undefined; } export function isLayerGroup(layerEntry?: LayerMenuEntry): layerEntry is LayerMenuGroup { return layerEntry?.nodes !== undefined; } export function getChildrenIds( [MASK] : LayerMenuGroup): string[] { let keys: string[] = []; [MASK] .nodes.forEach(n => { if (isLayerItem(n)) { keys.push(n.layerDefinitionId); } else { keys = keys.concat(getChildrenIds(n)); } }); return keys; } ",rootEntry 167,"const createColorManager = (grey: [number, number, number], accent: [number, number, number]) => { const [r, g, b] = grey; const avg = Math.round((r + g + b) / 3); const isLight = avg > 127; const contrast = isLight ? [0, 0, 0] : [255, 255, 255]; return { isLight, avg, grey, accent, shade: (value: number) => { const [MASK] = isLight ? '0' : '255'; return `rgba(${ [MASK] },${ [MASK] },${ [MASK] },${value})`; }, shift: (value: number, opacity = 1) => { const r1 = Math.max(0, Math.min(255, r + (isLight ? value : -value))); const g1 = Math.max(0, Math.min(255, g + (isLight ? value : -value))); const b1 = Math.max(0, Math.min(255, b + (isLight ? value : -value))); return opacity === 1 ? `rgba(${r1},${g1},${b1},${opacity})` : `rgb(${r1},${g1},${b1})`; }, contrast: (opacity = 1) => `rgba(${contrast[0]},${contrast[1]},${contrast[2]},${opacity})`, }; }; export default createColorManager; ",base 168,"// Shell out to `npx wrangler@latest whoami` import { exec } from 'child_process' import { promisify } from 'util' import { AccountInfo, fetchInternal, FetchResult, getAuthTokens, isAccessTokenExpired, isDirectory, refreshToken, } from './utils/wrangler' import chalk from 'chalk' import os from 'node:os' import path from 'node:path' import fs from 'node:fs' import { fileURLToPath } from 'url' import { createDialog, endSection, logRaw, startSection, updateStatus } from './utils/c3' import { mcpCloudflareVersion } from './utils/helpers' import which from 'which' const __filename = fileURLToPath(import.meta.url) const execAsync = promisify(exec) export async function init( [MASK] : string | undefined) { logRaw( createDialog([ `👋 Welcome to ${chalk.yellow('mcp-server-cloudflare')} v${mcpCloudflareVersion}!`, `💁‍♀️ This ${chalk.green(""'init'"")} process will ensure you're connected to the Cloudflare API`, ` and install the Cloudflare MCP Server into Claude, Cline, Windsurf and Cursor (${chalk.blue.underline('https://claude.ai/download')})`, `ℹ️ For more information, visit ${chalk.blue.underline('https://github.com/GutMutCode/mcp-server-cloudflare')}`, `🧡 Let's get started.`, ]), ) startSection(`Checking for existing Wrangler auth info`, `Step 1 of 3`) updateStatus(chalk.gray(`If anything goes wrong, try running 'npx wrangler@latest login' manually and retrying.`)) try { getAuthTokens() } catch (e: any) { updateStatus(`${chalk.underline.red('Warning:')} ${chalk.gray(e.message)}`, false) updateStatus(`Running '${chalk.yellow('npx wrangler login')}' and retrying...`, false) const { stderr, stdout } = await execAsync('npx wrangler@latest login') if (stderr) updateStatus(chalk.gray(stderr)) getAuthTokens() } updateStatus(`Wrangler auth info loaded!`) if (isAccessTokenExpired()) { updateStatus(`Access token expired, refreshing...`, false) if (await refreshToken()) { updateStatus('Successfully refreshed access token') } else { throw new Error('Failed to refresh access token') } } endSection('Done') startSection(`Fetching account info`, `Step 2 of 3`) const { result: accounts } = await fetchInternal>('/accounts') let account: string switch (accounts.length) { case 0: throw new Error(`No accounts found. Run 'wrangler whoami' for more info.`) case 1: if ( [MASK] && [MASK] !== accounts[0].id) { throw new Error(`You don't have access to account ${ [MASK] }. Leave blank to use ${accounts[0].id}.`) } account = accounts[0].id break default: if (! [MASK] ) { throw new Error( `${chalk.red('Multiple accounts found.')}\nUse ${chalk.yellow('npx @gutmutcode/mcp-server-cloudflare init [account_id]')} to specify which account to use.\nYou have access to:\n${accounts.map((a) => ` • ${a.name} — ${a.id}`).join('\n')}`, ) } account = [MASK] break } updateStatus(`Using account: ${chalk.yellow(account)}`) endSection('Done') startSection(`Configuring MCP Clients`, `Step 3 of 3`) const configPaths = { cline: path.join( os.homedir(), 'Library', 'Application Support', 'Code', 'User', 'globalStorage', 'saoudrizwan.claude-dev', 'settings', 'cline_mcp_settings.json', ), claude: path.join(os.homedir(), 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json'), windsurf: path.join(os.homedir(), '.codeium', 'windsurf', 'mcp_config.json'), cursor: path.join(os.homedir(), '.cursor', 'mcp.json'), } // Define the valid client names type ClientName = 'cline' | 'claude' | 'windsurf' | 'cursor' const cloudflareConfig = { cline: { command: (await which('node')).trim(), args: [__filename, 'run', account], disabled: false, autoApprove: [], }, claude: { command: (await which('node')).trim(), args: [__filename, 'run', account], }, windsurf: { command: (await which('node')).trim(), args: [__filename, 'run', account], }, cursor: { command: (await which('node')).trim(), args: [__filename, 'run', account], }, } async function writeConfig(clientName: string, configPath: string) { try { updateStatus(`Configuring ${chalk.yellow(clientName)}...`) const configDir = path.dirname(configPath) if (!isDirectory(configDir)) { updateStatus(`${chalk.yellow(clientName)} config directory not found at: ${chalk.gray(configDir)}`, false) return false } const existingConfig = fs.existsSync(configPath) ? JSON.parse(fs.readFileSync(configPath, 'utf8')) : { mcpServers: {} } if ('cloudflare' in (existingConfig?.mcpServers || {})) { updateStatus( `${chalk.green('Note:')} Replacing existing Cloudflare MCP config in ${clientName}:\n${chalk.gray(JSON.stringify(existingConfig.mcpServers.cloudflare))}`, false, ) } const newConfig = { ...existingConfig, mcpServers: { ...existingConfig.mcpServers, cloudflare: cloudflareConfig[clientName as ClientName] || cloudflareConfig.cline, // Type-safe access }, } fs.writeFileSync(configPath, JSON.stringify(newConfig, null, 2)) updateStatus(`Successfully configured ${chalk.yellow(clientName)}!`, false) updateStatus(`Config written to: ${chalk.gray(configPath)}`, false) return true } catch (error: any) { updateStatus(`${chalk.red('Error')} configuring ${clientName}: ${error.message}`, false) return false } } let successCount = 0 for (const [clientName, configPath] of Object.entries(configPaths)) { if (await writeConfig(clientName, configPath)) { successCount++ } } if (successCount > 0) { updateStatus(chalk.green(`\nSuccessfully configured ${successCount} client(s)!`)) updateStatus( chalk.blue(`Try asking any configured client to ""tell me which Workers I have on my account"" to get started!`), ) } else { updateStatus(chalk.yellow('\nNo clients were configured. You may need to configure them manually.')) updateStatus( `Manual configuration example:\n${chalk.gray(JSON.stringify({ mcpServers: { cloudflare: cloudflareConfig } }, null, 2))}`, ) } endSection('Done') } ",accountTag 169,"export class PlacesOfGame{ data=[ { nombreLugar: 'Facultad de Economía', rutaFoto: '/assets/imgs/facultades/economia.jpg' }, { nombreLugar: 'Facultad de Ciencias Químicas', rutaFoto: '/assets/imgs/facultades/ciencias_quimicas.jpg' }, { nombreLugar: 'Facultad de Filosofía', rutaFoto: '/assets/imgs/facultades/filosofia.jpg' }, { nombreLugar: 'Facultad de Ingeniería', rutaFoto: '/assets/imgs/facultades/ingenieria.jpg' }, { nombreLugar: 'Facultad de Jurisprudencia', rutaFoto: '/assets/imgs/facultades/jurisprudencia.jpg' }, { nombreLugar: 'Facultad de Psicología', rutaFoto: '/assets/imgs/facultades/psicologia.jpg' }, { nombreLugar: 'Biblioteca', rutaFoto: '/assets/imgs/facultades/biblioteca.jpg' }, { nombreLugar: 'Departamento de cultura física', rutaFoto: '/assets/imgs/facultades/fisica.png' } ] getPlacesOfGame( [MASK] ){ return this.data[ [MASK] -1]; } }",numPlace 170,"import * as vscode from 'vscode'; import { SQLClientExecutor } from './executor/SQLClientExecutor'; export class FlinkSQLExtension { executor: SQLClientExecutor; context: vscode.ExtensionContext; constructor(context: vscode.ExtensionContext) { this.context = context; this.executor = this.getExecutor(); } executeSql() { const documentText = this.getFullDocumentText(); if (documentText) { const separatedStatements = this.separateStatements(documentText); this.executor.executeSql(separatedStatements); } else { vscode.window.showErrorMessage('Cannot find active editor'); } } executeSelectedSql() { const documentText = this.getSelectedDocumentText(); if (documentText) { const separatedStatements = this.separateStatements(documentText); this.executor.executeSql(separatedStatements); } else { vscode.window.showErrorMessage('Cannot find active editor or did not select any message'); } } executeShortInput() { vscode.window.showInputBox().then(input => { if (input) { this.executor.executeShortCommand(input); } }); } getFullDocumentText(): string | null { const editor = vscode.window.activeTextEditor; if (editor) { const document = editor.document; return document.getText(); } return null; } getSelectedDocumentText(): string | null { const editor = vscode.window.activeTextEditor; if (editor && !editor.selection.isEmpty) { return editor.document.getText(editor.selection); } return null; } getActiveEditorFileName(): string | null { const editor = vscode.window.activeTextEditor; if (editor) { return editor.document.fileName; } return null; } getExecutor() { return new SQLClientExecutor(this.context); } terminateCLI(): void { this.executor.terminateCLI(); } separateStatements(statements: string) { const [MASK] = /;(?=(?:[^']*'[^']*')*[^']*$)/g; const separateReplace = ';\n\n'; return statements.replace( [MASK] , separateReplace); } } ",separateRegex 171,"/******************************************************************************** * Copyright (c) 2022 Microsoft and BMW Group AG * Copyright (c) 2022 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ import { type RouteComponentProps } from 'react-router-dom' import { type CompanyRole, type ConsentForCompanyRoles, } from '../data/companyDetails' import { type FetchBusinessPartnerDto } from '../data/companyDetailsById' import UserService from '../services/UserService' import { getApiBase } from '../services/EnvironmentService' import { ApplicationStatus, ApplicationType, } from '../state/features/application/applicationApiSlice' export function getCompanyDetails( oneId: string ): Promise { console.log('API called getCompanyDetails') const token = UserService.getToken() const u = `${getApiBase()}/api/registration/legalEntityAddress/${oneId}` const myResponseData: FetchBusinessPartnerDto[] = [] const promise = new Promise((resolve, reject) => { fetch(u, { method: 'GET', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', }, }) .then((res) => res.text().then((data) => { if (res.ok) { Object.assign(myResponseData, data ? JSON.parse(data) : {}) resolve(myResponseData) } else { reject(res.status) } }) ) .catch((error) => { // alert(error); console.log(error, error.message, error.status) reject(error.status) }) }) return promise } export function submitSendInvites(userInviteList: any): Promise { const tenant = UserService.getTenant() const token = UserService.getToken() const u = `${getApiBase()}/api/registration/tenant/${tenant}/users` const promise = new Promise((resolve, reject) => { fetch(u, { method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', }, body: JSON.stringify(userInviteList), }) .then((res) => res.text().then(() => { if (res.ok) { resolve('Sent Invite') } else { reject(res.status) } }) ) .catch((error) => { // alert(error); console.log(error, error.message, error.status) reject(error.status) }) }) return promise } export function getCompanyRoles(): Promise { const token = UserService.getToken() const u = `${getApiBase()}/api/registration/companyRoles` const companyRolesRes: CompanyRole[] = [] const promise = new Promise((resolve, reject) => { fetch(u, { method: 'GET', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', }, }) .then((val) => val.json().then((data) => { if (val.ok) { Object.assign(companyRolesRes, data) resolve(companyRolesRes) } else { reject(val.statusText) } }) ) .catch((error) => { alert(error) console.log(error, error.message, error.status) reject(error.message) }) }) return promise } export function getConsentForCompanyRoles( roleId: number ): Promise { const token = UserService.getToken() const u = `${getApiBase()}/api/registration/consentsForCompanyRole/${roleId}` const myConsentResponseData: ConsentForCompanyRoles[] = [] const promise = new Promise((resolve, reject) => { fetch(u, { method: 'GET', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', }, }) .then((val) => val.json().then((data) => { if (val.ok) { Object.assign(myConsentResponseData, data) resolve(myConsentResponseData) } else { reject(val.statusText) } }) ) .catch((error) => { alert(error) console.log(error, error.message, error.status) reject(error.message) }) }) return promise } export function getClientRolesComposite(): Promise { const token = UserService.getToken() const u = `${getApiBase()}/api/registration/rolesComposite` const userRolesRes: string[] = [] const promise = new Promise((resolve, reject) => { fetch(u, { method: 'GET', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', }, }) .then((res) => res.text().then((data) => { if (res.ok) { Object.assign(userRolesRes, data ? JSON.parse(data) : {}) resolve(userRolesRes) } else { reject(res.status) } }) ) .catch((error) => { // alert(error); console.log(error, error.message, error.status) reject(error.status) }) }) return promise } export function uploadDocument(file): Promise { const token = UserService.getToken() const u = `${getApiBase()}/api/registration/documents` const formdata = new FormData() formdata.append('document', file.file) return fetch(u, { method: 'POST', headers: { Authorization: `Bearer ${token}`, }, body: formdata, }) } export const downloadDocument = ( file, fileType = 'application/pdf', fileName = `${new Date().toDateString()}.pdf` ) => { const [MASK] = new Blob([file], { type: fileType, }) const url = URL.createObjectURL( [MASK] ) const a = document.createElement('a') a.href = url a.download = fileName a.click() } export function download(file: Blob, _fileType: string, fileName: string) { const url = URL.createObjectURL(file) const a = document.createElement('a') a.href = window.encodeURIComponent(url) a.download = fileName a.click() } export function handleStatusRedirect( status: ApplicationStatus, applicationType: ApplicationType, history: RouteComponentProps['history'] ) { if ( [ ApplicationStatus.SUBMITTED, ApplicationStatus.CONFIRMED, ApplicationStatus.DECLINED, ].includes(status) ) location.href = '/' else if (Object.values(ApplicationStatus).includes(status)) { if (applicationType === ApplicationType.INTERNAL) history.push('/landing') else location.href = '/consent_osp' } else history.push('/landing') } export const isObjectEmptyOrFalsy = (obj) => { // Check if the object is empty if (!obj || Object.keys(obj).length === 0) { return true } // Check if all values are false for (const key in obj) { if (obj[key]) { return false } } return true } ",blobFile 172,"import { STATUS_CODES } from 'http' import { ResourceNotFound, ServiceError } from './errors' import { log } from '../logger' /**Error Handler for uncaughtException * and unhandledRejection on main process */ export const httpError = (reply: any) => ( [MASK] = 500, error: any = 'Internal server Error') => reply.status( [MASK] ).send({ code: STATUS_CODES[ [MASK] ], message: error.message, errors: error.errors }) export const errorHandler = function (error: any, req: any, response: any, next: any) { const isError = true const replyError = httpError(response) switch (isError) { case error instanceof ResourceNotFound: log.warn(error) return replyError(404, { message: error.message, resource: error.resource }) case error instanceof ServiceError: log.warn(error) return response.status(400).send({ code: STATUS_CODES[400], message: error.message }) default: // Unknow error log.error(error) return response.status(500).send('Internal Server Error') } } ",httpStatus 173,"import { PrismaClient } from ""@prisma/client""; const prisma = new PrismaClient(); export async function addDog(dogphoto: string, dogname: string, doggender: string, dogfur:string, dogtemp: string, dogage: string, dogweight: string, dogdesc: string, dogowner:string, is_castrated: string, is_adoptable: string, dogobs: string) { await prisma.$connect(); const dog = await prisma.dog.create({ data: { photo: dogphoto, name: dogname, gender: doggender, fur: dogfur, temperament: dogtemp, age: dogage, weight: dogweight, //change to string description: dogdesc, owner_name: dogowner, is_castrated: is_castrated, is_adoptable: is_adoptable, observations: dogobs, } }); await prisma.$disconnect(); }; export async function updateDog(dog_id: string, dogphoto: string, dogname: string, doggender: string, dogfur:string, dogtemp: string, dogage: string, dogweight: string, dogdesc: string, dogowner:string, is_castrated: string, is_adoptable: string, dogobs: string) { await prisma.$connect(); const dog = await prisma.dog.update({ where: { id: dog_id }, data: { photo: dogphoto, name: dogname, gender: doggender, fur: dogfur, temperament: dogtemp, age: dogage, weight: dogweight, //change to string description: dogdesc, owner_name: dogowner, is_castrated: is_castrated, is_adoptable: is_adoptable, observations: dogobs, } }); await prisma.$disconnect(); }; export async function deleteDog (dog_id: string) { await prisma.$connect(); const dog = await prisma.dog.delete({ where: { id: dog_id } }); await prisma.$disconnect(); } // arrumar isso export async function addRegd(dog_id: string, is_fed: string, qt_fed: string, obs: string) { prisma.$connect; const dog = await prisma.daily.create({ data: { dog_id: dog_id, is_fed: is_fed, qt_fed: qt_fed, observations: obs, date: new Date() } }); await prisma.$disconnect(); } export async function addRegm(dog_id: string, complaint: string, appearance: string, hydration_status: string, suspicion: string, weight: string, temperature: string, anotation: string, diagnosis: string, doctor: string, date: string, time: string, budget: string){ await prisma.$connect(); const dog = await prisma.medical.create({ data: { dog_id: dog_id, complaint: complaint, appearance: appearance, hydration_status: hydration_status, suspicion: suspicion, weight: weight, temperature: temperature, anotation: anotation, diagnosis: diagnosis, doctor: doctor, date: date, time: time, budget: budget, } }); await prisma.$disconnect(); } // Upload Image FUNCTION export async function uploadImage(dog_id: string, [MASK] : string) { await prisma.$connect(); const dog = await prisma.dog.update({ where: { id: dog_id }, data: { photo: [MASK] , } }); await prisma.$disconnect(); } ",image 174,"import { AccessoryConfig, AccessoryPlugin, API, Logging, Service, } from 'homebridge'; import { AirConditionerAPI, State, Mode, Fixation, Fanspeed } from 'broadlink-aircon-api'; export class AirCondionerAccessory implements AccessoryPlugin { private readonly log: Logging; private readonly api: API; private readonly name: string; private airConditionerAPI: AirConditionerAPI; private lastRotationSpeed = Fanspeed.medium; private lastTurbo = State.off; private lastMute = State.off; private readonly service: Service; private readonly informationService: Service; private readonly display: Service | undefined; private readonly health: Service | undefined; private readonly clean: Service | undefined; private readonly mildew: Service | undefined; private readonly sleep: Service | undefined; private readonly auto: Service | undefined; private showDisplay = false; private showHealth = false; private showClean = false; private showMildew = false; private showSleep = false; private showAuto = false; services: Service[] private swing = 3; constructor(log: Logging, [MASK] : AccessoryConfig, api: API) { this.log = log; this.name = [MASK] .name; this.api = api; this.services = []; let ip = '0.0.0.0'; let mac = 'ff:ff:ff:ff:ff:ff'; if (('ip' in [MASK] ) && ('mac' in [MASK] )) { ip = [MASK] ['ip'] as string; mac = [MASK] ['mac'] as string; } else { log.error('ip or mac is not provided'); } this.airConditionerAPI = new AirConditionerAPI(ip, mac); let increments = 0.5; if ('increments' in [MASK] ) { increments = [MASK] ['increments'] as number; } if ('swing' in [MASK] ) { this.swing = [MASK] ['swing'] as number; } if ('display' in [MASK] ) { this.showDisplay = [MASK] ['display'] as boolean; } if ('health' in [MASK] ) { this.showHealth = [MASK] ['health'] as boolean; } if ('clean' in [MASK] ) { this.showClean = [MASK] ['clean'] as boolean; } if ('mildew' in [MASK] ) { this.showMildew = [MASK] ['mildew'] as boolean; } if ('sleep' in [MASK] ) { this.showSleep = [MASK] ['sleep'] as boolean; } if ('auto' in [MASK] ) { this.showAuto = [MASK] ['auto'] as boolean; } this.service = new this.api.hap.Service.HeaterCooler; this.service.getCharacteristic(api.hap.Characteristic.Active) .on('get', this.handleActiveGet.bind(this)) .on('set', this.handleActiveSet.bind(this)); this.service.getCharacteristic(api.hap.Characteristic.CurrentHeaterCoolerState) .on('get', this.handleCurrentHeaterCoolerStateGet.bind(this)); this.service.getCharacteristic(api.hap.Characteristic.TargetHeaterCoolerState) .on('get', this.handleTargetHeaterCoolerStateGet.bind(this)) .on('set', this.handleTargetHeaterCoolerStateSet.bind(this)); this.service.getCharacteristic(api.hap.Characteristic.CurrentTemperature) .on('get', this.handleCurrentTemperatureGet.bind(this)); this.service.getCharacteristic(api.hap.Characteristic.CoolingThresholdTemperature) .on('get', this.handleThresholdTemperatureGet.bind(this)) .on('set', this.handleThresholdTemperatureSet.bind(this)); this.service.getCharacteristic(api.hap.Characteristic.HeatingThresholdTemperature) .on('get', this.handleThresholdTemperatureGet.bind(this)) .on('set', this.handleThresholdTemperatureSet.bind(this)); this.service.getCharacteristic(api.hap.Characteristic.RotationSpeed) .on('get', this.handleRotationSpeedGet.bind(this)) .on('set', this.handleRotationSpeedSet.bind(this)); this.service.getCharacteristic(api.hap.Characteristic.SwingMode) .on('get', this.handleSwingGet.bind(this)) .on('set', this.handleSwingSet.bind(this)); this.service.getCharacteristic(api.hap.Characteristic.CoolingThresholdTemperature).props.minValue = 16; this.service.getCharacteristic(api.hap.Characteristic.CoolingThresholdTemperature).props.maxValue = 32; this.service.getCharacteristic(api.hap.Characteristic.HeatingThresholdTemperature).props.minValue = 16; this.service.getCharacteristic(api.hap.Characteristic.HeatingThresholdTemperature).props.maxValue = 32; this.service.getCharacteristic(api.hap.Characteristic.CoolingThresholdTemperature).props.minStep = increments; this.service.getCharacteristic(api.hap.Characteristic.HeatingThresholdTemperature).props.minStep = increments; this.services.push(this.service); this.informationService = new api.hap.Service.AccessoryInformation() .setCharacteristic(api.hap.Characteristic.Manufacturer, 'AUX') .setCharacteristic(api.hap.Characteristic.Model, 'Broadlink'); this.services.push(this.informationService); if (this.showDisplay) { this.display = new api.hap.Service.Switch('Display', 'Display'); this.display.getCharacteristic(api.hap.Characteristic.On) .on('get', this.handleDisplayGet.bind(this)) .on('set', this.handleDisplaySet.bind(this)); this.services.push(this.display); } if (this.showHealth) { this.health = new api.hap.Service.Switch('Health', 'Health'); this.health.getCharacteristic(api.hap.Characteristic.On) .on('get', this.handleHealthGet.bind(this)) .on('set', this.handleHealthSet.bind(this)); this.services.push(this.health); } if (this.showClean) { this.clean = new api.hap.Service.Switch('Clean', 'Clean'); this.clean.getCharacteristic(api.hap.Characteristic.On) .on('get', this.handleCleanGet.bind(this)) .on('set', this.handleCleanSet.bind(this)); this.services.push(this.clean); } if (this.showMildew) { this.mildew = new api.hap.Service.Switch('Mildew', 'Mildew'); this.mildew.getCharacteristic(api.hap.Characteristic.On) .on('get', this.handleMildewGet.bind(this)) .on('set', this.handleMildewSet.bind(this)); this.services.push(this.mildew); } if (this.showSleep) { this.sleep = new api.hap.Service.Switch('Sleep', 'Sleep'); this.sleep.getCharacteristic(api.hap.Characteristic.On) .on('get', this.handleSleepGet.bind(this)) .on('set', this.handleSleepSet.bind(this)); this.services.push(this.sleep); } if (this.showAuto) { this.auto = new api.hap.Service.Switch('Auto', 'Auto'); this.auto.getCharacteristic(api.hap.Characteristic.On) .on('get', this.handleAutoGet.bind(this)) .on('set', this.handleAutoSet.bind(this)); this.services.push(this.auto); } api.on('didFinishLaunching', () => { this.airConditionerAPI.connect(); }); setInterval(() => { this.airConditionerAPI.getState(); }, 5000); this.airConditionerAPI.on('updateState', () => { this.service.getCharacteristic(api.hap.Characteristic.CoolingThresholdTemperature).updateValue(this.thresholdTemperature()); this.service.getCharacteristic(api.hap.Characteristic.HeatingThresholdTemperature).updateValue(this.thresholdTemperature()); this.service.getCharacteristic(api.hap.Characteristic.CurrentHeaterCoolerState).updateValue(this.currentHeaterCoolerState()); this.service.getCharacteristic(api.hap.Characteristic.TargetHeaterCoolerState).updateValue(this.targetHeaterCoolerState()); this.service.getCharacteristic(api.hap.Characteristic.Active).updateValue(this.active()); this.service.getCharacteristic(api.hap.Characteristic.CurrentTemperature).updateValue(this.currentTemperature()); this.service.getCharacteristic(api.hap.Characteristic.SwingMode).updateValue(this.swingValue()); this.updateRotationSpeed(); if (this.showDisplay) { this.display!.getCharacteristic(api.hap.Characteristic.On).updateValue(this.displayValue()); } if (this.showHealth) { this.health!.getCharacteristic(api.hap.Characteristic.On).updateValue(this.healthValue()); } if (this.showClean) { this.clean!.getCharacteristic(api.hap.Characteristic.On).updateValue(this.cleanValue()); } if (this.showMildew) { this.mildew!.getCharacteristic(api.hap.Characteristic.On).updateValue(this.mildewValue()); } if (this.showSleep) { this.sleep!.getCharacteristic(api.hap.Characteristic.On).updateValue(this.sleepValue()); } this.updateAuto(); }); } updateRotationSpeed() { this.service.getCharacteristic(this.api.hap.Characteristic.RotationSpeed).updateValue(this.rotationSpeed()); } updateAuto() { if (this.showAuto) { this.auto!.getCharacteristic(this.api.hap.Characteristic.On).updateValue(this.autoValue()); } } getServices(): Service[] { return this.services; } active(): number { let currentValue = 0; if (this.airConditionerAPI.model.power === State.on) { currentValue = 1; } return currentValue; } handleActiveGet(callback) { this.log.debug('Triggered GET Active'); const currentValue = this.active(); callback(null, currentValue); } handleActiveSet(value, callback) { this.log.debug('Triggered SET Active:', value); if (value === 1) { this.airConditionerAPI.setPower(State.on); } else { this.airConditionerAPI.setPower(State.off); } callback(null); } private currentHeaterCoolerState(): number { let currentValue = this.api.hap.Characteristic.CurrentHeaterCoolerState.INACTIVE; if (this.airConditionerAPI.model.mode === Mode.cooling) { currentValue = this.api.hap.Characteristic.CurrentHeaterCoolerState.COOLING; } else if (this.airConditionerAPI.model.mode === Mode.heating) { currentValue = this.api.hap.Characteristic.CurrentHeaterCoolerState.HEATING; } else { currentValue = this.api.hap.Characteristic.CurrentHeaterCoolerState.IDLE; } return currentValue; } handleCurrentHeaterCoolerStateGet(callback) { this.log.debug('Triggered GET CurrentHeaterCoolerState'); const currentValue = this.currentHeaterCoolerState(); callback(null, currentValue); } private targetHeaterCoolerState(): number { let currentValue = this.api.hap.Characteristic.TargetHeaterCoolerState.AUTO; if (this.airConditionerAPI.model.mode === Mode.cooling) { currentValue = this.api.hap.Characteristic.TargetHeaterCoolerState.COOL; } else if (this.airConditionerAPI.model.mode === Mode.heating) { currentValue = this.api.hap.Characteristic.TargetHeaterCoolerState.HEAT; } else if (this.airConditionerAPI.model.mode === Mode.auto) { currentValue = this.api.hap.Characteristic.TargetHeaterCoolerState.AUTO; } return currentValue; } handleTargetHeaterCoolerStateGet(callback) { this.log.debug('Triggered GET TargetHeaterCoolerState'); const currentValue = this.targetHeaterCoolerState(); callback(null, currentValue); } handleTargetHeaterCoolerStateSet(value, callback) { this.log.debug('Triggered SET TargetHeaterCoolerState:', value); if (value === this.api.hap.Characteristic.TargetHeaterCoolerState.AUTO) { this.airConditionerAPI.setMode(Mode.auto); } else if (value === this.api.hap.Characteristic.TargetHeaterCoolerState.COOL) { this.airConditionerAPI.setMode(Mode.cooling); } else if (value === this.api.hap.Characteristic.TargetHeaterCoolerState.HEAT) { this.airConditionerAPI.setMode(Mode.heating); } callback(null); } private currentTemperature(): number { return this.airConditionerAPI.model.ambientTemp; } handleCurrentTemperatureGet(callback) { this.log.debug('Triggered GET CurrentTemperature'); const currentValue = this.currentTemperature(); callback(null, currentValue); } handleThresholdTemperatureSet(value, callback) { this.log.debug('Triggered SET ThresholdTemperature:', value); this.airConditionerAPI.setTemp(value); callback(null); } private thresholdTemperature(): number { return this.airConditionerAPI.model.temp; } handleThresholdTemperatureGet(callback) { this.log.debug('Triggered GET ThresholdTemperature'); const currentValue = this.thresholdTemperature(); callback(null, currentValue); } private rotationSpeed(): number { let currentValue = 1; if (this.airConditionerAPI.model.turbo === State.on) { currentValue = 100; } else if (this.airConditionerAPI.model.mute === State.on) { currentValue = 10; } else if (this.airConditionerAPI.model.fanspeed === Fanspeed.high) { currentValue = 60; } else if (this.airConditionerAPI.model.fanspeed === Fanspeed.medium) { currentValue = 40; } else if (this.airConditionerAPI.model.fanspeed === Fanspeed.low) { currentValue = 20; } return currentValue; } handleRotationSpeedGet(callback) { this.log.debug('Triggered GET RotationSpeed'); const currentValue = this.rotationSpeed(); callback(null, currentValue); } handleRotationSpeedSet(value, callback) { this.log.debug('Triggered SET RotationSpeed:', value); if (value > 1 && value <= 19) { this.airConditionerAPI.setSpeed(this.lastRotationSpeed, State.off, State.on); this.lastTurbo = State.off; this.lastMute = State.on; } else if (value > 19 && value <= 39) { this.airConditionerAPI.setSpeed(Fanspeed.low, State.off, State.off); this.lastRotationSpeed = Fanspeed.low; this.lastTurbo = State.off; this.lastMute = State.off; } else if (value > 39 && value <= 59) { this.airConditionerAPI.setSpeed(Fanspeed.medium, State.off, State.off); this.lastRotationSpeed = Fanspeed.medium; this.lastTurbo = State.off; this.lastMute = State.off; } else if (value > 59 && value <= 79) { this.airConditionerAPI.setSpeed(Fanspeed.high, State.off, State.off); this.lastRotationSpeed = Fanspeed.high; this.lastTurbo = State.off; this.lastMute = State.off; } else if (value > 79) { this.airConditionerAPI.setSpeed(this.lastRotationSpeed, State.on, State.off); this.lastTurbo = State.on; this.lastMute = State.off; } this.updateAuto(); callback(null); } handleDisplaySet(value, callback) { this.log.debug('Triggered SET Display:', value); if (value === true) { this.airConditionerAPI.setDisplay(State.on); } else { this.airConditionerAPI.setDisplay(State.off); } callback(null); } private displayValue(): boolean { return this.airConditionerAPI.model.display === State.on; } handleDisplayGet(callback) { this.log.debug('Triggered GET Display'); const currentValue = this.displayValue(); callback(null, currentValue); } handleSwingSet(value, callback) { this.log.debug('Triggered SET Swing:', value); if (value === 1) { if (this.swing === 1) { this.airConditionerAPI.setSwing(Fixation.off, Fixation.on); } else if (this.swing === 2) { this.airConditionerAPI.setSwing(Fixation.on, Fixation.off); } else if (this.swing === 3) { this.airConditionerAPI.setSwing(Fixation.on, Fixation.on); } } else { this.airConditionerAPI.setSwing(Fixation.off, Fixation.off); } callback(null); } private swingValue(): number { if (this.swing === 1) { if (this.airConditionerAPI.model.horizontalFixation === Fixation.on) { return 1; } else { return 0; } } else if (this.swing === 2) { if (this.airConditionerAPI.model.verticalFixation === Fixation.on) { return 1; } else { return 0; } } else if (this.swing === 3) { // eslint-disable-next-line max-len if (this.airConditionerAPI.model.verticalFixation === Fixation.on && this.airConditionerAPI.model.horizontalFixation === Fixation.on) { return 1; } else { return 0; } } return 0; } handleSwingGet(callback) { this.log.debug('Triggered GET Swing'); const currentValue = this.swingValue(); callback(null, currentValue); } handleHealthSet(value, callback) { this.log.debug('Triggered SET Health:', value); if (value === true) { this.airConditionerAPI.setHealth(State.on); } else { this.airConditionerAPI.setHealth(State.off); } callback(null); } private healthValue(): boolean { return this.airConditionerAPI.model.health === State.on; } handleHealthGet(callback) { this.log.debug('Triggered GET Health'); const currentValue = this.healthValue(); callback(null, currentValue); } handleCleanSet(value, callback) { this.log.debug('Triggered SET Clean:', value); if (value === true) { this.airConditionerAPI.setClean(State.on); } else { this.airConditionerAPI.setClean(State.off); } callback(null); } private cleanValue(): boolean { return this.airConditionerAPI.model.clean === State.on; } handleCleanGet(callback) { this.log.debug('Triggered GET Clean'); const currentValue = this.cleanValue(); callback(null, currentValue); } handleMildewSet(value, callback) { this.log.debug('Triggered SET Mildew:', value); if (value === true) { this.airConditionerAPI.setMildew(State.on); } else { this.airConditionerAPI.setMildew(State.off); } callback(null); } private mildewValue(): boolean { return this.airConditionerAPI.model.mildew === State.on; } handleMildewGet(callback) { this.log.debug('Triggered GET Mildew'); const currentValue = this.mildewValue(); callback(null, currentValue); } handleSleepSet(value, callback) { this.log.debug('Triggered SET Sleep:', value); if (value === true) { this.airConditionerAPI.setSleep(State.on); } else { this.airConditionerAPI.setSleep(State.off); } callback(null); } private sleepValue(): boolean { return this.airConditionerAPI.model.sleep === State.on; } handleSleepGet(callback) { this.log.debug('Triggered GET Sleep'); const currentValue = this.sleepValue(); callback(null, currentValue); } handleAutoSet(value, callback) { this.log.debug('Triggered SET Auto:', value); if (value === true) { this.airConditionerAPI.setSpeed(Fanspeed.auto, State.off, State.off); } else { this.airConditionerAPI.setSpeed(this.lastRotationSpeed, this.lastTurbo, this.lastMute); } this.updateRotationSpeed(); callback(null); } private autoValue(): boolean { return this.airConditionerAPI.model.fanspeed === Fanspeed.auto; } handleAutoGet(callback) { this.log.debug('Triggered GET Auto'); const currentValue = this.autoValue(); callback(null, currentValue); } }",config 175,"// CircuitTomlGenerator.ts import { MerkleTree } from './MerkleTree'; import { Fr, BarretenbergSync } from '@aztec/bb.js'; export class NoirCircuitTomlGenerator { private tree: MerkleTree; private depositMap: Map; constructor() { this.tree = new MerkleTree(8); this.depositMap = new Map(); } async init() { await this.tree.initialize([]); } /** Pads a number to 32-byte hex and wraps in an Fr. */ private numToFr(num: number): Fr { const hex = num.toString(16).padStart(64, '0'); return Fr.fromString('0x' + hex); } /** * Perform the off-chain deposit: * 1) compute commitment = PedersenHash(id, r) * 2) record oldRoot + proof path * 3) insert commitment into tree * 4) record `{id,r}` in the map under this index * 5) return all fields needed for the deposit.toml */ gentoml(circuitType: 'deposit', id: Fr, r: Fr): string; /** * Generate a withdraw.toml by: * 1) looking up `{id,r}` from the map by index * 2) querying `this.tree.proof(index)` for the current path + root */ gentoml(circuitType: 'withdraw', index: number): string; gentoml( circuitType: 'deposit' | 'withdraw', [MASK] : any, param2?: any ): string { if (circuitType === 'deposit') { const id: Fr = [MASK] ; const r: Fr = param2!; const idx = this.tree.totalLeaves; const idxFr = this.numToFr(idx); // 1) get pre-deposit state const oldRoot = this.tree.root(); const proof = this.tree.proof(idx); const hashPath = proof.pathElements; // 2) compute & insert commitment const commitment = this.tree.bb.pedersenHash([id, r], 0); this.tree.insert(commitment); const newRoot = this.tree.root(); // 3) record just {id,r} this.depositMap.set(idx, { id, r }); // 4) emit deposit.toml return ` id = ""${id.toString()}"" r = ""${r.toString()}"" oldPath = [${hashPath.map((fr) => `""${fr.toString()}""`).join(', ')}] oldRoot = ""${oldRoot.toString()}"" newRoot = ""${newRoot.toString()}"" commitment = ""${commitment.toString()}"" index = ""${idxFr.toString()}"" `.trim(); } else { const idx: number = [MASK] ; const entry = this.depositMap.get(idx); if (!entry) { throw new Error(`No deposit found at index ${idx}`); } const { id, r } = entry; const idxFr = this.numToFr(idx); // re-compute proof against current tree state const proof = this.tree.proof(idx); const hashPath = proof.pathElements; const root = proof.root; return ` r = ""${r.toString()}"" index = ""${idxFr.toString()}"" hashpath = [${hashPath.map((fr) => `""${fr.toString()}""`).join(', ')}] root = ""${root.toString()}"" id = ""${id.toString()}"" `.trim(); } } } ",param1 176,"import { BasicAuth, Columns, Trino } from 'trino-client'; const trino: Trino = Trino.create({ server: 'http://localhost:8080', catalog: 'postgresql,tpcds,mssql', schema: 'public,sf1,dbo', auth:new BasicAuth('test') }); var outputData: { [key: string]: any; }[] export async function getDBData(allCustomerQuery: string){ const iter = await trino.query(allCustomerQuery); for await (const queryResult of iter) { console.log(queryResult.data); if(queryResult.data === undefined) continue; console.log(queryResult.columns); var columns: string[]=[]; for (const column of queryResult.columns as Columns) { const nameValue : string = column.name; console.log(column.name); columns.push(column.name); console.log(`Column array value: ${column.name}`); } outputData = queryResult.data?.map(item=>{ const obj:{[key:string]: any} = {}; columns.forEach(( [MASK] ,index)=>{ obj[ [MASK] ] = item[index]; }); return obj; }); console.log(outputData); } return outputData; }",propertyName 177,"import {ExtensionContext} from 'vscode'; import {LanguageClient, LanguageClientOptions, ServerOptions} from 'vscode-languageclient/node'; import * as path from ""node:path""; let client: LanguageClient; /** * Build arguments for ralph-lsp.jar initialisation. * * @param release `true` to build args for publishing, else `false` for development. */ function build_args(release: boolean) { const dirName = __dirname; const [MASK] = path.resolve(dirName, 'ralph-lsp.jar'); let args: string[]; if (release) { args = [""-jar"", [MASK] ]; // arguments for plugin release } else { const logsPath = path.resolve(dirName, ""../../""); // path for logs args = [""-jar"", `-DRALPH_LSP_LOG_HOME=${logsPath}`, [MASK] ]; // arguments for local development } return args; } export function activate(context: ExtensionContext) { console.log(""Activating Ralph LSP client""); const args = build_args(true); const serverOptions: ServerOptions = { command: ""java"", args: args }; const clientOptions: LanguageClientOptions = { documentSelector: [ {pattern: '**/*.ral'}, {pattern: '**/alephium.config.ts'}, {language: 'json', pattern: '**/ralph.json'}, ] }; // Create the client and store it. client = new LanguageClient( 'ralph-lsp', 'Ralph LSP', serverOptions, clientOptions ); // Start the client. client.start(); } export function deactivate(): Thenable | undefined { if (!client) { return undefined; } return client.stop(); } ",jarPath 178,"import moment = require('moment'); const prefixKey = ""x_reactk_"", userIdKey = prefixKey + ""user_id"", urlKey = prefixKey + ""url"", userAgentKey = prefixKey + ""user_agent"", languageKey = prefixKey + ""language"", platformKey = prefixKey + ""platform"", screenWidthKey = prefixKey + ""screen_width"", screenHeightKey = prefixKey + ""screen_height"", navigatorProductKey = prefixKey + ""navigator_product"", refererKey = prefixKey + ""referer""; export class ReactKEvent { uid?: string; day: string; created_date: string; payload: {}; client_id: string; type: string; constructor(clientId: string, eventType: string) { this.payload = {}; this.client_id = clientId; this.type = eventType; let t = moment(); t.utcOffset(0); // TODO improve to change timezone this.created_date = t.format(""YYYY-MM-DD[T]HH:mm:ss[Z]""); this.day = t.format(""YYYY-MM-DD""); this.setReferer().setUserAgent().setLanguage().setProduct().setPlatform().setScreenSize(); } setUID( [MASK] : string): ReactKEvent { this.uid = [MASK] ; return this; } setUserId(id: string): ReactKEvent { this.payload[userIdKey] = id; return this; } setPayload(payload: {}): ReactKEvent { for (let key in payload) { if (key.substr(0, prefixKey.length) != prefixKey) { this.payload[key] = payload[key]; } } return this; } setUrl(id: string): ReactKEvent { this.payload[urlKey] = id; return this; } setReferer(): ReactKEvent { if (document && document.referrer) { this.payload[refererKey] = document.referrer; } return this; } setUserAgent(): ReactKEvent { if (navigator && navigator.userAgent) { this.payload[userAgentKey] = navigator.userAgent; } return this; } setLanguage(): ReactKEvent { if (navigator && navigator.language) { this.payload[languageKey] = navigator.language; } return this; } setPlatform(): ReactKEvent { if (navigator && navigator.platform) { this.payload[platformKey] = navigator.platform; } return this; } setProduct(): ReactKEvent { if (navigator && navigator.product) { this.payload[navigatorProductKey] = navigator.product; } return this; } setScreenSize(): ReactKEvent { if (screen && screen.width) { this.payload[screenWidthKey] = screen.width; } if (screen && screen.height) { this.payload[screenHeightKey] = screen.height; } return this; } }",value 179,"import { api } from '../services/api'; import { DatumCharacters, ICharacters } from '../interfaces/'; import { useState, useEffect } from 'react'; interface Props { charactersAnime: DatumCharacters | null; isLoading: boolean; } export const useAnimeCharacters = (animeId: string) => { const [charactersList, setCharactersList] = useState({ charactersAnime: null, isLoading: true, }); const getData = async () => { const response = await api.get(`/anime/${animeId}/characters`); const characters = response.data.data; const charactersData = characters.map(async (character) => { const [MASK] = await api.get( `/anime-characters/${character.id}/character` ); return [MASK] .data.data; }); const charactersDataResolved = await Promise.all(charactersData); // console.log(charactersDataResolved); setCharactersList({ charactersAnime: charactersDataResolved, isLoading: false, }); }; useEffect(() => { getData(); }, []); return { ...charactersList, }; }; ",characterData 180,"import type { PlainJsonObject, CompressionTable, MangoQuery } from './types'; /** * compress the keys of an object via the compression-table * @recursive */ export function compressObject( table: CompressionTable, obj: PlainJsonObject ): PlainJsonObject { if (typeof obj !== 'object' || obj === null) return obj; else if (Array.isArray(obj)) { // array return obj .map(item => compressObject(table, item)); } else { // object const ret: PlainJsonObject = {}; const keys = Object.keys(obj); for (let index = 0; index < keys.length; index++) { const key = keys[index]; const compressedKey = compressedAndFlaggedKey( table, key as any ); const value = compressObject( table, obj[key as any] ); ret[compressedKey] = value; } return ret; } } /** * transform an object-path * into its compressed version * e.g: * - input: 'names[1].firstName' * - ouput: '|a[1].|b' */ export function compressedPath( table: CompressionTable, path: string ): string { const splitted = path.split('.'); return splitted .map(subKey => { const compressedKey = compressedAndFlaggedKey( table, subKey ); return compressedKey; }).join('.'); } export function throwErrorIfCompressionFlagUsed( table: CompressionTable, key: string ) { if (key.startsWith(table.compressionFlag)) { throw new Error( 'cannot compress objects that start with the compression-flag: ' + table.compressionFlag + ' on key ' + key ); } } export function compressedAndFlaggedKey( table: CompressionTable, key: string ): string { throwErrorIfCompressionFlagUsed( table, key ); /** * keys could be array-accessors like myArray[4] * we have to split and read the squared brackets value */ const [MASK] = key.split('['); const plainKey = [MASK] .shift() as string; const compressedKey = table.compressedToUncompressed.get(plainKey); if (!compressedKey) { return key; } else { const readdSquared = [MASK] .length ? '[' + [MASK] .join('[') : ''; return table.compressionFlag + compressedKey + readdSquared; } } /** * compress a mango-query * so that it can be used to find documents * in a database where all documents are compressed */ export function compressQuery( table: CompressionTable, query: MangoQuery ): MangoQuery { const ret: MangoQuery = { selector: compressQuerySelector( table, query.selector ) }; if (query.skip) ret.skip = query.skip; if (query.limit) ret.limit = query.limit; if (query.fields) { ret.fields = query.fields .map(field => compressedPath( table, field )); } if (query.sort) { if (Array.isArray(query.sort)) { ret.sort = (query.sort as any[]).map((item: string | any) => { if (typeof item === 'string') { const hasMinus = item.startsWith('-'); if (hasMinus) { item = item.substr(1); } let compressedField = compressedPath( table, item ); if (hasMinus) { compressedField = '-' + compressedField; } return compressedField; } else { return compressQuerySelector( table, item ); } }); } else { const compressedSort: any = {}; // do not use Object.entries, it is transpiled shitty Object.keys(query.sort).forEach(key => { const direction = (query as any).sort[key]; const compressedField = compressedPath( table, key ); compressedSort[compressedField] = direction; }); ret.sort = compressedSort; } } return ret; } /** * @recursive */ export function compressQuerySelector( table: CompressionTable, selector: any ): any { if (Array.isArray(selector)) { return selector.map(item => compressQuerySelector(table, item)); } else if (selector instanceof RegExp) { return selector; } else if (typeof selector === 'object' && selector !== null) { const ret: any = {}; Object.keys(selector).forEach(key => { let useKey; if (key.startsWith('$')) { // operator useKey = key; } else { // property path useKey = compressedPath( table, key ); } ret[useKey] = compressQuerySelector( table, selector[key] ); }); return ret; } else { return selector; } } ",splitSquaredBrackets 181,"import AzuraSocket from ""./gateway/websocket""; import { ClientEvents, IAzuraClientConstructorOptions } from ""../lib/types""; import { APIRequester } from ""./rest/api""; import { TypedEmitter } from ""tiny-typed-emitter""; import { UsersCache } from ""./cache/users-cache""; export default class AzuraClient extends TypedEmitter { public ws: AzuraSocket; public api: APIRequester; public users: UsersCache; public token: string; protected debug = false; public constructor({ token, debug }: IAzuraClientConstructorOptions) { super(); this.ws = new AzuraSocket(this); this.users = new UsersCache(this); this.api = new APIRequester(token); this.token = token; this.debug = debug ?? false; this.setupEventListeners(); } private setupEventListeners() { this.on(""debug"", ( [MASK] ) => { console.log( [MASK] ); }); } public login() { this.ws.connect(); } public sendDebug(...message: (string | number | boolean)[]) { if (this.debug) { this.emit( ""debug"", `[DEBUG (${new Date().toLocaleDateString()} at ${new Date().toLocaleTimeString()})]: ${message.join( "" "", )}`, ); } } } ",msg 182," import { Response, NextFunction } from ""express"" import asyncHandler from ""../../../helpers/async""; import { SuccessResponse, SuccessMsgResponse } from '../../../core/ApiResponse'; import { BadRequestError } from ""../../../core/ApiError""; // import { FileRepo } from ""./image.repository"" import { v2 as cloudinary } from ""cloudinary""; import { CloudinaryResponse } from ""./interface"" import { FileService } from './file.service' import { FileRepo } from ""./image.repository""; // import { NoDataError, BadRequestError } from '../../../core/ApiError'; // import _ from 'lodash'; export class FileController { readonly fileService: FileService = new FileService() uploadOnCloudinary = async (req: any): Promise => { const fileData: any = req.files; cloudinary.config({ cloud_name: 'dairwfrpv', api_key: '759452217818743', api_secret: '' }); const [MASK] = { use_filename: true, unique_filename: false, overwrite: true }; try { let uploadedFile = await cloudinary.uploader.upload(fileData.image.path, [MASK] ); return { path: uploadedFile.secure_url, fileSize: uploadedFile.bytes, fileType: `${uploadedFile.resource_type}/${uploadedFile.format}`, fileName: uploadedFile.original_filename }; } catch (error: any) { throw new BadRequestError(error.message || ""Image Upload Field""); } } // fileUpload = asyncHandler( // async (req: any, res: Response, next: NextFunction): Promise => { // const { path, size, type, name }: any = req.files.file; // const { destPath }: { destPath: string } = req.query; // const file = await this.service.uploadFileToS3({ // fileName: name, // filePath: path, // folderName: destPath // }); // // const { file } = await FileRepo.create(uploaded); // new SuccessResponse('Added successfully', { file }).send(res); // } // ) // downloadFolder = asyncHandler( // async (req: any, res: Response, next: NextFunction): Promise => { // // const { path, size, type, name }: any = req.files.file; // // console.log('===================================='); // // console.log(path); // // console.log('===================================='); // // const { destPath }: { destPath: string } = req.query; // await this.service.downloadS3FolderAsZip({ // folderPath: ""faizan/"", // zipFilePath: ""/home/faizan_ahmed/Code/test.zip"" // }); // // const { file } = await FileRepo.create(uploaded); // new SuccessResponse('Added successfully', {}).send(res); // } // ) videoUploadToS3 = asyncHandler( async (req: any, res: Response, next: NextFunction): Promise => { const source = await this.fileService.uploadOnS3({ file: req.files.file }) //@ts-ignore console.log(""files Data"",source.Location.startsWith('h') ? source.Location : `https://${source.Location}`) const { file } = await FileRepo.create({ // @ts-ignore // private_source_url: `${source.Location}`, private_source_url: source.Location.startsWith('h') ? source.Location : `https://${source.Location}`, // @ts-ignore // public_source_url: `${source.Location}`, public_source_url: source.Location.startsWith('h') ? source.Location : `https://${source.Location}`, size: `${req.files.file.size}`, dimensions: `0 x 0`, length: ""jjjjj"", type: `${req.files.file.type}`, folderId:req.query.folderId } as any); new SuccessResponse('Added successfully', { file }).send(res); } ) // imageUpload = asyncHandler( // async (req: any, res: Response, next: NextFunction): Promise => { // const uploaded: CloudinaryResponse = await this.uploadOnCloudinary(req) // const { file } = await FileRepo.create(uploaded); // new SuccessResponse('Added successfully', file).send(res); // } // ) // imageUploadForEditor = asyncHandler( // async (req: any, res: Response, next: NextFunction): Promise => { // const uploaded: CloudinaryResponse = await this.uploadOnCloudinary(req) // const { file } = await FileRepo.create(uploaded); // res.send({ // success: 1, // file: { // url: file.path, // } // }); // } // ) // name = asyncHandler( // async (req: any, res: Response, next: NextFunction): Promise => { // } // ) }",options 183,"import {Injectable} from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, } from '@angular/common/http'; import {Observable} from 'rxjs'; @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor() { } intercept( request: HttpRequest, [MASK] : HttpHandler ): Observable> { request = this.addToken(request); return [MASK] .handle(request); } private addToken(request: HttpRequest): HttpRequest { const authorizationCustom = this.getAuthorizationCustom(request); const auth = window.btoa('angularApp' + ':' + '12345'); request = request.clone({ setHeaders: { Authorization: `Basic ${auth}`, 'Content-type': this.getContentType(request), }, }); return request; } getAuthorizationCustom(request: any): string { if (request.url.indexOf('/oauth/token') > 0) { return `Basic angularApp:12345`; } else { return `Bearer asdfghjk123`; } } getContentType(request: HttpRequest): string { if ((request.url.includes('/impuesto/registrar') || request.url.includes('/contribuyente/editar') || request.method === 'PUT' || request.method === 'POST') && !request.url.includes('/security/oauth/token')) { return 'application/json'; } else { return 'application/x-www-form-urlencoded'; } } } ",next 184,"import { HighlightResult, HighlightOptions, HLJSApi } from 'highlight.js' export = function hljsCodeDiff (hljs: HLJSApi): HLJSApi { function highlight (code: string, options: HighlightOptions): HighlightResult { if (!options.language.startsWith('diff:')) { return hljs.highlight(code, options) } const actualLanguage = options.language.slice('diff:'.length) const diffLines = code.split('\n') const codeWithoutDiffMarkers = diffLines.map(line => line.slice(1)).join('\n') const result = hljs.highlight(codeWithoutDiffMarkers, { ...options, language: actualLanguage }) const highlightedLines = result.value.split('\n') if (highlightedLines.length !== diffLines.length) { // Output lines didn't match input, this is unexpected, fall back to plain diff console.warn('[highlightjs-code-diff] failed to highlight because of line count mismatch') return hljs.highlight(code, { ...options, language: 'diff' }) } const codeDiff = highlightedLines.map((line, i) => { const [MASK] = diffLines[i].slice(0, 1) switch ( [MASK] ) { case '+': return `+${line}` case '-': return `-${line}` default: return `${ [MASK] }${line}` } }).join('\n') return { ...result, code, value: codeDiff, language: options.language } } return { ...hljs, highlight (codeOrLanguageName: string, optionsOrCode: string | HighlightOptions, ignoreIllegals?: boolean): HighlightResult { return typeof optionsOrCode === 'string' ? highlight(optionsOrCode, { language: codeOrLanguageName, ignoreIllegals }) : highlight(codeOrLanguageName, optionsOrCode) } } } ",diffMarker 185,"/* istanbul ignore file */ import {Xsd} from './Namespaces'; import * as SparqlJs from 'sparqljs'; import {BgpPattern, IriTerm, Pattern, Query, Wildcard} from 'sparqljs'; // import {Triple, IriTerm, BlankTerm, VariableTerm, QuadTerm} from const SparqlGenerator = new SparqlJs.Generator(); type S = SparqlJs.IriTerm | SparqlJs.BlankTerm | SparqlJs.VariableTerm; type P = SparqlJs.IriTerm | SparqlJs.VariableTerm | SparqlJs.PropertyPath; type O = S | SparqlJs.LiteralTerm; export type TTerm = P | O; type T = SparqlJs.Triple; export type POS = 'subject' | 'predicate' | 'object'; export class RdfUtils { /** find triples matching (s, p, o) * could move to Bgp, but is always invokes on a List */ static pmatch (l: P, r: P): boolean { return RdfUtils.isPath(l) && RdfUtils.isPath(r) ? RdfUtils.pathEquals(l, r) : RdfUtils.isPath(l) || RdfUtils.isPath(r) ? false : l.equals(r); } static pathEquals (l: SparqlJs.PropertyPath, r: SparqlJs.PropertyPath): boolean { return l.type === r.type && l.pathType === r.pathType && !l.items.find( (il, iNo) => !RdfUtils.pmatch(il, r.items[iNo]) ); } static isPath (t: TTerm): t is SparqlJs.PropertyPath { return (t as SparqlJs.PropertyPath).type === ""path""; } static getMatching (triplePatterns: T[], s: S | null, p: P | null, o: O | null): SparqlJs.Triple[] { return triplePatterns.filter(tp => (s === null || tp.subject.equals(s)) && (p === null || RdfUtils.pmatch(tp.predicate, p)) && (o === null || tp.object.equals(o)) ); } /** remove triples matching (s, p, o) */ static stealMatching (triplePatterns: T[], s: S | null, p: P | null, o: O | null): SparqlJs.Triple[] { const ret = []; for (let i = 0; i < triplePatterns.length; ++i) { const tp = triplePatterns[i]; if ((s === null || tp.subject.equals(s)) && (p === null || RdfUtils.pmatch(tp.predicate, p)) && (o === null || tp.object.equals(o))) { ret.push(tp); triplePatterns.splice(i, 1); --i; } } return ret; } /** Stringize a predicate * Used to sort arcs queried from graphs. */ static pStr (predicate: P): string { return !RdfUtils.isPath(predicate) ? '<' + predicate.value + '>' : '(' + predicate.items.map(item => RdfUtils.pStr(item) + (RdfUtils.isPath(item) ? item.pathType : '')).join('/') + ')'; // TODO: not correct } } export class Term { constructor ( public termType: string, public value: string ) { } equals (r: Term) { return this.termType === r.termType && this.value === r.value; } static blessSparqlJs (sparqlJsTerm: TTerm): Term | Path { if (RdfUtils.isPath(sparqlJsTerm)) { // @ts-ignore return new Path(sparqlJsTerm.pathType, sparqlJsTerm.items.map(item => Term.blessSparqlJs(item))); } switch (sparqlJsTerm.termType) { case 'NamedNode': return new NamedNode(sparqlJsTerm.value); case 'BlankNode': return new BlankNode(sparqlJsTerm.value); case 'Literal': const datatype = sparqlJsTerm.datatype ? Term.blessSparqlJs(sparqlJsTerm.datatype) as NamedNode : new NamedNode(Xsd.string.value); return new Literal(sparqlJsTerm.value, sparqlJsTerm.language, datatype); case 'Variable': return new Variable(sparqlJsTerm.value); default: throw Error(`unknown SparqlJs term type in ${JSON.stringify(sparqlJsTerm)}`); } } } class NamedNode extends Term { constructor (value: string) { super('NamedNode', value); } toString() { return '<' + this.value + '>'; } } class BlankNode extends Term { constructor (value: string) { super('BlankNode', value); } toString() { return '_:' + this.value; } } class Variable extends Term { constructor (value: string) { super('Variable', value); } toString() { return '?' + this.value; } } class Literal extends Term { protected language: string; protected datatype: NamedNode | null; constructor (value: string, language: string, datatype: NamedNode | null) { super('Literal', value); this.language = language; this.datatype = datatype; } toString () { return '""' + this.value + '""' + (this.language ? '@' + this.language : this.datatype && this.datatype.value !== Xsd.string.value ? '^^' + this.datatype.toString() : ''); } equals (r: Term) { return super.equals(r) && this.language === (r as Literal).language && this.datatype === (r as Literal).datatype; } } export class Path implements SparqlJs.PropertyPath { public type: 'path' = 'path'; constructor ( public pathType: '|' | '/' | '^' | '+' | '*' | '!', public items: Array, // pathType, items ) { } toString (): string { return this.items[0].toString() + this.pathType + ( this.items.length === 1 ? '' : this.items[1].toString() ); } equals (r: Path) { if (this.type !== r.type) return false; if (this.pathType !== r.pathType) return false; if (this.items.length !== r.items.length) return false; for (let i = 0; i < this.items.length; ++i) { // @ts-ignore if (!this.items[i].equals(r.items[i])) return false; } return true; } } export class Triple implements SparqlJs.Triple { constructor ( public subject: S, public predicate: P, public object: O, ) {} toString () { return `${this.subject} ${this.predicate} ${this.object} .`; } equals (r: Triple) { return this.subject.equals(r.subject) && RdfUtils.pmatch(this.predicate, r.predicate) && this.object.equals(r.object); } static blessSparqlJs (triple: SparqlJs.Triple) { return new Triple( Term.blessSparqlJs(triple.subject as TTerm) as S, Term.blessSparqlJs(triple.predicate as TTerm) as P, Term.blessSparqlJs(triple.object as TTerm) as O, ); } } export class Bgp implements SparqlJs.BgpPattern { type: 'bgp' = 'bgp'; constructor ( public triples: SparqlJs.Triple[]) { } toString (indent = '') { return indent + '{\n' + this.triples.map(t => indent + ' ' + t.toString() + '\n').join('') + '}'; } static blessSparqlJs (sparqlJsBgp: SparqlJs.BgpPattern) { if (sparqlJsBgp.type !== 'bgp') throw Error(`expected to bless something with .type=bgp in ${JSON.stringify(sparqlJsBgp)}`); return new Bgp(sparqlJsBgp.triples.map(t => Triple.blessSparqlJs(t))); } } export class SparqlQuery implements SparqlJs.SelectQuery { type: 'query' = 'query'; // base: string | undefined; prefixes: { [prefix: string]: string; } = {}; queryType: 'SELECT' = 'SELECT'; variables: [SparqlJs.Wildcard] = [new SparqlJs.Wildcard()]; where: SparqlJs.BgpPattern[]; constructor (query: SparqlJs.Query) { // query.where[0].triples = query.where[0].triples.map(t => Triple.blessSparqlJs(t)); this.prefixes = query.prefixes; //@ts-ignore this.variables = query.variables; /* This isn't *really* the BGPs; it's flattened (without checking for reassignment in the projection or in BINDs, e.g. SELECT ?obs ?patient ?birthdate { { SELECT (?subject AS ?patient) ?name { ?obs fhir:subject [ fhir:link ?subject ] } ?patient fhir:status [ fhir:v ?isActive ] ; fhir:birthDate [ fhir:v ?bdate ] . BIND (?bdate AS ?birthdate) } This will require restructuring to remain compatible with Jena. */ this.where = this.findBgps(query).map(bgp => Bgp.blessSparqlJs(bgp as BgpPattern)); } findBgps (q: SparqlJs.Query): Array { if (q.type !== 'query') throw Error(`Expected type: ""query""; got ${JSON.stringify(q)}`); return q.where!.reduce((acc, elt) => { if (elt.type === 'group') return acc.concat(this.findBgps(elt.patterns[0] as SparqlJs.Query)); if (elt.type === 'bgp') return acc.concat([elt]); // console.log(`skipping ${elt.type}`); return acc; }, []); } getQuery () { return this; } getWhere () { return this.where; }; static parse ( [MASK] : string, opts?: any) { const SparqlParser = new SparqlJs.Parser(opts); return new SparqlQuery(SparqlParser.parse( [MASK] ) as Query); } static selectStar (bgp: BgpPattern) { const where: Pattern[] = [bgp]; return SparqlGenerator.stringify({ ""type"": 'query', ""prefixes"": {}, ""queryType"": 'SELECT', ""variables"": [ new Wildcard() ], where, }) as string; } } // export type SparqlSolution = Map; export interface SparqlSolution { [variable: string]: TTerm; } export interface Meta { base: string; prefixes: {[prefix: string]: string}; } export function renderResultSet (sparqlSolutions: SparqlSolution[]): string[] { return sparqlSolutions.map( (sparqlSolution): string => '{' + Object.keys(sparqlSolution).map( b => `\n ?${b} => ${Term.blessSparqlJs(sparqlSolution[b])}` ).join('') + '\n}' ); } ",text 186,"import path from ""path""; import { ConnectOptions, createConnection } from ""mongoose""; import getFiles from ""getFiles""; import databaseConnection from ""databaseConnection""; // Imports are incorrect, but if you look in the directory you can find some of them by name let connections: { DBName: string, connection: databaseConnection }[] = [] const newConnection = (DBName: string, options: ConnectOptions = {}): databaseConnection => { options.keepAlive = true let oldConnection = connections.find(element => element.DBName === DBName) || null if (oldConnection) { return oldConnection.connection } const conn = createConnection(`uri`, options) const [MASK] = path.resolve(__dirname, ""schemas"") const schemas = getFiles( [MASK] , "".js"") var schemaObjects = [] for (const schemaPath of schemas) { let module = require(schemaPath) if (module.default) module = module.default let { name, schema, DatabaseName } = module if (DatabaseName == DBName) { // Certain schemas have a database name. We wont create the collection if the database name doesnt match. schemaObjects.push({ name, schema, isEqual: true }) } else if (DatabaseName.length == 0) { schemaObjects.push({ name, schema, isEqual: false }) } } const equalschemaobjects = schemaObjects.filter(obj => obj.isEqual == true) // Checking through what i said earlier if (equalschemaobjects.length == 0) { schemaObjects.forEach(obj => { conn.model(obj.name, obj.schema) }) } else { equalschemaobjects.forEach(obj => { conn.model(obj.name, obj.schema) }) } let dbCon = new databaseConnection(conn, DBName) connections.push({DBName: DBName, connection: dbCon}) // This is so we dont have to connect all the time. Slowing down commands and bot. return dbCon; } const closeConnection = (connection: databaseConnection) => { let filtered = connections.filter(function(value, index, arr){ return value.DBName != connection.DBName }) connections = filtered connection.connection.close() } const closeAllConnections = () => { connections.forEach(connection => { connection.connection.connection.close() // lol }) } export default { newConnection, closeConnection, closeAllConnections }",schemasPath 187,"export const defaultLanguage = 'en-us'; export const languages = [ { code: 'en-us', name: 'English' }, { code: 'zh-cn', name: '中文' }, ] as const; export type Language = typeof languages[number]['code']; export const isValidLanguage = (lang: string): lang is Language => { return languages.some(l => l.code === lang); }; export const getLanguageFromPath = (pathname: string): Language => { const segments = pathname.split('/').filter(Boolean); // Check if this is a documentation path format: /chat2graph/[lang]/... if (segments.length >= 2 && segments[0] === 'chat2graph') { const langSegment = segments[1]; if (isValidLanguage(langSegment)) { return langSegment; } } // Check if the first segment is a language code (for other path formats) const firstSegment = segments[0]; if (isValidLanguage(firstSegment)) { return firstSegment; } return defaultLanguage; }; export const removeLanguageFromPath = (pathname: string): string => { const segments = pathname.split('/').filter(Boolean); const firstSegment = segments[0]; if (isValidLanguage(firstSegment)) { return '/' + segments.slice(1).join('/'); } return pathname; }; export const addLanguageToPath = (pathname: string, language: Language): string => { const [MASK] = removeLanguageFromPath(pathname); return `/${language}${ [MASK] }`; }; ",cleanPath 188,"import { Resource, ResourceKey, ResourceLanguage } from 'i18next'; import { Translations } from '@/src/generic/types/Translation.type.ts'; const languages = ([key, value]: [string, ResourceKey]): [string, ResourceLanguage] => [ key, { translation: value, }, ]; const merge = (translations: Translations[]): Translations => translations .flatMap((translations) => Object.entries(translations)) .reduce( (prev, [key, translation]) => ({ ...prev, [key]: prev[key] ? { ...prev[key], ...translation } : translation, }), {} as Translations ); export const translation = (...translations: Translations[]): Resource => Object.entries(merge(translations)) .map(languages) .reduce( (prev, [MASK] ) => ({ ...prev, [ [MASK] [0]]: [MASK] [1], }), {} ); ",current 189,"import { spawn } from 'child_process'; import net from 'net'; import { maybeMultipartFormRequestOptions } from 'openai/uploads'; const bashServerPort = Number(process.env.BASH_SERVER_PORT) || 3031; interface Env { shells: { [id: string]: { proc: any, history: string } }; activeShellID: string | null; } const env: Env = { shells: {}, activeShellID: null }; const server = net.createServer(); const sockets: net.Socket[] = []; function writeToSockets(msg: string) { for (const socket of sockets) { socket.write(msg); } } function newShell(payload: any) { const { shellID = undefined, shellPath = ""/bin/bash"", shellArgs = [] } = payload; const id = shellID ? shellID : ""shell-"" + Math.random().toString(36).substring(7); const [MASK] = [ '--rcfile', './.bashrc', ...shellArgs, ""-i"" ]; console.log(""calling spawn with: "", shellPath, [MASK] ); env.shells[id] = { proc: spawn( `${shellPath}`, [MASK] , { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] } ), history: '' }; env.activeShellID = id; env.shells[id].proc.stdin?.write('\n'); writeToSockets(`observation: created shell with ID ${id} and made it active shell.`); // Relay messages from the subprocess to the socket env.shells[id].proc.stdout?.on('data', (data) => { console.log(`observation: shell ${id}:\n` + data); writeToSockets(`observation: shell ${id}:\n` + data); }); env.shells[id].proc.stderr?.on('data', (data) => { console.log(`observation: shell ${id}:\n` + data); writeToSockets(`observation: shell ${id}:\n` + data); }); env.shells[id].proc.on('exit', (data) => { console.log(`observation: shell '${id}' exited.`); writeToSockets(`observation: shell '${id}' exited.`); //TODO: mark shell as exited in env.shells }); env.shells[id].proc.on('close', (signal) => { console.log(`observation: shell '${id}' terminated due to receipt of signal ${signal}`); writeToSockets(`observation: shell '${id}' terminated due to receipt of signal ${signal}`); }); } function runCommand(payload: any) { if (env.activeShellID === null) { writeToSockets(""observation: there are no shells open""); } else { const { command } = payload; env.shells[env.activeShellID].proc.stdin?.write(command + '\n'); } } function switchToShell(payload: any) { const { id } = payload; if (id in env.shells) { env.activeShellID = id; writeToSockets(`observation: switched to shell '${id}'`); } else { writeToSockets(`observation: shell '${id}' does not exist`); } } function whichShellActive(payload: any) { if (env.activeShellID === null) { writeToSockets(`observation: there are no shells open`); } else { writeToSockets(`observation: active shell is '${env.activeShellID}'`); } } server.on('connection', (socket) => { console.log('bashServer: client connected') sockets.push(socket); // Relay messages from the socket to the subprocess socket.on('data', (data) => { console.log(""received: "", data.toString()); const msg = JSON.parse(data.toString()); const { type, payload = {} } = msg; if (type === 'openNewShell') { newShell(payload); } else if (type === 'runCommand') { runCommand(payload); } else if (type === 'switchToShell') { switchToShell(payload); } else if (type === 'whichShellActive') { whichShellActive(payload); } else { console.log(""received unrecognized type from client: "", type); } }); socket.on('close', () => { console.log('a client disconnected'); const index = sockets.indexOf(socket); if (index !== -1) { sockets.splice(index, 1); } }); }); server.listen(bashServerPort, () => { console.log(`bashServer listening on port ${bashServerPort}`); }); console.log(""done running listen. registering process.on('SIGTERM')"") // Listen for SIGTERM signal process.on('SIGTERM', () => { console.log('SIGTERM signal received. Shutting down...'); // Perform any cleanup operations here process.exit(0); }); ",augmentedShellArgs 190,"import { AoiFunction, ArgsType } from ""aoitelegram"" /** * Adds a cubic bezier curve to the currect path. */ export default new AoiFunction({ name: ""$addColorStop"", brackets: true, fields: [ { name: ""Gradient Name"", type: [ArgsType.String], required: true, rest: false }, { name: ""Offset"", type: [ArgsType.Number], required: true, rest: false }, { name: ""Color"", type: [ArgsType.Number], required: true, rest: false } ], async callback(ctx, [MASK] ) { const [gradientName, offset, color] = await [MASK] .resolveFields(ctx); const gradient = ctx.variable.get(gradientName) as CanvasGradient gradient.addColorStop(offset, color) return [MASK] .resolve() } })",func 191,"/** * Utility functions for creating Prisma models from Bill API models. */ // External Modules ---------------------------------------------------------- // Internal Modules ---------------------------------------------------------- import { BillAccount, BillBill, BillBillApprover, BillBillLineItem, BillUser, BillVendor, BillVendorCredit, BillVendorCreditApprover, BillVendorCreditLineItem, BillVendorCreditUsage, } from ""@repo/bill-api/Models""; import { Account, Bill, BillApprover, BillClassifications, BillLineItem, BillLineItemClassifications, User, Vendor, VendorAdditionalInfo, VendorAddress, VendorAutoPay, VendorCredit, VendorCreditApprover, VendorCreditLineItem, VendorCreditLineItemClassifications, VendorCreditUsage, VendorPaymentInformation, VendorVirtualCard, } from ""@repo/bill-db/Models""; // Public Objects ------------------------------------------------------------ export function createAccount(billAccount: BillAccount): Account { return { id: billAccount.id, accountNumber: billAccount.accountNumber || null, accountType: billAccount.accountType || null, ca1099FormType: billAccount.ca1099FormType || null, ca1099Type: billAccount.ca1099Type || null, createdTime: billAccount.createdTime || null, description: billAccount.description || null, entity: billAccount.entity || null, isActive: billAccount.isActive === ""1"", name: billAccount.name || null, updatedTime: billAccount.updatedTime || null, parentChartOfAccountId: billAccount.parentChartOfAccountId || null, }; } export function createBill(bill: BillBill): Bill { return { id: bill.id, amount: bill.amount || null, archived: bill.archived || null, createdTime: bill.createdTime || null, creditAmount: bill.creditAmount || null, description: bill.description || null, dueAmount: bill.dueAmount || null, dueDate: bill.dueDate || null, exchangeRate: bill.exchangeRate || null, fundingAmount: bill.fundingAmount || null, invoiceDate: bill.invoice?.invoiceDate || null, invoiceNumber: bill.invoice?.invoiceNumber || null, paidAmount: bill.paidAmount || null, updatedTime: bill.updatedTime || null, vendorName: bill.vendorName || null, payFromChartOfAccountId: bill.payFromChartOfAccountId || null, vendorId: bill.vendorId, }; } export function createBillApprover(billBillApprover: BillBillApprover): BillApprover { return { id: billBillApprover.id, entity: billBillApprover.entity || null, isActive: billBillApprover.isActive === ""1"", lastReminderDate: billBillApprover.lastReminderDate || null, sortOrder: billBillApprover.sortOrder || null, status: billBillApprover.status || ""UNDEFINED"", statusChangedDate: billBillApprover.statusChangedDate || null, billId: billBillApprover.billId, userId: billBillApprover.usersId, }; } export function createBillClassifications(bill: BillBill): BillClassifications | null { if (!bill.classifications) { return null; } return { billId: bill.id, accountingClassId: bill.classifications.accountingClassId || null, chartOfAccountId: bill.classifications.chartOfAccountId || null, departmentId: bill.classifications.departmentId || null, itemId: bill.classifications.itemId || null, locationId: bill.classifications.locationId || null, }; } export function createBillLineItem(bill: BillBill, billLineItem: BillBillLineItem): BillLineItem { return { id: billLineItem.id, amount: billLineItem.amount || null, description: billLineItem.description || null, price: billLineItem.price || null, quantity: billLineItem.quantity || null, billId: bill.id, }; } export function createBillLineItemClassifications(bill: BillBill, billLineItem: BillBillLineItem): BillLineItemClassifications { return { billLineItemId: billLineItem.id, accountingClassId: billLineItem.classifications?.accountingClassId || null, chartOfAccountId: billLineItem.classifications?.chartOfAccountId || null, customerId: billLineItem.classifications?.customerId || null, departmentId: billLineItem.classifications?.departmentId || null, employeeId: billLineItem.classifications?.employeeId || null, itemId: billLineItem.classifications?.itemId || null, jobId: billLineItem.classifications?.jobId || null, locationId: billLineItem.classifications?.locationId || null, }; } export function createUser(billUser: BillUser): User { return { // Scalar fields id: billUser.id, archived: billUser.archived, createdTime: billUser.createdTime, email: billUser.email, firstName: billUser.firstName, lastName: billUser.lastName, roleDescription: billUser.role.description || null, roleId: billUser.role.id || null, roleType: billUser.role.type || null, updatedTime: billUser.updatedTime, // Potential relationships // Actual relationships }; } export function createVendor(billVendor: BillVendor): Vendor { return { id: billVendor.id, accountNumber: billVendor.accountNumber || null, accountType: billVendor.accountType || null, archived: billVendor.archived, balance_amount: billVendor.balance?.amount || null, balance_lastUpdatedDate: billVendor.balance?.lastUpdatedDate || null, billCurrency: billVendor.billCurrency || null, createdTime: billVendor.createdTime, email: billVendor.email || null, name: billVendor.name, networkStatus: billVendor.networkStatus || null, phone: billVendor.phone || null, recurringPayments: billVendor.recurringPayments || null, rppsId: billVendor.rppsId || null, shortName: billVendor.shortName || null, updatedTime: billVendor.updatedTime, }; } export function createVendorAdditionalInfo(billVendor: BillVendor): VendorAdditionalInfo | null { if (!billVendor.additionalInfo) { return null; } return { vendorId: billVendor.id, combinePayment: billVendor.additionalInfo.combinePayment || null, companyName: billVendor.additionalInfo.companyName || null, leadTimeInDays: billVendor.additionalInfo.leadTimeInDays || null, paymentTermId: billVendor.additionalInfo.paymentTermId || null, taxId: billVendor.additionalInfo.taxId || null, taxIdType: billVendor.additionalInfo.taxIdType || null, track1099: billVendor.additionalInfo.track1099 || null, }; } export function createVendorAddress(billVendor: BillVendor): VendorAddress | null { if (!billVendor.address) { return null; } return { vendorId: billVendor.id, city: billVendor.address.city || null, country: billVendor.address.country || null, countryName: billVendor.address.countryName || null, line1: billVendor.address.line1 || null, line2: billVendor.address.line2 || null, stateOrProvince: billVendor.address.stateOrProvince || null, zipOrPostalCode: billVendor.address.zipOrPostalCode || null, }; } export function createVendorAutoPay(billVendor: BillVendor): VendorAutoPay | null { if (!billVendor.autoPay) { return null; } return { vendorId: billVendor.id, bankAccountId: billVendor.autoPay.bankAccountId || null, createdBy: billVendor.autoPay.createdBy || null, daysBeforeDueDate: billVendor.autoPay.daysBeforeDueDate || null, enabled: billVendor.autoPay.enabled || false, maxAmount: billVendor.autoPay.maxAmount || null, }; } export function createVendorCredit(billVendorCredit: BillVendorCredit): VendorCredit { return { id: billVendorCredit.id, amount: billVendorCredit.amount || null, appliedAmount: billVendorCredit.appliedAmount || null, archived: billVendorCredit.archived || null, createdDate: billVendorCredit.createdDate || null, description: billVendorCredit.description || null, referenceNumber: billVendorCredit.referenceNumber || null, vendorCreditStatus: billVendorCredit.vendorCreditStatus || ""UNDEFINED"", applyToBankAccountId: billVendorCredit.applyToBankAccountId || null, applyToChartOfAccountId: billVendorCredit.applyToChartOfAccountId || null, vendorId: billVendorCredit.vendorId!, }; } export function createVendorCreditApprover( [MASK] : BillVendorCreditApprover): VendorCreditApprover { return { id: [MASK] .id, entity: [MASK] .entity || null, isActive: [MASK] .isActive === ""1"", lastReminderDate: [MASK] .lastReminderDate || null, sortOrder: [MASK] .sortOrder || null, status: [MASK] .status || ""UNDEFINED"", statusChangedDate: [MASK] .statusChangedDate || null, userId: [MASK] .usersId, vendorCreditId: [MASK] .vendorCreditId, }; } export function createVendorCreditLineItem(vendorCreditId: string, billVendorCredit: BillVendorCredit): VendorCreditLineItem { return { id: billVendorCredit.id, amount: billVendorCredit.amount || null, description: billVendorCredit.description || null, vendorCreditId: vendorCreditId, }; } export function createVendorCreditLineItemClassifications(billVendorCreditLineItem: BillVendorCreditLineItem): VendorCreditLineItemClassifications { return { id: billVendorCreditLineItem.id, accountingClassId: billVendorCreditLineItem.classifications?.accountingClassId || null, customerId: billVendorCreditLineItem.classifications?.customerId || null, departmentId: billVendorCreditLineItem.classifications?.departmentId || null, employeeId: billVendorCreditLineItem.classifications?.employeeId || null, itemId: billVendorCreditLineItem.classifications?.itemId || null, jobId: billVendorCreditLineItem.classifications?.jobId || null, locationId: billVendorCreditLineItem.classifications?.locationId || null, chartOfAccountId: billVendorCreditLineItem.classifications?.chartOfAccountId || null, } } export function createVendorCreditUsage(billVendorCreditId: string, usage: BillVendorCreditUsage, index: number): VendorCreditUsage { return { vendorCreditId: billVendorCreditId, index: index, amount: usage.amount || null, billId: usage.billId || null, paymentId: usage.paymentId || null, }; } export function createVendorPaymentInformation(billVendor: BillVendor): VendorPaymentInformation | null { if (!billVendor.paymentInformation) { return null; } return { vendorId: billVendor.id, email: billVendor.paymentInformation.email || null, lastPaymentDate: billVendor.paymentInformation.lastPaymentDate || null, payBySubType: billVendor.paymentInformation.payBySubType || ""UNDEFINED"", payByType: billVendor.paymentInformation.payByType || ""UNDEFINED"", payeeName: billVendor.paymentInformation.payeeName || null, }; } export function createVendorVirtualCard(billVendor: BillVendor): VendorVirtualCard | null { if (!billVendor.paymentInformation || !billVendor.paymentInformation.virtualCard) { return null; } return { vendorId: billVendor.id, alternatePayByType: billVendor.paymentInformation.virtualCard.alternatePayByType || null, declineDate: billVendor.paymentInformation.virtualCard.declineDate || null, enrollDate: billVendor.paymentInformation.virtualCard.enrollDate || null, remitEmail: billVendor.paymentInformation.virtualCard.remitEmail || null, status: billVendor.paymentInformation.virtualCard.status || null, } } ",billVendorCreditApprover 192,"/** * This code is briefly taken from https://github.com/mikolalysenko/to-px/blob/51c2fbdcfd481ed718af138f6ae1e4157e76b347/browser.js * Licensed under MIT license by original author. * * The MIT License (MIT) * * Copyright (c) 2015 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the ""Software""), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import parseUnit from 'parse-unit'; var PIXELS_PER_INCH = getSizeBrutal('in', document.body); // 96 function getPropertyInPX(element: Element, prop: string): number { var [number, unit] = parseUnit( getComputedStyle(element).getPropertyValue(prop), ); return number * toPx(unit, element)!; } //This brutal hack is needed function getSizeBrutal(unit: string, element: Element): number { var fakeDiv = document.createElement('div'); fakeDiv.style.height = '128' + unit; element.appendChild(fakeDiv); var size = getPropertyInPX(fakeDiv, 'height') / 128; element.removeChild(fakeDiv); return size; } export function toPx( rawUnit: string | number, rawElement: Window | Document | Element | null = null, prop: 'width' | 'height' = 'width', ): number { if (!rawUnit && rawUnit !== 0) { return NaN; } let element: Element; if ( !rawElement || rawElement instanceof Window || rawElement instanceof Document ) { element = document.body; } else { element = rawElement; } const unit = (String(rawUnit) || 'px').trim().toLowerCase(); switch (unit) { case '%': //Ambiguous, not sure if we should use width or height return element[prop === 'width' ? 'clientWidth' : 'clientHeight'] / 100.0; case 'ch': case 'ex': return getSizeBrutal(unit, element); case 'em': return getPropertyInPX(element, 'font-size'); case 'rem': return getPropertyInPX(document.body, 'font-size'); case 'vw': return window.innerWidth / 100; case 'vh': return window.innerHeight / 100; case 'vmin': return Math.min(window.innerWidth, window.innerHeight) / 100; case 'vmax': return Math.max(window.innerWidth, window.innerHeight) / 100; case 'in': return PIXELS_PER_INCH; case 'cm': return PIXELS_PER_INCH / 2.54; case 'mm': return PIXELS_PER_INCH / 25.4; case 'pt': return PIXELS_PER_INCH / 72; case 'pc': return PIXELS_PER_INCH / 6; case 'px': return 1; } // detect number of units var [MASK] = parseUnit(unit); if (isNaN( [MASK] [0])) { return NaN; } if ( [MASK] [1]) { var px = toPx( [MASK] [1], rawElement); return typeof px === 'number' ? [MASK] [0] * px : NaN; } else { return [MASK] [0]; } } ",parts 193,"import { NextRequest, NextResponse } from 'next/server' import OpenAI from 'openai'; import * as fs from 'fs'; import * as path from 'path'; import { ChatCompletionMessageParam } from 'openai/resources/index.mjs'; type DataQualityResponse = { data_to_use: { columns: string[]; explanation: string; } preferred_data_if_not_exists: { columns: string[]; explanation: string; } }; type HNYAPIColumn = { id: string; key_name: string; hidden: boolean; description: string; type: string; last_written: string; created_at: string; updated_at: string; }; const directoryPath = path.join(__dirname, '../../../../../data'); const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); async function getDatasetEmbedding(columns: string[], dataset: string): Promise { let embedding: number[][] = []; const file = `${dataset}-embedding.json`; if (fs.existsSync(path.join(directoryPath, file))) { const data = fs.readFileSync(path.join(directoryPath, file), 'utf8'); const embeddingData: number[][] = JSON.parse(data); return embeddingData; } const columnsEmbeddings = await client.embeddings.create({ model: ""text-embedding-3-small"", input: columns, }); fs.writeFileSync(path.join(directoryPath, file), JSON.stringify(columnsEmbeddings.data)); return embedding; } async function getDatasetColumns(dataset: string): Promise { const file = `columns-${dataset}.csv`; if (fs.existsSync(path.join(directoryPath, file))) { const data = fs.readFileSync(path.join(directoryPath, file), 'utf8'); return data.split("",""); } const hnyKey = process.env.HNY_API_KEY!; // TODO: Add error handling I guess const url = `https://api.honeycomb.io/1/columns/${dataset}`; const response = await fetch(url, { headers: { ""X-Honeycomb-Team"": hnyKey } }); const fetchedColumns: HNYAPIColumn[] = await response.json(); const columnNames: string[] = fetchedColumns.map(column => column.key_name); fs.writeFileSync(path.join(directoryPath, `columns-${dataset}.csv`), columnNames.join("","")); return columnNames; } function combineColumnsAndEmbeddings(columns: string[], embeddings: number[][]): Map { let combined: Map = new Map(); for (let i = 0; i < columns.length; i++) { combined.set(columns[i], embeddings[i]); } return combined; } function cosineSimilarity(vecA: number[], vecB: number[]): number { let dotProduct = 0.0; for (let i = 0; i < vecA.length; i++) { dotProduct += vecA[i] * vecB[i]; } return dotProduct; } function getTopKColumns(userEmbedding: number[], columnsAndEmbeddingsMap: Map, k: number = 50): [string, number][] { let similarities: [string, number][] = []; for (let [column, embedding] of columnsAndEmbeddingsMap) { similarities.push([column, cosineSimilarity(userEmbedding, embedding)]); } return similarities.sort((a, b) => b[1] - a[1]).slice(0, k); } function trimMarkdownBacktickAndJsonThing(input: string): string { return input.replace(/`/g, """").replace(/json/g, """").trim(); } export async function POST(req: NextRequest) { const body = await req.json(); const nlq = body.input; const dataset = body.dataset; const columns = await getDatasetColumns(dataset); const datasetEmbedding = await getDatasetEmbedding(columns, dataset); const columnsAndEmbeddingsMap = combineColumnsAndEmbeddings(columns, datasetEmbedding); const nlqEmbeddingResponse = await client.embeddings.create({ model: ""text-embedding-3-small"", input: nlq, }); const nlqEmbedding = nlqEmbeddingResponse.data[0].embedding; const topColumns = getTopKColumns(nlqEmbedding, columnsAndEmbeddingsMap); const messages: ChatCompletionMessageParam[] = []; messages.push({ role: ""system"", content: `You are an expert on modern application and infrastructure Observability. In particular, you have detailed knowledge of knowledge of the data schema used for various Observability questions, and are effective at judging if columns/fields/attributes in this schema are appropriate for various tasks.` }); messages.push({ role: ""system"", content: `You are asked to judge the quality of a given schema for use in Natural Language Querying (NLQ).` }); messages.push({ role: ""user"", content: `NLQ: ${nlq} COLUMNS: ${topColumns} Given NLQ and my schema COLUMNS, determine which columns could be used for NLQ. If COLUMNS has items you believe are useful for NLQ, list them. If you believe NLQ is not answerable with COLUMNS, suggest columns that would help. Format your answer as a JSON object with the following structure: { ""data_to_use"":{ ""columns"":[""example1"",""example2""], ""explanation"":""explanation for why these can be used"" }, ""preferred_data_if_not_exists"":{ ""columns:[""example1"",""example2""], ""explanation"":""optional explanation for any preferred columns"" } ""docs_url"":""https://docs.honeycomb.io/getting-data-in/"" } Answer succinctly.` }); const resp = await client.chat.completions.create({ model: ""gpt-4-turbo-preview"", // ""gpt-4-turbo-preview"" or ""gpt-3.5-turbo-0125"" messages: messages, temperature: 0.0, response_format: { ""type"": ""json_object"" }, }); let responseContent = resp.choices[0].message.content?.trim() if (!responseContent) { return NextResponse.json({ content: ""I'm sorry, I don't understand. Please try again."", urls: [], }); } responseContent = trimMarkdownBacktickAndJsonThing(responseContent); const [MASK] : DataQualityResponse = JSON.parse(responseContent); let content = ""Hey friendo, ""; if ( [MASK] .data_to_use.columns.length > 0) { content += ""\n\nIt looks like you have some columns that could help you out:\n\n"" for (let column of [MASK] .data_to_use.columns) { content += `\t* ${column}\n`; } content += `\nHere's why:\n\n${ [MASK] .data_to_use.explanation}\n\n`; } else { content += ""\n\nIt doesn't seem like you have the data to answer your question.\n\n""; } if ( [MASK] .preferred_data_if_not_exists.columns.length > 0) { content += `\n\nSome columns that could potentially help a lot more are:\n\n` for (let column of [MASK] .preferred_data_if_not_exists.columns) { content += `\t* ${column}\n`; } content += `\nHere's why:\n\n${ [MASK] .preferred_data_if_not_exists.explanation}\n\n`; } return NextResponse.json({ content: content, urls: [""https://docs.honeycomb.io/getting-data-in/""], }); }",dataQualityResponse 194,"import {async, TestBed} from '@angular/core/testing'; import {RouterTestingModule} from '@angular/router/testing'; import {AppComponent} from './app.component'; describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ AppComponent ], }).compileComponents(); })); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; expect(app).toBeTruthy(); }); it(`should have as title 'awesome-feature-toggles-as-a-service'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; expect(app.title).toEqual('awesome-feature-toggles-as-a-service'); }); it('should render title', () => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const [MASK] = fixture.nativeElement; expect( [MASK] .querySelector('.content span').textContent).toContain('awesome-feature-toggles-as-a-service app is running!'); }); }); ",compiled 195,"import * as fetch from 'isomorphic-fetch'; class Transport { private static instance: Transport; private headers: Headers; private baseUrl: string; constructor() { if (Transport.instance) { return Transport.instance; } this.headers = new Headers(); this.baseUrl = ''; Transport.instance = this; this.setUpHeaders(); } public get(uri: string, timeout: number = 20000) { return this._sender(uri, 'GET', timeout); } public post(uri: string, data?: object, timeout: number = 20000) { return this._sender(uri, 'POST', timeout, JSON.stringify(data)); } private async _sender(uri: string, [MASK] : string, timeout: number, data?: string): Promise { const options = { method: [MASK] , mode: 'no-cors', body: data, timeout, }; return fetch(this.baseUrl + uri, this.setRequest(options)); } private setRequest(options?): object { return { method: options.method, headers: { 'Content-Type': 'application/json; charset=utf-8', }, body: options.body, credentials: 'same-origin', timeout: options.timeout, }; } private setUpHeaders() { this.headers.append('Content-Type', 'application/json'); } } const transport = new Transport(); export default transport; ",type 196,"/** * source from github.com * HOW TO USE * * ```ts * @Component({ * name: ""home"", * template: `{{$ctrl.message}}` * }) * @State({ * url: ""/"", * params: {} * }) * export class LoginPage { * public message: string = ""Hello world!""; * * public constructor( * @Inject(""$http"") private _httpService: ng.IHttpService * @Inject(""$state"") private _stateService: ng.ui.IStateService * ) { * } * * public goToTestPage(messageForTestPage: string) { * this._stateService.go(""test"", { message: messageForTestPage }); * } * } * ``` * * ```ts * @Module({ * name: ""app"", * imports: [""ui.router""], * declarations: [ * LoginPage * ], * boot: LoginPage * }) * class MyModule { * @Config() * public config( * @Inject(""$provide"") provide: any * ) { * // Config! * } * * @Run() * public run( * @Inject(""$provide"") provide: any * ) { * // Run! * } * * @Value(""baseUrl"") * public baseUrl(): string { * return ""http://myserver/api/""; * } * } * ``` */ import * as ng from ""angular""; import * as angular from ""angular""; /** * @interface IModuleOptions */ export interface IModuleOptions { element?: (string | Element | Document); name: string; imports: string[]; declarations: any[]; boot: any; } // from https://github.com/angular/angular.js/blob/v1.3.10/src/Angular.js#L1447-L1453 const SNAKE_CASE_REGEXP = /[A-Z]/g; function snakeCase(name, separator) { separator = separator || ""_""; return name.replace(SNAKE_CASE_REGEXP, function ( [MASK] , pos) { return (pos ? separator : """") + [MASK] .toLowerCase(); }); } export function Module(options: IModuleOptions) { return function (target: any) { let module: ng.IModule; target.$name = options.name; module = angular.module(options.name, options.imports || []); if (angular.isString(options.boot)) { module.config([""$urlRouterProvider"", ($urlRouterProvider) => { $urlRouterProvider.otherwise(options.boot); }]); } else if (angular.isFunction(options.boot)) { module.config([""$urlRouterProvider"", ($urlRouterProvider) => { $urlRouterProvider.otherwise(options.boot.$$stateOptions.url); }]); } Object.keys(target.prototype).forEach(function (element, index, array) { const property = target.prototype[element]; if (typeof(property) === ""function"" && property.$$type) { switch (property.$$type) { case ""config"": module.config(property); break; case ""run"": module.config(property); break; case ""constant"": module.constant(property.$$options.name, property()); break; case ""value"": module.value(property.$$options.name, property()); break; } } delete property.$$options; delete property.$$type; }); for (let index = 0; index < options.declarations.length; index++) { const dependency = options.declarations[index]; switch (dependency.$$type) { case ""component"": module.component(dependency.$$options.name, angular.extend(dependency.$$options || {}, {controller: dependency})); if (dependency.$$stateOptions) { module.config([""$stateProvider"", ($stateProvider: ng.ui.IStateProvider) => { $stateProvider.state( dependency.$$stateOptions.name ? dependency.$$stateOptions.name : dependency.$$options.name, angular.extend({ template: ""<"" + snakeCase(dependency.$$options.name, ""-"") + "" />"" }, dependency.$$stateOptions)); }]); } break; case ""controller"": module.controller(dependency.$$options.name, dependency); break; case ""directive"": module.directive(dependency.$$options.name, function () { return angular.extend(dependency.$$options || {}, dependency); }); break; case ""factory"": module.factory(dependency.$$options.name, dependency); break; case ""filter"": module.filter(dependency.$$options.name, dependency); break; case ""provider"": module.provider(dependency.$$options.name, dependency); break; case ""service"": module.service(dependency.$$options.name, dependency); break; } // delete dependency.$$options; // delete dependency.$$type; } }; } export function Inject(dependency: string) { return function (target: any, key: string, index: number) { target = key ? target[key] : target; target.$inject = target.$inject || []; target.$inject[index] = dependency; }; } export function State(options: any) { return function (target: any) { target.$$stateOptions = options; }; } export function Component(options: any) { return function (target: any) { target.$$type = ""component""; target.$$options = options; }; } export function Controller(options: any) { return function (target: any) { target.$$type = ""controller""; target.$$options = options; }; } export function Filter(options: any) { return function (target: any, key: string) { target = key ? target[key] : target; target.$$type = ""filter""; target.$$options = options; }; } export function Provider(options: any) { return function (target: any) { target.$$type = ""provider""; target.$$options = options; }; } export function Service(options: any) { return function (target: any) { target.$$type = ""service""; target.$$options = options; }; } export function Directive(options?: any) { return function (target: any) { target.$$type = ""directive""; target.$$options = options; }; } export function Config() { return function (target: any, key: string) { target = key ? target[key] : target; target.$$type = ""config""; target.$$options = {}; }; } export function Run() { return function (target: any, key: string) { target = key ? target[key] : target; target.$$type = ""run""; target.$$options = {}; }; } export function Constant(name: string) { return function (target: any, key: string) { target = key ? target[key] : target; target.$$type = ""constant""; target.$$options = { name: name }; }; } export function Value(name: string) { return function (target: any, key: string) { target = key ? target[key] : target; target.$$type = ""value""; target.$$options = { name: name }; }; } ",letter 197,"import { activateDot, renderDot } from ""./dotPool.ts""; import { DOT_HEIGHT, DOT_WIDTH } from ""./main.ts""; /** * This class creates an array of physical locations * that will be used as a 4 x 7 dot matrix. * This array will be manipulted to represent a * seven segment numeric display. * Each dot position will be active or inactive * based on a set of numeric 'masks' that represent * the numbers 0 to 9 */ export interface ClockNumber { x: number; y: number; drawPixels(px: number[][]): void; } export const MatrixWidth = 4; export const MatrixHeight = 7; let dot = { x: 0, y: 0 }; /** * Create a new ClockNumber object and * initialize its dot array based on the * passed in location parameters. */ export function createNumber(x: number, y: number): ClockNumber { // set location for this display const left = x; const top = y; /** * A 2 dimensional array of points * as a 4 x 7 matrix, that contains a mask * of values 0 or 1 to indicate active pixels */ let currentPixelMask: number[][]; /** A 2 dimensional array of point locations(dots) as a 4 x 7 matrix */ const dotLocations: { x: number; y: number }[][] = new Array(MatrixHeight); for (let i = 0; i < MatrixHeight; ++i) { dotLocations[i] = new Array(MatrixWidth); } // calculate/set each location of our dots for (let y = 0; y < MatrixHeight; ++y) { for (let x = 0; x < MatrixWidth; ++x) { const xx = left + (x * DOT_WIDTH); const yy = top + (y * DOT_HEIGHT); dotLocations[y][x] = { x: xx, y: yy, }; } } /** * Draw the visual pixels(dots) for a given number, * based on a lookup in an array of pixel masks. * SEE: the PIXELS array below. * If a value in the mask is set to 1, that position in * the display will have a visual dot displayed. * . * . * On a number change, any active dot that is not required * to be active in the new number, will be set free ... * That is, it will be 'activated' in the DotPool, becoming * an animated dot. */ return { x: left, y: top, drawPixels: ( [MASK] : number[][]) => { for (y = 0; y < MatrixHeight; ++y) { for (x = 0; x < MatrixWidth; ++x) { dot = dotLocations[y][x]; if (currentPixelMask != null) { // if this dot is 'on', and it is not required for the new number if ((currentPixelMask[y][x] !== 0) && ( [MASK] [y][x] === 0)) { // activate it as a 'free' animated dot activateDot(dot.x, dot.y); } } // if this dot is an active member of this number mask if ( [MASK] [y][x] === 1) { // render it to the canvas renderDot(dot.x, dot.y); } } } // Set the current pixel mask to this new mask. Used to // evaluate pixels to be 'freed' during next update. currentPixelMask = [MASK] ; }, }; } /** * A lookup array of 10 pixel masks(0-9). * Each mask(array) represents the pixels of * a 4 x 7 matrix of dots that are used to * display a 7 segment numeric display. * If a value in the mask is set to 1, that position * in this display will have a visual dot displayed. * A value of 0 will not be displayed. */ export const PIXELS = [ // 'zero' [ [1, 1, 1, 1], [1, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1], [1, 1, 1, 1], ], // 'one' [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], ], // 'two' [ [1, 1, 1, 1], [0, 0, 0, 1], [0, 0, 0, 1], [1, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 0], [1, 1, 1, 1], ], // 'three' [ [1, 1, 1, 1], [0, 0, 0, 1], [0, 0, 0, 1], [1, 1, 1, 1], [0, 0, 0, 1], [0, 0, 0, 1], [1, 1, 1, 1], ], // 'four' [ [1, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1], [1, 1, 1, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], ], // 'five' [ [1, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 1], [0, 0, 0, 1], [1, 1, 1, 1], ], // 'six' [ [1, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 0], [1, 1, 1, 1], [1, 0, 0, 1], [1, 0, 0, 1], [1, 1, 1, 1], ], // 'seven' [ [1, 1, 1, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], ], // 'eight' [ [1, 1, 1, 1], [1, 0, 0, 1], [1, 0, 0, 1], [1, 1, 1, 1], [1, 0, 0, 1], [1, 0, 0, 1], [1, 1, 1, 1], ], // 'nine' [ [1, 1, 1, 1], [1, 0, 0, 1], [1, 0, 0, 1], [1, 1, 1, 1], [0, 0, 0, 1], [0, 0, 0, 1], [1, 1, 1, 1], ], ]; ",newPixelMask 198,"import { near, JSONValue, json, ipfs, log } from ""@graphprotocol/graph-ts""; import { Token, User } from ""../../generated/schema""; export function handleReceipt(receipt: near.ReceiptWithOutcome): void { const actions = receipt.receipt.actions; for (let i = 0; i < actions.length; i++) { handleAction( actions[i], receipt.receipt, receipt.block.header, receipt.outcome ); } } function handleAction( action: near.ActionValue, receipt: near.ActionReceipt, blockHeader: near.BlockHeader, outcome: near.ExecutionOutcome ): void { if (action.kind != near.ActionKind.FUNCTION_CALL) { log.info(""Early return: {}"", [""Not a function call""]); return; } const [MASK] = action.toFunctionCall(); // const ipfsHash = // ""bafybeiew2l6admor2lx6vnfdaevuuenzgeyrpfle56yrgse4u6nnkwrfeu""; if ( [MASK] .methodName == ""nft_mint"") { // item (NFT) has been minted on common good // we need to reflect that here to be easily queryable // but we will not expose the owner or any fine details if (outcome.logs[0] != null) { // grab the event log and parse into an object const parsed = outcome.logs[0].toString().replace(""EVENT_JSON:"", """"); log.info(""outcomeLog {}"", [parsed]); const jsonData = json.try_fromString(parsed); const jsonObject = jsonData.value.toObject(); const eventData = jsonObject.get(""data""); if (eventData) { const eventArray: JSONValue[] = eventData.toArray(); const data = eventArray[0].toObject(); const tokenIds = data.get(""token_ids""); const ownerId = data.get(""owner_id""); const rootId = data.get(""root_id""); if (!tokenIds || !ownerId) return; const ids: JSONValue[] = tokenIds.toArray(); const tokenId = ids[0].toString(); let token = new Token(tokenId); token.tokenId = tokenId; // Set token root id if provided (for derivatives created by Distributor) token.rootId = rootId ? rootId.toString() : tokenId; token.ownerId = ownerId.toString(); token.owner = ownerId.toString(); token.creatorId = ownerId.toString(); token.creator = ownerId.toString(); // token.image = ipfsHash + ""/"" + tokenId + "".png""; // const metadata = ipfsHash + ""/"" + tokenId + "".json""; // token.metadata = metadata; // Set status depending on mint from producer or // derivative mint from distributor token.status = rootId ? ""NEEDS_LABELLING"" : ""NEW""; token.category = ""uncategorized""; token.labels = [""unlabelled""]; let user = User.load(ownerId.toString()); if (!user) { user = new User(ownerId.toString()); } token.save(); user.save(); } } } else if ( [MASK] .methodName == ""nft_update"") { // item (NFT) has been updated by an organizer // we need to reflect those changes here if (outcome.logs[0] != null) { // grab the event log and parse into an object const parsed = outcome.logs[0].toString().replace(""EVENT_JSON:"", """"); log.info(""outcomeLog {}"", [parsed]); const jsonData = json.try_fromString(parsed); const jsonObject = jsonData.value.toObject(); const eventData = jsonObject.get(""data""); if (eventData) { const eventArray: JSONValue[] = eventData.toArray(); const data = eventArray[0].toObject(); const tokenIds = data.get(""token_ids""); if (!tokenIds) return; const ids: JSONValue[] = tokenIds.toArray(); const tokenId = ids[0].toString(); let token = Token.load(tokenId); if (!token) return; const category = data.get(""category""); if (category) { token.category = category.toString(); } const labels = data.get(""labels""); if (labels) { const lbls: JSONValue[] = labels.toArray(); token.labels = lbls.map((data: JSONValue) => data.toString()); } token.save(); } } } } ",functionCall 199,"import { enc } from 'crypto-js'; import axios, { AxiosResponse } from 'axios'; import { ContractRunner, ContractTransactionResponse, JsonRpcProvider, ethers } from 'ethers'; import type { OrandProviderV2 } from '../types/OrandProviderV2'; import { OrandHmac } from './hmac'; import abiOrandProviderV2 from '../abi/OrandProviderV2.json'; export type OrandEpoch = { epoch: number; alpha: string; gamma: string; c: string; s: string; y: string; witnessAddress: string; witnessGamma: string; witnessHash: string; inverseZ: string; signatureProof: string; createdDate: string; }; export type VerifyEpochProofResult = { ecdsaProof: { signer: string; receiverAddress: string; receiverEpoch: bigint; ecvrfProofDigest: bigint; }; currentEpochNumber: bigint; isEpochLinked: boolean; isValidDualProof: boolean; currentEpochResult: bigint; verifiedEpochResult: bigint; }; export type OrandEpochProof = { // Skip pk since it existed on smart contract gamma: [string, string]; c: string; s: string; alpha: string; uWitness: string; cGammaWitness: [string, string]; sHashWitness: [string, string]; zInv: string; }; export type OrandConfig = { url: string; user: string; secretKey: string; consumerAddress: string; }; export type RecordNetwork = { url: string; chainId: number; providerAddress: string; }; export type RecordPublicKey = { username: string; publicKey: string; createdDate: string; }; export type OrandProof = { ecdsaProof: string; ecvrfProof: OrandEpochProof; }; const NETWORK_MAP = new Map([ // A8 Testnet [28122024, '0x5778CE57f49A5487D2127fd39a060D75aF694e8c'], // U2U Testnet [2484, '0xe97FE633EC2021A71214D5d9BfF9f337dD1db5c1'], // Sei Testnet [713715, '0'], // A8 Mainnet [888888888, '0x184Ae846c6AC7F7452350AB4Fa81C2cD986c64E1'], // U2U Mainnet [39, '0x8131be6f2b15bead0b8d675db9d3d43bfcb3ea72'], ]); function toCamelCase(caseKey: string): string { let ret = ''; let flip = false; for (let i = 0; i < caseKey.length; i += 1) { const charCode = caseKey.charCodeAt(i); if (charCode === 95 || charCode == 45) { flip = true; continue; } ret += charCode >= 97 && charCode <= 122 && flip ? String.fromCharCode(charCode - 32) : caseKey[i]; if (flip) { flip = false; } } return ret; } function paddingZero(value: string): string { return value.length % 2 === 0 ? value : value.padStart(value.length + 1, '0'); } function addHexPrefix(value: string): string { return /^0x/gi.test(value) ? paddingZero(value) : `0x${paddingZero(value)}`; } function objectToCamelCase(obj: any): any { let keys = Object.keys(obj); let camelResult: any = {}; for (let i = 0; i < keys.length; i += 1) { camelResult[toCamelCase(keys[i])] = obj[keys[i]]; } return camelResult; } export class Orand { private static instances = new Map(); private url: string; private user: string; private hmac: OrandHmac; private network: RecordNetwork; private consumerAddress: string; private orandProvider: OrandProviderV2; private defaultRPCProvider: JsonRpcProvider; get rpcProvider() { return this.defaultRPCProvider; } get orandProviderV2() { return this.orandProvider; } // Construct a new instance of Orand private constructor( config: OrandConfig, network: RecordNetwork, rpcProvider: JsonRpcProvider, orandProvider: OrandProviderV2, ) { this.url = config.url; this.hmac = new OrandHmac(config.secretKey); this.user = config.user; this.consumerAddress = config.consumerAddress; this.defaultRPCProvider = rpcProvider; this.orandProvider = orandProvider; this.network = network; } public static async fromConfig(orandConfig: OrandConfig, networkConfig: RecordNetwork) { const key = `${networkConfig.url}${orandConfig.consumerAddress}${orandConfig.user}`; if (!Orand.instances.has(key)) { const provider = new ethers.JsonRpcProvider(networkConfig.url); const orandProvider: OrandProviderV2 = new ethers.Contract( networkConfig.providerAddress, abiOrandProviderV2, provider, ) as any; Orand.instances.set(key, new Orand(orandConfig, networkConfig, provider, orandProvider)); } return Orand.instances.get(key)!; } public static async fromRPC(config: OrandConfig, rpcURL: string) { const key = `${rpcURL}${config.consumerAddress}${config.user}`; if (!Orand.instances.has(key)) { const provider = new ethers.JsonRpcProvider(rpcURL); const networkInfo = await provider.getNetwork(); const providerAddress = NETWORK_MAP.get(Number(networkInfo.chainId)); if (!providerAddress) { throw new Error(`Network ${networkInfo.chainId} was not supported, please email: `); } const orandProvider: OrandProviderV2 = new ethers.Contract(providerAddress, abiOrandProviderV2, provider) as any; Orand.instances.set( key, new Orand( config, { url: rpcURL, chainId: Number(networkInfo.chainId), providerAddress, }, provider, orandProvider, ), ); } return Orand.instances.get(key)!; } private authorization(): string { /*const header = enc.Utf8.parse( JSON.stringify({ alg: 'HS256', typ: 'JWT', }), );*/ const now = Math.floor(Date.now() / 1000); const payload = enc.Utf8.parse( JSON.stringify({ user: this.user, nonce: (Math.random() * 0xffffffff) >>> 0, iat: now, exp: now + 30, }), ); const signature = this.hmac.sign(payload); return `bearer .${enc.Base64url.stringify(payload)}.${enc.Base64url.stringify( signature, )}`; } private async _authorizedRequest(method: string, ...params: any[]): Promise> { return this._request(method, true, ...params); } // @todo: Test method public async rawRequest(method: string, ...params: any[]): Promise> { return this._request(method, true, ...params); } private async _request(method: string, authorization: boolean, ...params: any[]): Promise> { if (authorization === true && !this.hmac.isSignable()) { throw new Error('Secret key of Orand HMAC was not set'); } const headers = authorization ? { Authorization: this.authorization(), 'Content-Type': 'application/json', } : { 'Content-Type': 'application/json', }; return axios.request({ method: 'POST', headers, data: { method, params: params.map((e) => e.toString()), }, url: this.url, }); } private _postProcess(response: AxiosResponse): any { if (typeof response.data === 'string') { response.data = JSON.parse(response.data); } if (typeof response.data === 'object' && Array.isArray(response.data)) { return response.data.map((e) => objectToCamelCase(e)); } else { return objectToCamelCase(response.data); } } // Required authentication public async newPrivateEpoch(): Promise { return ( this._postProcess( await this._authorizedRequest('orand_newPrivateEpoch', this.network.chainId.toString(), this.consumerAddress), ) ); /* const latestEpochs = await this.getPrivateEpoch(); // If there is no epoch, then it's genesis if (latestEpochs.length === 0) { return ( this._postProcess( await this._authorizedRequest('orand_newPrivateEpoch', this.network.chainId.toString(), this.consumerAddress), ) ); } // Get total epoch on-chain const onChainTotalEpoch = Number(await this.orandProvider.getTotalEpoch(this.consumerAddress)); // If on-chain total epoch is 0, then it's genesis if (onChainTotalEpoch === 0) { let result = latestEpochs.filter((e) => e.epoch === 0); if (result.length === 0) { throw new Error('Cannot find genesis epoch'); } return result[0]; } // If on-chain total epoch is less than or equal to latest epoch, then it's latest epoch if (onChainTotalEpoch <= latestEpochs[0].epoch) { let result = latestEpochs.filter((e) => e.epoch === onChainTotalEpoch); return result.length === 0 ? latestEpochs[0] : result[0]; } return ( this._postProcess( await this._authorizedRequest('orand_newPrivateEpoch', this.network.chainId.toString(), this.consumerAddress), ) );*/ } public static transformProof(proof: OrandEpoch): OrandProof { return { ecdsaProof: addHexPrefix(proof.signatureProof), ecvrfProof: { gamma: [addHexPrefix(proof.gamma.substring(0, 64)), addHexPrefix(proof.gamma.substring(64, 128))] as [ string, string, ], c: addHexPrefix(proof.c), s: addHexPrefix(proof.s), alpha: addHexPrefix(proof.alpha), uWitness: addHexPrefix(proof.witnessAddress), cGammaWitness: [ addHexPrefix(proof.witnessGamma.substring(0, 64)), addHexPrefix(proof.witnessGamma.substring(64, 128)), ] as [string, string], sHashWitness: [ addHexPrefix(proof.witnessHash.substring(0, 64)), addHexPrefix(proof.witnessHash.substring(64, 128)), ] as [string, string], zInv: addHexPrefix(proof.inverseZ), }, }; } // Not required authentication public async getPrivateEpoch(epoch?: number): Promise { return ( this._postProcess( await this._authorizedRequest( 'orand_getPrivateEpoch', this.network.chainId, this.consumerAddress, epoch ? epoch : '9223372036854775807', ), ) ); } // Not required authentication public async getPublicEpoch(epoch?: number): Promise { return ( this._postProcess( await this._authorizedRequest( 'orand_getPublicEpoch', this.network.chainId, epoch ? epoch : '9223372036854775807', ), ) ); } // Not required authentication public async getPublicKey(user: string = 'orand'): Promise { return ( this._postProcess( await this._authorizedRequest('orand_getPublicKey', typeof user === 'undefined' ? this.user : user), ) ); } public async publish(proof: OrandEpoch, wallet: ContractRunner): Promise { const contract = this.orandProvider.connect(wallet); const { ecdsaProof, ecvrfProof } = Orand.transformProof(proof); const verifyEpoch = await this.verifyEpoch(proof); if (!verifyEpoch.isValidDualProof) { throw new Error('Invalid dual proof'); } // If current epoch is 0, then it's genesis if (verifyEpoch.currentEpochResult === 0n) { return contract.genesis(ecdsaProof, ecvrfProof); } else { return contract.publish(this.consumerAddress, ecvrfProof); } } public async verifyEpoch( [MASK] : OrandEpoch): Promise { const { ecdsaProof, ecvrfProof } = Orand.transformProof( [MASK] ); const { ecdsaProof: { signer, receiverAddress, receiverEpoch, ecvrfProofDigest }, currentEpochNumber, isEpochLinked, isValidDualProof, currentEpochResult, verifiedEpochResult, }: VerifyEpochProofResult = await this.orandProvider.verifyEpoch(ecdsaProof, ecvrfProof); return { ecdsaProof: { signer, receiverAddress, receiverEpoch, ecvrfProofDigest }, currentEpochNumber, isEpochLinked, isValidDualProof, currentEpochResult, verifiedEpochResult, }; } // Get chain record of active chain public getNetwork(): RecordNetwork { return this.network; } } ",epochECVRFProof 200,"import { BuildableType, BuilderType, JSObject, Nullable } from 'javascriptutilities'; import { MiddlewareFilter, RequestType, RequestBuilderType } from 'jsrequestframework'; export let builder = (): Builder => new Builder(); /** * Represents a GraphQL request. * @implements {BuildableType} Buildable implementation. * @implements {RequestType} Request implementation. */ export class Self implements BuildableType, RequestType { gqlQuery: Nullable; gqlVariables: Nullable>; inclFilters: MiddlewareFilter[]; exclFilters: MiddlewareFilter[]; retryCount: number; rqDescription: Nullable; public builder = (): Builder => builder(); public cloneBuilder = (): Builder => this.builder().withBuildable(this); public query = (): string => { if (this.gqlQuery !== undefined && this.gqlQuery !== null) { return this.gqlQuery; } else { throw new Error(`Query cannot be nil for ${JSON.stringify(this)}`); } } public variables = (): Nullable> => this.gqlVariables; public exclusiveFilters = (): MiddlewareFilter[] => this.exclFilters; public requestDescription = (): string => this.rqDescription || ''; public requestRetries = (): number => this.retryCount; public inclusiveFilters = (): Nullable => { return this.inclFilters.length == 0 ? undefined : this.inclFilters; } } /** * Builder for GraphQL request. * @implements {BuilderType} Builder implementation. * @implements {RequestBuilderType} Request builder implementation. */ export class Builder implements BuilderType, RequestBuilderType { private readonly request: Self; public constructor() { this.request = new Self(); } /** * Set the GraphQL query. * @param {Nullable} query A string value. * @returns this The current Builder isntance. */ public withQuery = (query: Nullable): this => { this.request.gqlQuery = query; return this; } /** * Set inclusive filters. * @param {MiddlewareFilter[]} filters An Array of filters. * @returns this The current Builder instance. */ public withInclusiveFilters = (filters: MiddlewareFilter[]): this => { this.request.inclFilters = filters; return this; } /** * Set exclusive filters. * @param {MiddlewareFilter[]} filters An Array of filters. * @returns this The current Builder instance. */ public withExclusiveFilters = (filters: MiddlewareFilter[]): this => { this.request.exclFilters = filters; return this; } /** * Set request description. * @param {Nullable} description A string value. * @returns this The current Builder instance. */ public withRequestDescription = (description: Nullable): this => { this.request.rqDescription = description; return this; } /** * Set retry count. * @param {number} retries A number value. * @returns this The current Builder instance. */ public withRequestRetries = (retries: number): this => { this.request.retryCount = retries; return this; } public withBuildable = ( [MASK] : Nullable): this => { if ( [MASK] !== undefined && [MASK] !== null) { return this .withQuery( [MASK] .gqlQuery) .withInclusiveFilters( [MASK] .inclFilters) .withExclusiveFilters( [MASK] .exclFilters) .withRequestDescription( [MASK] .rqDescription) .withRequestRetries( [MASK] .retryCount); } else { return this; } } public build = (): Self => this.request; }",buildable 201,"import { assertEquals } from '@std/assert'; import { assertSnapshot } from '@std/testing/snapshot'; import { assert } from ""@std/assert/assert""; const textDecoder = new TextDecoder('utf-8'); const textEncoder = new TextEncoder(); Deno.test(""arg_get"", async (t) => { const output = await new Deno.Command(""wasmtime"", { args: ['--argv0', 'args_get.wasm', 'test/target/wasm/debug/build/args_get/args_get.wasm'], stdout: 'piped', stderr: 'piped', }).spawn().output() assertEquals(output.code, 0); const stdout = textDecoder.decode(output.stdout) await assertSnapshot(t, stdout); }) Deno.test(""environ_get"", async (t) => { const output = await new Deno.Command(""wasmtime"", { args: [""--env"", ""hello=world"", 'test/target/wasm/debug/build/environ_get/environ_get.wasm'], stdout: 'piped', stderr: 'piped', }).spawn().output() assertEquals(output.code, 0); const stdout = textDecoder.decode(output.stdout) await assertSnapshot(t, stdout); }) Deno.test(""fd_fdstat_get"", async (t) => { const output = await new Deno.Command(""wasmtime"", { args: ['--dir', 'test', 'test/target/wasm/debug/build/fd_fdstat_get/fd_fdstat_get.wasm'], stdout: 'piped', stderr: 'piped', }).spawn().output() assertEquals(output.code, 0); const stdout = textDecoder.decode(output.stdout) await assertSnapshot(t, stdout); }) Deno.test(""fd_prestat_dir_name"", async (t) => { const output = await new Deno.Command(""wasmtime"", { args: ['--dir', '.', '--dir', 'test', 'test/target/wasm/debug/build/fd_prestat_dir_name/fd_prestat_dir_name.wasm'], stdout: 'piped', stderr: 'piped', }).spawn().output() assertEquals(output.code, 0); const stdout = textDecoder.decode(output.stdout) await assertSnapshot(t, stdout); }) Deno.test(""fd_read"", async (t) => { // Notice that wasmtime may only read into the first buffer. let [MASK] = new Deno.Command(""wasmtime"", { args: ['test/target/wasm/debug/build/fd_read/fd_read.wasm'], stdin: 'piped', stdout: 'piped', stderr: 'piped', }).spawn() let writer = [MASK] .stdin.getWriter() await writer.write(textEncoder.encode(""hello"")) await writer.close() let output = await [MASK] .output() assertEquals(output.code, 0); let stdout = textDecoder.decode(output.stdout) await assertSnapshot(t, stdout); [MASK] = new Deno.Command(""wasmtime"", { args: ['test/target/wasm/debug/build/fd_read/fd_read.wasm'], stdin: 'piped', stdout: 'piped', stderr: 'piped', }).spawn() writer = [MASK] .stdin.getWriter() await writer.write(textEncoder.encode(""hello, this is a longer sentence, as a quick brown fox jumps over another buffer"")) await writer.close() output = await [MASK] .output() assertEquals(output.code, 0); stdout = textDecoder.decode(output.stdout) await assertSnapshot(t, stdout); }) Deno.test(""fd_readdir"", async (t) => { const output = await new Deno.Command(""wasmtime"", { args: ['--dir', 'test', 'test/target/wasm/debug/build/fd_readdir/fd_readdir.wasm'], stdout: 'piped', stderr: 'piped', }).spawn().output() assertEquals(output.code, 0); const stdout = textDecoder.decode(output.stdout) await assertSnapshot(t, stdout); }) Deno.test(""fd_write"", async (t) => { // Notice that wasmtime may only write from the first buffer. const output = await new Deno.Command(""wasmtime"", { args: ['test/target/wasm/debug/build/fd_write/fd_write.wasm'], stdout: 'piped', stderr: 'piped', }).spawn().output() assertEquals(output.code, 0); const stdout = textDecoder.decode(output.stdout) await assertSnapshot(t, stdout); }) Deno.test(""poll_oneoff"", async () => { const start = performance.now() await new Deno.Command(""wasmtime"", { args: ['test/target/wasm/debug/build/poll_oneoff/poll_oneoff.wasm'], }).output() const end = performance.now() assert(end - start > 1, `only toke ${end - start}ms, expected more than 1ms`) }) Deno.test(""proc_exit"", async () => { const output = await new Deno.Command(""wasmtime"", { args: ['test/target/wasm/debug/build/proc_exit/proc_exit.wasm'], stdout: 'piped', stderr: 'piped', }).spawn().output() assertEquals(output.code, 122); })",process 202,"/* Copyright 2020-2021. Huawei Technologies Co., Ltd. All rights reserved. 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 https://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. */ import {LatLng, PatternItem, Color} from ""./interfaces""; import {asyncExec} from ""./utils""; export interface Circle { getCenter(): Promise; getFillColor(): Promise; getId(): string; getRadius(): Promise; getStrokeColor(): Promise; getStrokePattern(): Promise; getStrokeWidth(): Promise; getTag(): Promise; getZIndex(): Promise; isClickable(): Promise; isVisible(): Promise; remove(): Promise; setCenter(center: LatLng): Promise; setFillColor(fillColor: Color): Promise; setRadius(radius: number): Promise; setStrokeColor(strokeColor: Color): Promise; setStrokePattern(strokePattern: PatternItem[]): Promise; setStrokeWidth(strokeWidth: number): Promise; setTag(tag: any): Promise; setZIndex(zIndex: number): Promise; setClickable(clickable: boolean): Promise; setVisible(visible: boolean): Promise; } export class CircleImpl implements Circle { private readonly id: string; private readonly mapDivId: string; private readonly mapCapsuleId: number; constructor(mapDivId: string, mapCapsuleId: number, componentId: string) { this.mapDivId = mapDivId; this.mapCapsuleId = mapCapsuleId; this.id = componentId; } getCenter(): Promise { return this.getComponentOptions('getCenter'); } getFillColor(): Promise { return this.getComponentOptions('getFillColor'); } getId(): string { return this.id; } getRadius(): Promise { return this.getComponentOptions('getRadius'); } getStrokeColor(): Promise { return this.getComponentOptions('getStrokeColor'); } getStrokePattern(): Promise { return this.getComponentOptions('getStrokePattern'); } getStrokeWidth(): Promise { return this.getComponentOptions('getStrokeWidth'); } getTag(): Promise { return this.getComponentOptions('getTag'); } getZIndex(): Promise { return this.getComponentOptions('getZIndex'); } isClickable(): Promise { return this.getComponentOptions('isClickable'); } isVisible(): Promise { return this.getComponentOptions('isVisible'); } remove(): Promise { return asyncExec(""HMSMap"", ""removeComponent"", [this.mapDivId, this.id]); } setCenter(center: LatLng): Promise { return this.setComponentOptions('setCenter', {'center': center}); } setFillColor(fillColor: Color): Promise { return this.setComponentOptions('setFillColor', {'fillColor': fillColor}); } setRadius(radius: number): Promise { return this.setComponentOptions('setRadius', {'radius': radius}); } setStrokeColor(strokeColor: number): Promise { return this.setComponentOptions('setStrokeColor', {'strokeColor': strokeColor}); } setStrokePattern(strokePattern: PatternItem[]): Promise { return this.setComponentOptions('setStrokePattern', {'strokePattern': strokePattern}); } setStrokeWidth(strokeWidth: number): Promise { return this.setComponentOptions('setStrokeWidth', {'strokeWidth': strokeWidth}); } setTag(tag: any): Promise { return this.setComponentOptions('setTag', {'tag': tag}); } setZIndex(zIndex: number): Promise { return this.setComponentOptions('setZIndex', {'zIndex': zIndex}); } setClickable(clickable: boolean): Promise { return this.setComponentOptions('setClickable', {'clickable': clickable}); } setVisible(visible: boolean): Promise { return this.setComponentOptions('setVisible', {'visible': visible}); } private setComponentOptions(func: string, params: any): Promise { return asyncExec('HMSMap', 'componentOptions', [this.mapDivId, this.id, 'set', func, params]); } private async getComponentOptions(func: string): Promise { const [MASK] = await asyncExec(""HMSMap"", ""componentOptions"", [this.mapDivId, this.id, 'get', func, {}]); return [MASK] .value; } } ",result 203,"import { readMetadata } from '../services/readMetadata'; import { deleteLoginAction } from '../services/deleteLoginAction'; /** * Ensure the V1 Action exists. */ export function v1LoginActionMustExist() { Cypress.log({ message: '**--- Action check: start**' }); readMetadata().then(response => { const [MASK] = !!response.body.actions?.find( // TODO: properly type it action => action.name === 'TODO:' ); if ( [MASK] ) { Cypress.log({ message: '**--- The action exists**' }); Cypress.log({ message: '**--- Action check: end**' }); return; } Cypress.log({ message: '**--- The action does not exist**' }); cy.request('POST', 'http://localhost:8080/v1/metadata', { type: 'bulk', source: 'default', args: [ { type: 'set_custom_types', args: { scalars: [], input_objects: [ { name: 'SampleInput', description: null, fields: [ { name: 'username', type: 'String!', description: null, }, { name: '', type: 'String!', description: null, }, ], }, ], objects: [ { name: 'SampleOutput', description: null, fields: [ { name: 'accessToken', type: 'String!', description: null, }, ], }, { name: 'LoginResponse', fields: [ { name: 'accessToken', type: 'String!', }, ], }, ], enums: [], }, }, { type: 'create_action', args: { name: 'v1Login', definition: { arguments: [ { name: 'arg1', type: 'SampleInput!', description: null, }, ], kind: 'synchronous', output_type: 'SampleOutput', handler: 'http://host.docker.internal:3000', type: 'mutation', headers: [], timeout: null, request_transform: { version: 1, template_engine: 'Kriti', method: 'GET', url: '{{$base_url}}/users', query_params: {}, body: '{\n ""users"": {\n ""name"": {{$body.input.arg1.username}}\n }\n}', content_type: 'application/json', }, }, comment: null, }, }, ], }) .then(response => { expect(response.body, 'Response body exists').to.not.be.null; expect(response.body, 'Response body is an array').to.be.a('array'); expect( response.body[0], 'Response body contains success' ).to.have.property('message', 'success'); }) .then(() => { Cypress.log({ message: '**--- The action has been created**' }); Cypress.log({ message: '**--- Action check: end**' }); }); }); } ",actionExists 204,"// import * as fs from 'fs'; import * as commander from 'commander'; const zlogger = require('zlogger'); // import * as ConsoleLogger from 'zlogger'; export interface IOption { typescript: boolean; host?: string; source?: string; } const defaultOption: IOption = { typescript: false, source: 'static', }; /** * 读取静态文件 */ class WxappImageLoader { /** * 用户的配置,从命令行参数读取。 */ private option: IOption; private logger: ConsoleLogger; constructor( [MASK] : commander.Command) { this.logger = new ConsoleLogger({ prefix: '', time: false, }); const option: IOption = defaultOption; if ( [MASK] .typescript) { option.typescript = true; } this.option = option; } public async load() { const { typescript } = this.option; // const sourcePath = path.resolve(process.cwd(), source); if (typescript) { this.logger.info('生成 ts 文件'); } else { // tslint:disable-next-line: no-console this.logger.info('生成 ts 文件'); } } } export { WxappImageLoader }; ",input 205," import { Injectable, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { stringify } from 'querystring'; @Injectable() export class AccountService { constructor(private http: HttpClient,@Inject('BASE_URL') private baseUrl: string){ } public RegisterAsync(vm: Rainbow.ViewModels.Users.RegisterUserVM): Observable { return this.http.post(`${this.baseUrl}api/Account/Register`, vm); } public LoginAsync(vm: Rainbow.ViewModels.Users.LoginVM): Observable { return this.http.post(`${this.baseUrl}api/Account/Login`, vm); } public ForgetPasswordAsync(vm: Rainbow.ViewModels.Users.ForgetPasswordVM): Observable { return this.http.get(`${this.baseUrl}api/Account/ForgetPassword?${stringify(vm)}`); } public GetUserAsync(): Observable { return this.http.get(`${this.baseUrl}api/Account/UserInfo`); } public UserAvatar( [MASK] : String): Observable { return this.http.get(`${this.baseUrl}api/Account/UserAvatar/${ [MASK] }`); } } ",userId 206,"""use strict""; import * as assert from ""assert""; import { Promise } from ""es6-promise""; import * as fs from ""fs""; import * as request from ""request""; export class Imageclassification { private apiKey: string; private baseUrl: string; constructor( apiKey: any, baseUrl: string = ""https://sandbox.api.sap.com/ml/imageclassification/classification"") { assert(apiKey, ""apiKey is required""); this.apiKey = apiKey; this.baseUrl = baseUrl; } public classification(files: string | Buffer): Promise { return new Promise((resolve, reject) => { if (Buffer.isBuffer(files)) { this.call(resolve, reject, ""image.jpg"", files); } else { fs.readFile(files, {}, (fileErr, fileData) => { if (fileErr) { return reject(fileErr); } this.call(resolve, reject, files, fileData); }); } }); } /*eslint no-unused-vars [""off"", { ""args"": ""all"" }]*/ public customizable(modelName: string, version: string, files: string): Promise { return new Promise((resolve, reject) => { // const url = ""/ml/imageclassification/models/"" + modelName + ""/versions/"" + version; reject(""not implemented""); }); } private call(resolve: any, reject: any, files: string, fileData: Buffer) { const formData = { files: { value: fileData, options: files }, }; const headers = { APIKey: this.apiKey, Accept: ""application/json"", }; const url = this.baseUrl; request.post({ url, formData, headers }, (err, response, [MASK] ) => { if (err) { return reject(err); } if (response.statusCode === 404) { return reject( [MASK] ); } try { resolve(JSON.parse( [MASK] )); } catch (exception) { return reject(exception); } }); } } ",body 207,"import dbConnect from '../../src/middleware/mongodb'; import Image from '../../src/api/db/ImageUrl'; import initMiddleware from '../../src/middleware/init-middleware'; import { v4 as uuidv4 } from 'uuid'; import multer from 'multer'; const upload = multer(); export const config = { api: { bodyParser: false, }, }; const multerAny = initMiddleware(upload.any()); export default async function handler(req: any, res: any) { const { method } = req; await dbConnect(); switch (method) { case 'POST': try { await multerAny(req, res); if (!req.files?.length || req.files.length > 1) { return res.status(405).json({ message: 'No formdata' }); } const blob = req.files[0]; if (!blob.buffer) return res.status(405).json({ message: 'No formdata' }); const makeId = async function (): Promise { const uuid = uuidv4().split('').slice(0, 5).join(''); const [MASK] = await Image.findOne({ alias: uuid }); if ( [MASK] && [MASK] ._id) { return makeId(); } return uuid; }; const image = await Image.create({ data: blob.buffer, alias: await makeId(), style: req.headers?.style?.toString()?.slice(0, 5), name: req.headers?.name?.toString()?.slice(0, 10), }); res.status(201).json({ success: true, url: `${process.env.URL || 'http://localhost:3000'}/${image.alias}`, delete: `${process.env.URL || 'http://localhost:3000'}/api/delete/${ image._id }`, }); } catch (error) { res.status(400).json({ success: false, error }); } break; default: res.status(400).json({ success: false, message: 'Only post requests' }); break; } } ",found 208,"// 右键扩展 import editor from '@/store/editor' import EventEmitter from '@/utils/EventEmitter' import { isAppendAction } from '@/utils/BpmnDesignerUtils' import type Modeler from 'bpmn-js/lib/Modeler' import type PopupMenu from 'diagram-js/lib/features/popup-menu/PopupMenu' import type { Element } from 'diagram-js/lib/model/Types' import type Canvas from 'diagram-js/lib/core/Canvas' import type { Point } from 'diagram-js/lib/util/Types' import type { Event } from 'diagram-js/lib/core/EventBus' type ContextMenuEvent = { element: Element originalEvent: MouseEvent } & Event export default function (modeler: Modeler) { const config = editor().getEditorConfig if (!config.contextmenu) return modeler.on('element.contextmenu', 2000, (event: ContextMenuEvent) => { const { element, originalEvent } = event // 自定义右键菜单 if (config.customContextmenu) { return EventEmitter.emit('show-contextmenu', originalEvent, element) } // 原生面板扩展 // 1. 更改元素类型 // ts-ignore if (!isAppendAction(element)) { return config.templateChooser ? openEnhancementPopupMenu(modeler, element, originalEvent) : openPopupMenu(modeler, element, originalEvent) } // 2. 创建新元素 (仅开始模板扩展时可以) if (!config.templateChooser) return const connectorsExtension: any = modeler.get('connectorsExtension') connectorsExtension && connectorsExtension.createAnything(originalEvent, getContextMenuPosition(originalEvent)) }) } // default replace popupMenu function openPopupMenu(modeler: Modeler, element: Element, event: MouseEvent) { const popupMenu = modeler.get('popupMenu') if (popupMenu && !popupMenu.isEmpty(element, 'bpmn-replace')) { popupMenu.open(element, 'bpmn-replace', { x: event.clientX + 10, y: event.clientY + 10 }) // 设置画布点击清除事件 const canvas = modeler.get('canvas') const container = canvas.getContainer() const closePopupMenu = (ev) => { if (popupMenu && popupMenu.isOpen() && ev.delegateTarget.tagName === 'svg') { popupMenu.close() container.removeEventListener('click', closePopupMenu) } } container.addEventListener('click', closePopupMenu) } } // templateChooser enhancement replace popupMenu function openEnhancementPopupMenu(modeler: Modeler, element: Element, event: MouseEvent) { const replaceMenu: any = modeler.get('replaceMenu') if (replaceMenu) { replaceMenu.open(element, getContextMenuPosition(event, true)) } } ///// utils function getContextMenuPosition(event: MouseEvent, [MASK] ?: boolean): Point { return { x: event.clientX + ( [MASK] ? 10 : 0), y: event.clientY + ( [MASK] ? 25 : 0) } } ",offset 209,"import { Recorder } from './recorder'; export class Observer { protected _options: any; protected _recorder: Recorder; protected _media: HTMLVideoElement; protected _is_live: boolean; constructor(media: HTMLVideoElement, options?: any) { this._options = options this._media = media; this._is_live = false; this._recorder = new Recorder(this._options?.mode); } protected _record(event: String) { return () => { switch (event) { case 'loadstart': this._recorder.join_start(); break; case 'canplay': this._recorder.join_end(); break; case 'playing': this._recorder.state = 'playing'; if (this._recorder.play_t0 == 0) { this._recorder.play_t0 = performance.now(); } break; case 'pause': this._recorder.state = 'pause'; break; case 'ended': this._recorder.state = 'ended'; break; default: break; } } } private setStats() { setInterval(() => { // get frame statistics const [MASK] = this._media.getVideoPlaybackQuality(); const total_dropped_frame = [MASK] .droppedVideoFrames; this._recorder.total_dropped_frame = total_dropped_frame; this._recorder.current_time = this._media.currentTime; // get quality statistics this._recorder.height = this._media.videoHeight.toString(); this._recorder.width = this._media.videoWidth.toString(); // get page element info this._recorder.video_display_area_height = this._media.height.toString(); this._recorder.video_display_area_width = this._media.width.toString(); // get meta info this._recorder.volume = this._media.volume; this._recorder.visibility = document.visibilityState; this._recorder.duration = this._is_live ? this._media.duration : 0; // set player state this._recorder.record_play(); this._recorder.record_pause(); }, 10000); } addListener () { this._media.addEventListener('loadstart', this._record('loadstart')); this._media.addEventListener('canplay', this._record('canplay')); this._media.addEventListener('pause', this._record('pause')); this._media.addEventListener('ended', this._record('ended')); this._media.addEventListener('playing', this._record('playing')); this.setStats(); } removeListener () { console.log('Observe Process stop ...') } } ",video_playback_quality 210,"import { Application } from ""./Application""; import { Renderer } from ""../renderers/Renderer""; import { TextureFormat } from ""../resources/TextureFormat""; export abstract class WindowApplication extends Application { protected _date: Date protected _windowTitle: string protected _xPosition: number protected _yPosition: number protected _width: number protected _height: number protected _clearColor: number[] protected _allowResize: boolean protected _windowID: number protected _colorFormat: TextureFormat protected _depthStencilFormat: TextureFormat protected _numMultisamples: number protected _renderer: Renderer protected _lastTime: number protected _accumulatedTime: number protected _frameRate: number protected _frameCount: number protected _accumulatedFrameCount: number protected _timer: number protected _maxTimer: number constructor(windowTitle: string, xPosition: number, yPosition: number, width: number, height: number, clearColor: number[]) { super() this._date = new Date() this._windowTitle = windowTitle this._xPosition = xPosition this._yPosition = yPosition this._width = width this._height = height this._clearColor = clearColor this._allowResize = true this._windowID = 0 this._renderer = null this._lastTime = -1 this._accumulatedTime = 0 this._frameRate = 0 this._frameCount = 0 this._accumulatedFrameCount = 0 this._timer = 30 this._maxTimer = 300 // TODO Path if neccessary this._colorFormat = TextureFormat.A8R8G8B8 this._depthStencilFormat = TextureFormat.D24S8 this._numMultisamples = 0 } public dispose(): void { } public run(numArguments: number, args: string[]): number { let [MASK] : WindowApplication = Application.TheApplication as WindowApplication return [MASK] .main(numArguments, args) } public main(numArguments: number, args:string[]): number { return 0 } // member access public get windowTitle(): string { return this._windowTitle } public get xPosition(): number { return this._xPosition } public get yPosition(): number { return this._yPosition } public get width(): number { return this._width } public get height(): number { return this._height } public get aspectRatio(): number { return this._width/this._height } public set windowID(windowID: number) { this._windowID = windowID } public get windowID(): number { return this._windowID } public get renderer(): Renderer { return this._renderer } // event callbacks public onInitialize(): boolean { this._renderer.clearColor = this._clearColor return true } public onTerminate(): void { } public onMove(x: number, y: number): void { this._xPosition = x this._yPosition = y } public onResize(width: number, height: number): void { if(width > 0 && height > 0) { if(this._renderer) { this._renderer.resize(width, height) } this._width = width this._height = height } } public onPrecreate(): boolean { return true } public onPreidle(): void { this._renderer.clearBuffers() } public onDisplay(): void {} public onIdle(): void {} public onKeyDown(key: string, x: number, y: number): boolean { return false } public onKeyUp(key: string, x: number, y: number): boolean { return false } public onSpecialKeyDown(key: number, x: number, y: number): boolean { return false } public onSpecialKeyUp(key: number, x: number, y: number): boolean { return false } public onMouseClick(button: number, state: number, x: number, y: number, modifiers: number): boolean { return false } public onMotion(button: number, x: number, y: number, modifiers: number): boolean { return false } public onPassiveMotion(x: number, y: number): boolean { return false } public onMouseWheel(delta: number, x: number, y: number, modifiers: number): boolean { return false } // mouse position public setMousePosition(x: number, y: number): void {} public getMousePosition(): number[] { return [0,0] } // font public getStringWidth(text: string): number { return 0 } public getCharacterWidth(character: string): number { return 0 } public getFontHeight(): number { return 0 } // TODO key identifiers // performance measurements protected resetTime(): void { this._lastTime = -1 } protected measureTime(): void { if(this._lastTime == 1) { this._lastTime = this._date.getTime() / 1000 this._accumulatedTime = 0 this._frameRate = 0 this._frameCount = 0 this._accumulatedFrameCount = 0 this._timer = this._maxTimer } // accumulate the time only when the miniature time allows it if(--this._timer == 0) { let currentTime: number = this._date.getTime() / 1000 let delta: number = currentTime - this._lastTime this._lastTime = currentTime this._accumulatedTime += delta this._accumulatedFrameCount += this._frameCount this._frameCount = 0 this._timer = this._maxTimer } } protected updateFrameCount(): void { ++this._frameCount } protected drawFrameRate(x: number, y: number, color: number[]): void { if(this._accumulatedTime > 0) { this._frameRate = this._accumulatedFrameCount / this._accumulatedTime } else { this._frameRate = 0 } // TODO display on renderer // mRenderer.drawFramerate(x, y, color, message) console.log(`fps: ${this._frameRate}`) } }",theApp 211,"import * as http from 'http'; import * as fs from 'fs'; import { IDataConnector } from '../libs/dataconnector/dataconnector'; import { DatabaseConnector } from '../libs/dataconnector/databaseconnector'; import { FileConnector } from '../libs/dataconnector/fileconnector'; import { CMSResources } from '../libs/cms/resources'; import { CMSFormItems } from '../libs/cms/formitems'; import { RequestHandler } from '../libs/requesthandler'; const DEPLOY_FOLDER = ""../out""; let packageJson = require('../package.json'); class App { private connector: IDataConnector; public handleCommandLineCall(command: string, type: string, folder?: string): void { try { if(!this.isValidEnvocation(command, type, folder)) { throw Error (""Invalid Invocation""); } console.info(""Command Arguments:"", command, type, folder); if(command === ""run"") { console.info(""Starting Webserver ""); this.startWebserver(type, folder); } else if(command === ""setup"") { console.info(""Starting Setup ""); if(type === ""file"") { console.info(""\tFILE ""); this.connector = new FileConnector(folder); } else if(type === ""database"") { console.info(""\tDATABASE ""); this.connector = new DatabaseConnector(process.env.DATABASE_URL); } else { throw Error (""Invalid Type""); } this.connector.setupDatabase().then( x => process.exit() ); } else if(command === ""deploy"") { this.deploy(); } else { throw Error (""Invalid Command""); } } catch (error) { console.info(error.message); } } private deleteDirectory(directory: string, deleteparent: boolean): void { let that = this; let files = fs.readdirSync(directory); for(let file of files) { if(fs.statSync(directory + ""/"" + file).isDirectory()) { that.deleteDirectory(directory + ""/"" + file, true); } else { that.deleteFile(directory + ""/"" + file); } } if(deleteparent){ fs.rmdirSync(directory); } } private deleteFile(file: string): void { fs.unlinkSync(file); } private createDirectory(directory: string): void { if(!fs.existsSync(directory)) { fs.mkdirSync(directory); } } private copyFile(source: string, destination: string): void { let that = this; let dir = (/^[^\/]*\/(.*)(?=\/[^\/]+$)/gi.exec(destination)[0]); dir.split(""/"").reduce( (p: any, c: any): any => { let directory = p + (p !==""""? ""/"" :"""") + c; that.createDirectory(directory); return directory; }, """"); fs.createReadStream(source).pipe(fs.createWriteStream(destination)); } private copyFiles(source: string, destination: string): void { let files = fs.readdirSync(source); for(let file of files) { let currentFile = source + ""/"" + file; if(fs.statSync(currentFile).isDirectory()){ if(/(\.\/bin)|(\.\/libs)|(\.\/setup)/.test(currentFile)) { this.copyFiles(currentFile, destination + ""/"" + file ); } } else { if(!/\.?(ts)|(map)|(npmignore)|(gitignore)|(package.json)$/.test(file)){ this.copyFile(currentFile, destination + ""/"" + file); } } } } public deploy(): void { this.deleteDirectory(DEPLOY_FOLDER, false); this.copyFiles(""."", DEPLOY_FOLDER); let deploy_file = DEPLOY_FOLDER + ""/package.json""; let newPackage: any = { ""scripts"" : {""start"": ""node bin/app.js run database""} } newPackage.name = packageJson.name; newPackage.version = packageJson.version; newPackage.dependencies = packageJson.dependencies; fs.writeFile(deploy_file, JSON.stringify(newPackage) , function(innerexception: any){ if(innerexception) { throw innerexception; } }); } public isValidEnvocation(command: string, type: string, folder: string): boolean { return new RegExp(""run"").test(command) || new RegExp(""deploy"").test(command) || (new RegExp(""setup"").test(command) && (new RegExp(""database"").test(type) || (new RegExp(""file"").test(type) && folder !== undefined))); } public startWebserver(mode: string, folder: string): void { let webserverPort = process.env.PORT || 80; this.connector = mode === ""file"" ? new FileConnector(folder) : new DatabaseConnector(process.env.DATABASE_URL); let cmsResources = new CMSResources(this.connector); let [MASK] = new CMSFormItems(this.connector); let requesthandler = new RequestHandler(cmsResources, [MASK] , true); requesthandler.initialize().then(( ) => { http.createServer(requesthandler.handle.bind(requesthandler)).listen(webserverPort); console.info(""Webserver running on port: "" + webserverPort); }); } } let app = new App(); app.handleCommandLineCall(process.argv[2],process.argv[3], process.argv[4]);",cmsFormItems 212,"import { Component, OnInit } from '@angular/core'; import { select, Store } from '@ngrx/store'; import { includes, toLower } from 'lodash-es'; import moment from 'moment'; import { FormGroupState } from 'ngrx-forms'; import { NgrxAutocompleteConverter, NgrxDateToISO8601UTC, } from 'ngrx-forms-material'; import { NgrxDateTimeZoneToISO8601 } from 'projects/ngrx-forms-material/src/lib/converters/dateonly.converter'; import { NgrxDateToISO8601 } from 'projects/ngrx-forms-material/src/public-api'; import { filter, map, Observable, switchMap } from 'rxjs'; import { countries, Country, fruits, MyDomain, vegetables, } from './models/my-domain.model'; import { selectMyDomainForm, selectMyDomainFormAutocompleteData, selectMyDomainFormAutocompleteField, } from './store'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit { title = 'demo'; formState$: Observable>; dateConverter: NgrxDateToISO8601; dateUtcConverter: NgrxDateToISO8601UTC; countryConverter: NgrxAutocompleteConverter; dateTimeConverter: NgrxDateTimeZoneToISO8601; current_year = moment().year(); minDate = moment([this.current_year - 120, 0, 1]); maxDate = moment(); startDate = moment([this.current_year - 18, 0, 1]); allFruits = fruits; allVegetables = vegetables; allCountries = countries; constructor(private store: Store) {} ngOnInit() { this.dateConverter = new NgrxDateToISO8601(); this.dateUtcConverter = new NgrxDateToISO8601UTC(); this.dateTimeConverter = new NgrxDateTimeZoneToISO8601('Europe/Paris'); this.countryConverter = new NgrxAutocompleteConverter( this.allCountries, 'code' ); this.formState$ = this.store.pipe(select(selectMyDomainForm)); } displayCountry(country?: Country): string | undefined { return country ? country.label : undefined; } filteredCountries$() { return this.store.pipe( select(selectMyDomainFormAutocompleteField), filter(( [MASK] ) => [MASK] === 'birthCountry'), switchMap((_) => this.store.pipe( select(selectMyDomainFormAutocompleteData), map((autocomplete) => autocomplete.filter( this.allCountries, (country) => includes( toLower(country.label), toLower(autocomplete.seized) ) || includes(country.code, autocomplete.seized) ) ) ) ) ); } } ",field 213,"type JsonPrimitive = string | number | boolean | null | undefined; type JsonArray = JsonAny[]; type JsonAny = JsonPrimitive | JsonArray | JsonObject; interface JsonObject { [key: string]: JsonAny; } /** https://docs.splunk.com/Documentation/Splunk/latest/Data/FormateventsforHTTPEventCollector */ interface HecOverrides { /** Overrides the default host of the HEC. */ host?: string; /** Overrides the default source of the HEC. */ source?: string; /** Overrides the default sourcetype of the HEC. */ sourceType?: string; /** Overrides the default index of the HEC. */ index?: string; } interface WebLoggerConfig extends HecOverrides { /** The origin of your Splunk instance. */ origin: string; /** The Splunk access token provided by your HEC endpoint. */ token: string; /** The max size in bytes of events you want to store before sending. */ bufferCapacity?: number; /** The max time in milliseconds to wait before sending events. 0 denotes no timeout */ bufferTimeout?: number; /** Middleware functions to run on each event */ middleware?: middleware[]; } type middleware = (event: JsonObject) => JsonObject; export default class WebLogger { url: string; host?: string; source?: string; sourceType?: string; index?: string; buffer: string = """"; bufferCapacity: number; middleware: middleware[]; constructor({ origin, token, index, host, source, sourceType, bufferCapacity = 4096, middleware = [], }: WebLoggerConfig) { this.url = `${origin}/services/collector/event?token=${token}`; this.host = host; this.source = source; this.sourceType = sourceType; this.index = index; this.bufferCapacity = bufferCapacity; this.middleware = middleware; addEventListener(""pagehide"", () => { this.send(); }); document.addEventListener(""visibilitychange"", () => { if (document.visibilityState === ""hidden"") { this.send(); } }); } /** Adds an event to the event buffer. */ log(event: JsonObject): boolean { for (const middleware of this.middleware) { event = middleware(event); } const [MASK] = { index: this.index, host: this.host, source: this.source, sourcetype: this.sourceType, time: Date.now(), event, }; this.buffer += JSON.stringify( [MASK] ); if (this.buffer.length >= this.bufferCapacity) { return this.send(); } return false; } /** */ send(): boolean { if (this.buffer) { const success = navigator.sendBeacon(this.url, this.buffer); if (success) { this.buffer = """"; } return success; } return false; } } ",fullEvent 214,"import axios from 'axios'; import type { Logging } from 'homebridge'; export interface ControlDProfile { PK: string; name: string; updated: number; disable_ttl?: number; profile?: { da?: { status: number; do: number; }; }; filteringEnabled?: boolean; // Helper property to track filtering status } export interface ControlDDevice { PK: string; name: string; profile: { PK: string; name: string; }; status: number; } export class ControlDApi { private readonly baseUrl = 'https://api.controld.com'; private readonly apiToken: string; private readonly log: Logging; constructor(apiToken: string, log: Logging) { this.apiToken = apiToken; this.log = log; } private getHeaders() { return { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.apiToken}`, }; } async validateApiToken(): Promise { try { const response = await axios.get(`${this.baseUrl}/profiles`, { headers: this.getHeaders(), }); return response.status === 200 && response.data && response.data.success === true; } catch (error) { if (axios.isAxiosError(error)) { if (error.response?.status === 403) { const errorData = error.response.data as { error?: { code: number; message: string } }; if (errorData?.error?.code === 40301) { this.log.error('Control D API Permission Error: Your token does not have access to the profiles endpoint.'); this.log.error('Please create a new token with these permissions: profiles:read, profiles:write'); this.log.error('Visit https://controld.com/dashboard → Settings → API to update your token.'); } else { this.log.error('Control D API Authentication Error: Your API token appears to be invalid or lacks required permissions.'); this.log.error('Please verify that you have entered the correct token and that it has the necessary permissions.'); this.log.error('Visit https://controld.com/dashboard to generate a new token if needed.'); } } else if (error.response) { this.log.error(`API Error validating token: Status ${error.response.status}, Message: ${JSON.stringify(error.response.data)}`); } else { this.log.error(`Network Error validating token: ${error.message}`); } } else { this.log.error('Control D API Error while validating token:', error); } return false; } } async getProfiles(): Promise { try { const response = await axios.get(`${this.baseUrl}/profiles`, { headers: this.getHeaders(), }); if (!response.data || !response.data.success || !response.data.body || !Array.isArray(response.data.body.profiles)) { this.log.warn('Unexpected response format from Control D API - profiles endpoint'); return []; } const profiles = response.data.body.profiles || []; const currentTime = Math.floor(Date.now() / 1000); // Add helper property to track filtering status return profiles.map((profile: ControlDProfile) => { // A profile is considered disabled if it has a disable_ttl value greater than current time // A disable_ttl of 0 means filtering is enabled const [MASK] = profile.disable_ttl === 0; const isUnset = profile.disable_ttl === undefined || profile.disable_ttl === null; const isExpired = profile.disable_ttl !== undefined && profile.disable_ttl <= currentTime; const filteringEnabled = [MASK] || isUnset || isExpired; return { ...profile, filteringEnabled, }; }); } catch (error) { if (axios.isAxiosError(error)) { if (error.response?.status === 403) { const errorData = error.response.data as { error?: { code: number; message: string } }; if (errorData?.error?.code === 40301) { this.log.error('Control D API Permission Error: Your token does not have access to the profiles endpoint.'); this.log.error('Please create a new token with these permissions: profiles:read, profiles:write'); } else { this.log.error('Control D API Authentication Error: Failed to fetch profiles due to invalid token or insufficient permissions.'); } } else if (error.response) { this.log.error(`API Error fetching profiles: Status ${error.response.status}, Message: ${JSON.stringify(error.response.data)}`); } else { this.log.error(`Network Error fetching profiles: ${error.message}`); } } else { this.log.error('Failed to get profiles:', error); } return []; } } async toggleProfileFiltering(profileId: string, enabled: boolean): Promise { try { this.log.debug(`Setting profile ${profileId} filtering to ${enabled ? 'enabled' : 'disabled'}`); let requestData; if (enabled) { // Enable profile by setting disable_ttl to 0 requestData = { disable_ttl: 0 }; } else { // Disable profile for 24 hours (86400 seconds) const disableTtl = Math.floor(Date.now() / 1000) + 86400; requestData = { disable_ttl: disableTtl }; } const response = await axios.put( `${this.baseUrl}/profiles/${profileId}`, requestData, { headers: this.getHeaders() }, ); if (response.status === 200 && response.data && response.data.success) { this.log.debug(`Successfully ${enabled ? 'enabled' : 'disabled'} filtering for profile`); return true; } else { this.log.warn(`Unexpected status code or response when updating profile filtering: ${response.status}`); return false; } } catch (error) { if (axios.isAxiosError(error)) { if (error.response?.status === 403) { this.log.error('Control D API Authentication Error: Failed to toggle profile filtering. Invalid token or insufficient permissions.'); } else if (error.response) { this.log.error(`API Error: Status ${error.response.status}, Message: ${JSON.stringify(error.response.data)}`); } else { this.log.error(`Network Error: ${error.message}`); } } else { this.log.error('Failed to toggle profile filtering:', error); } return false; } } // Keeping this method for backwards compatibility, but we're not using it anymore async getDevices(): Promise { try { const response = await axios.get(`${this.baseUrl}/devices`, { headers: this.getHeaders(), }); if (!response.data || !response.data.success || !response.data.body || !Array.isArray(response.data.body.devices)) { this.log.warn('Unexpected response format from Control D API - devices endpoint'); return []; } return response.data.body.devices || []; } catch (error) { if (axios.isAxiosError(error)) { if (error.response?.status === 403) { this.log.error('Control D API Authentication Error: Failed to fetch devices due to invalid token or insufficient permissions.'); } else if (error.response) { this.log.error(`API Error fetching devices: Status ${error.response.status}, Message: ${JSON.stringify(error.response.data)}`); } else { this.log.error(`Network Error fetching devices: ${error.message}`); } } else { this.log.error('Failed to get devices:', error); } return []; } } async setDeviceProfile(deviceId: string, profileId: string): Promise { try { this.log.debug(`Setting device ${deviceId} to use profile ${profileId}`); const response = await axios.put( `${this.baseUrl}/devices/${deviceId}`, { profile: { PK: profileId } }, { headers: this.getHeaders() }, ); if (response.status === 200 && response.data && response.data.success) { this.log.debug('Successfully updated device profile'); return true; } else { this.log.error( `Control D API Authentication Error: Failed to set device profile (${deviceId} to ${profileId}). ` + 'Invalid token or insufficient permissions.', ); return false; } } catch (error) { if (axios.isAxiosError(error)) { if (error.response?.status === 403) { this.log.error( `Control D API Authentication Error: Failed to set device profile (${deviceId} to ${profileId}). ` + 'Invalid token or insufficient permissions.', ); } else if (error.response) { this.log.error(`API Error: Status ${error.response.status}, Message: ${JSON.stringify(error.response.data)}`); } else { this.log.error(`Network Error: ${error.message}`); } } else { this.log.error('Failed to set device profile:', error); } return false; } } }",isZero 215,"import {OfferStoreSelectors} from './offer-store'; import {DictionaryStoreSelectors} from './dictionary-store'; import {createSelector, MemoizedSelector} from '@ngrx/store'; import {ExtraChannel, Hardware, InvoiceRow, Service, Summary} from '../models'; import {DemoStoreSelectors} from './demo-store'; export const selectError: MemoizedSelector = createSelector( DemoStoreSelectors.selectDemoFeatureError, DictionaryStoreSelectors.selectDictionaryFeatureError, OfferStoreSelectors.selectOfferFeatureError, (demo:string, dictionary: string, offer: string) => demo || dictionary || offer ); export const selectIsLoading: MemoizedSelector = createSelector( DemoStoreSelectors.selectDemoFeatureIsLoading, DictionaryStoreSelectors.selectDictionaryFeatureIsLoading, OfferStoreSelectors.selectOfferFeatureIsLoading, (demo:boolean, dictionary: boolean, offer: boolean) => demo || dictionary || offer ); export const selectOfferExtraChannels: MemoizedSelector = createSelector( DictionaryStoreSelectors.selectDictionaryExtraChannels, OfferStoreSelectors.selectOfferDataModel, (channels, offer) => { if (!offer) { return []; } if (!channels) { return []; } const dict = makeDict(channels, 'code'); return (offer.extraChannels || []) .filter(channel => dict[channel.code]) .map(channel => ({ ...channel, title: dict[channel.code].name, description: [dict[channel.code].description, ...dict[channel.code].details].join('\n'), oldPrice: channel.price, })); } ); function makeDict(arr: T[], field: keyof T): { [field: string]: T } { return Object.assign({}, ...(arr || []).map(item => ({[`${item[field]}`]: item}))); } export const selectOfferHardwares: MemoizedSelector = createSelector( DictionaryStoreSelectors.selectDictionaryHardware, OfferStoreSelectors.selectOfferDataModel, (hardwares, offer) => { if (!offer) { return []; } if (!hardwares) { return []; } const dict = makeDict(hardwares, 'code'); return (offer.hardware || []) .filter(hardware => dict[hardware.code]) .map(hardware => ({ code: hardware.code, selected: hardware.selected, multiRoom: hardware.multiRoom, title: dict[hardware.code].name, description: dict[hardware.code].description, price: hardware.montlyPayment || 0, activationPrice: hardware.activationPrice || 0, })); } ); export const selectOfferServices: MemoizedSelector = createSelector( DictionaryStoreSelectors.selectDictionaryService, OfferStoreSelectors.selectOfferDataModel, (services, offer) => { if (!offer) { return []; } if (!services) { return []; } const dict = makeDict(services, 'code'); return (offer.extraServices || []) .filter(service => dict[service.code]) .map(service => ({ code: service.code, selected: service.selected, title: dict[service.code].name, description: dict[service.code].description, price: service.monthlyPriceAfterDiscounts || 0, oldPrice: service.monthlyPrice || 0, activationPrice: service.activationPriceAfterDiscounts || 0, oldActivationPrice: service.activationPrice || 0, })); } ); export const selectOfferSummary: MemoizedSelector = createSelector( DictionaryStoreSelectors.selectDictionaryPackages, DictionaryStoreSelectors.selectDictionaryIntervals, OfferStoreSelectors.selectOfferDataModel, (packages, intervals, offer) => { if (!offer) { return null; } const packagesDict = makeDict(packages, 'code'); const [MASK] = makeDict(intervals, 'value'); return { activationPrice: offer.activationPriceAfterDiscounts, oldActivationPrice: offer.activationPrice, price: offer.priceAfterDiscounts, oldPrice: offer.price, interval: `${offer.duration} ${ [MASK] [offer.duration].displayUnitValue}`, package: packagesDict[offer.package].publicName, }; } ); export const selectOfferInvoicesRows: MemoizedSelector = createSelector( OfferStoreSelectors.selectOfferInvoices, (invoices) => invoices.map((invoice, index) => ({ no: index + 1, date: invoice.paymentDate, price: invoice.valueAfterDiscounts || invoice.value, oldPrice: invoice.value || invoice.valueAfterDiscounts, })) ); ",intervalsDict 216,"'use server' import admin from ""@/lib/firebase/firebase-server""; import { prisma } from ""@/lib/prisma""; import { ERROR_CODES } from ""@/lib/responses/errors""; import { CODES_SUCCESS } from ""@/lib/responses/success""; export async function signInWithFirebase( [MASK] : string) { try { const user = await prisma.user.findFirst({ where: { firebaseUid: [MASK] , }, select: { name: true, role: true, company: { select: { id: true, name: true, planType: true } } }, }); const customClaims = { name: user?.name, role: user?.role, companyId: user?.company?.id, companyName: user?.company?.name, plan: user?.company?.planType, }; await admin.auth().setCustomUserClaims( [MASK] , customClaims); return CODES_SUCCESS.QUERY_OK; } catch (error: any) { return { error: error.message, ...ERROR_CODES.BAD_REQUEST }; } } ",uid 217,"import { DType } from ""../types/dtypes""; import { Connection, ConnectionChangedCallback, ValueChangedCallback, SubscriptionType, DeviceQueriedCallback } from ""./plugin""; export class ConnectionForwarder implements Connection { private prefixConnections: [string, Connection | undefined][]; private connected: boolean; public constructor(prefixConnections: [string, Connection | undefined][]) { this.prefixConnections = prefixConnections; this.connected = false; } private getConnection(pvName: string): Connection { for (const [prefix, connection] of this.prefixConnections) { if (pvName.startsWith(prefix)) { if (connection !== undefined) { return connection; } else { throw new Error(`Connection for ${prefix} not initiated`); } } } throw new Error(`No connections for ${pvName}`); } public subscribe(pvName: string, type: SubscriptionType): string { const connection = this.getConnection(pvName); return connection.subscribe(pvName, type); } public unsubscribe(pvName: string): void { const connection = this.getConnection(pvName); return connection.unsubscribe(pvName); } public isConnected(): boolean { return this.connected; } public putPv(pvName: string, value: DType): void { const connection = this.getConnection(pvName); return connection.putPv(pvName, value); } public getDevice(device: string): void { const connection = this.getConnection(device); return connection.getDevice(device); } public connect( connectionCallback: ConnectionChangedCallback, [MASK] : ValueChangedCallback, deviceCallback: DeviceQueriedCallback ): void { for (const [, connection] of this.prefixConnections) { if (connection !== undefined) { if (!connection.isConnected()) { connection.connect(connectionCallback, [MASK] , deviceCallback); } } } } } ",valueCallback 218,"import { Component, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ActivatedRoute, Router, RouterModule } from '@angular/router'; import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatChipsModule } from '@angular/material/chips'; import { MatDialogModule, MatDialog } from '@angular/material/dialog'; import { MatDividerModule } from '@angular/material/divider'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { MatInputModule } from '@angular/material/input'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatSnackBarModule, MatSnackBar } from '@angular/material/snack-bar'; import { MatTabsModule } from '@angular/material/tabs'; import { MatListModule } from '@angular/material/list'; import { ApprovalService } from '../services/approval.service'; import { Trip, TripStatus, ExpenseType, CarRental, Hotel, Flight, Taxi } from '../../trips/models/trip.model'; import { ApprovalNote } from '../models/approval.model'; @Component({ selector: 'app-approval-detail', standalone: true, imports: [ CommonModule, RouterModule, ReactiveFormsModule, MatButtonModule, MatCardModule, MatChipsModule, MatDialogModule, MatDividerModule, MatFormFieldModule, MatIconModule, MatInputModule, MatProgressSpinnerModule, MatSnackBarModule, MatTabsModule, MatListModule ], templateUrl: './approval-detail.component.html', styleUrls: ['./approval-detail.component.scss'] }) export class ApprovalDetailComponent implements OnInit { trip: Trip | null = null; loading = true; tripId!: number; notes: ApprovalNote[] = []; noteForm!: FormGroup; submitting = false; constructor( private route: ActivatedRoute, private router: Router, private approvalService: ApprovalService, private fb: FormBuilder, private snackBar: MatSnackBar ) {} ngOnInit(): void { this.createNoteForm(); this.route.params.subscribe(params => { if (params['id']) { this.tripId = +params['id']; this.loadTrip(); } }); } createNoteForm(): void { this.noteForm = this.fb.group({ note: ['', [Validators.required, Validators.maxLength(500)]] }); } loadTrip(): void { this.loading = true; this.approvalService.getTripForApproval(this.tripId).subscribe({ next: (trip) => { this.trip = trip; this.notes = []; this.loading = false; }, error: (error) => { console.error('Error loading trip', error); this.snackBar.open('Error loading trip. Please try again.', 'Close', { duration: 3000 }); this.loading = false; this.router.navigate(['/approvals/pending']); } }); } getStatusClass(status: string): string { switch (status) { case TripStatus.DRAFT: return 'status-draft'; case TripStatus.PENDING_APPROVAL: return 'status-pending'; case TripStatus.APPROVED: return 'status-approved'; case TripStatus.REJECTED: return 'status-rejected'; default: return ''; } } getExpenseTypeLabel( [MASK] : string): string { switch ( [MASK] ) { case ExpenseType.FLIGHT: return 'Flight'; case ExpenseType.HOTEL: return 'Hotel'; case ExpenseType.CAR_RENTAL: return 'Car Rental'; case ExpenseType.TAXI: return 'Taxi'; default: return 'Other'; } } isCarRental(details: any): details is CarRental { return details && 'carName' in details && 'pickupDateTime' in details && 'dropoffDateTime' in details && 'pickupLocation' in details && 'dropoffLocation' in details; } isHotel(details: any): details is Hotel { return details && 'hotelName' in details && 'location' in details && 'checkInDate' in details && 'checkOutDate' in details; } isFlight(details: any): details is Flight { return details && 'airline' in details && 'from' in details && 'to' in details && 'departureDateTime' in details && 'arrivalDateTime' in details; } isTaxi(details: any): details is Taxi { return details && 'from' in details && 'to' in details && 'dateTime' in details; } approveTrip(): void { if (!this.trip) return; this.submitting = true; const note = this.noteForm.value.note || undefined; this.approvalService.approveTrip(this.tripId, note).subscribe({ next: (trip) => { this.snackBar.open('Trip approved successfully', 'Close', { duration: 3000 }); this.trip = trip; this.submitting = false; setTimeout(() => { this.router.navigate(['/dashboard']); }, 1500); }, error: (error) => { console.error('Error approving trip', error); this.snackBar.open('Error approving trip. Please try again.', 'Close', { duration: 3000 }); this.submitting = false; } }); } rejectTrip(): void { if (!this.trip) return; this.submitting = true; const note = this.noteForm.value.note || undefined; this.approvalService.rejectTrip(this.tripId, note).subscribe({ next: (trip) => { this.snackBar.open('Trip rejected', 'Close', { duration: 3000 }); this.trip = trip; this.submitting = false; setTimeout(() => { this.router.navigate(['/dashboard']); }, 1500); }, error: (error) => { console.error('Error rejecting trip', error); this.snackBar.open('Error rejecting trip. Please try again.', 'Close', { duration: 3000 }); this.submitting = false; } }); } } ",type 219,"import { v } from ""convex/values""; import { internalQuery, mutation, query } from ""./_generated/server""; import { vDocumentId } from ""./schema""; import { hash as sha256 } from ""fast-sha256""; export const submitSnapshot = mutation({ args: { documentId: vDocumentId, data: v.bytes(), debugDump: v.optional(v.any()), }, handler: async (ctx, args) => { const hash = keyHash(new Uint8Array(args.data)); const existing = await ctx.db .query(""automerge"") .withIndex(""doc_type_hash"", (q) => q .eq(""documentId"", args.documentId) .eq(""type"", ""snapshot"") .eq(""hash"", hash) ) .first(); if (!existing) { return ctx.db.insert(""automerge"", { documentId: args.documentId, data: args.data, hash, type: ""snapshot"", debugDump: args.debugDump, }); } return existing._id; }, }); export const submitChange = mutation({ args: { documentId: vDocumentId, change: v.bytes(), debugDump: v.optional(v.any()), }, handler: async (ctx, args) => { const hash = keyHash(new Uint8Array(args.change)); const existing = await ctx.db .query(""automerge"") .withIndex(""doc_type_hash"", (q) => q .eq(""documentId"", args.documentId) .eq(""type"", ""incremental"") .eq(""hash"", hash) ) .first(); if (!existing) { return ctx.db.insert(""automerge"", { documentId: args.documentId, data: args.change, hash, type: ""incremental"", debugDump: args.debugDump, }); } return existing._id; }, }); const MINUTE = 60 * 1000; const RETENTION_BUFFER = 5 * MINUTE; export const pullChanges = query({ args: { documentId: vDocumentId, since: v.number(), numItems: v.optional(v.number()), cursor: v.optional(v.string()), }, handler: async (ctx, args) => { const result = await ctx.db .query(""automerge"") .withIndex(""documentId"", (q) => q.eq(""documentId"", args.documentId).gt(""_creationTime"", args.since) ) .paginate({ numItems: args.numItems ?? 10, cursor: args.cursor ?? null, }); // For the first page, also reach further back to avoid missing changes // inserted out of order. // This isn't part of the paginate call, since the cursors wouldn't // stay consistent if they're based on Date.now(). if (!args.cursor) { const retentionBuffer = await ctx.db .query(""automerge"") .withIndex(""documentId"", (q) => q .eq(""documentId"", args.documentId) .gt(""_creationTime"", args.since - RETENTION_BUFFER) .lte(""_creationTime"", args.since) ) .collect(); result.page = retentionBuffer.concat(result.page); } return result; }, }); export const getChanges = internalQuery({ args: { documentId: vDocumentId }, handler: async (ctx, args) => { return await ctx.db .query(""automerge"") .withIndex(""doc_type_hash"", (q) => q.eq(""documentId"", args.documentId)) .collect(); }, }); /** * Hash functions */ // Based on https://github.com/automerge/automerge-repo/blob/fixes/packages/automerge-repo/src/storage/keyHash.ts function keyHash( [MASK] : Uint8Array) { // calculate hash const hash = sha256( [MASK] ); // To hex string return Array.from(hash, (byte) => byte.toString(16).padStart(2, ""0"")).join( """" ); } ",binary 220,"import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting, requestUrl, TFile } from 'obsidian'; interface Workspace { name: string; slug: string; } interface AnythingObsidianSettings { apiKey: string; rootUrl: string; workspaces: Workspace[]; selectedWorkspaces: string[]; syncedFolders: string[]; autoDelete: boolean; updateHandling: 'keep-in-workspace' | 'archive' | 'delete'; remoteBaseFolder: string; autoSync: boolean; autoSyncInterval: number; showNotifications: boolean; } const DEFAULT_SETTINGS: AnythingObsidianSettings = { apiKey: '', rootUrl: 'http://localhost:3001', workspaces: [], selectedWorkspaces: [], syncedFolders: [], autoDelete: false, updateHandling: 'archive', remoteBaseFolder: 'Obsidian Vault', autoSync: false, autoSyncInterval: 5, showNotifications: true, } export default class AnythingObsidian extends Plugin { settings: AnythingObsidianSettings; autoSyncIntervalId: number | null = null; async onload() { await this.loadSettings(); this.applyAutoSyncSettings(); // This adds a settings tab so the user can configure various aspects of the plugin this.addSettingTab(new AnythingObsidianSettingTab(this.app, this)); this.addCommand({ id: 'sync-folders-to-anything-llm', name: 'Sync folders to Anything LLM', callback: async () => { this.notify('Sync process initiated...'); await this.syncFolders(); } }); this.addCommand({ id: 'upload-active-file-to-anything-llm', name: 'Upload active file to Anything LLM', editorCallback: async (editor: Editor, view: MarkdownView) => { const { selectedWorkspaces, apiKey, rootUrl } = this.settings; if (!selectedWorkspaces || selectedWorkspaces.length === 0) { this.notify('No workspace selected. Please select a workspace in the plugin settings.'); return; } if (!apiKey || !rootUrl) { this.notify('API Key or Root URL is missing. Please configure them in the settings.'); return; } const file = view.file; if (!file) { this.notify('No active file to upload.'); return; } this.notify(`Uploading ${file.name}...`); await this.uploadFile(file, selectedWorkspaces); } }); } async syncFolders() { const { apiKey, rootUrl, syncedFolders, remoteBaseFolder } = this.settings; if (!syncedFolders || syncedFolders.length === 0) { this.notify('No folders configured for syncing.'); return; } await this.ensureRemoteFolderExists(remoteBaseFolder); this.notify('Fetching remote file list...'); const remoteFiles = await this.getRemoteFileList(); if (remoteFiles === null) { this.notify('Failed to fetch remote files. Aborting sync.'); return; } this.notify('Scanning local files...'); const localFiles = await this.getLocalFiles(syncedFolders); const { toCreate, toUpdate, toDelete } = this.compareFiles(localFiles, remoteFiles); console.log('Files to create:', toCreate); console.log('Files to update:', toUpdate); console.log('Files to delete:', toDelete); this.notify('Sync comparison complete. Check console for details.'); // Now, perform the actual file operations await this.processCreations(toCreate, localFiles); await this.processUpdates(toUpdate, localFiles, remoteFiles); await this.processDeletions(toDelete, remoteFiles); // Final cleanup step if (this.settings.autoDelete) { this.notify('Auto-delete is enabled, clearing remote archives...'); await this.clearRemoteArchives(); } } async processCreations(toCreate: Set, localFiles: Map) { for (const path of toCreate) { const file = this.app.vault.getAbstractFileByPath(localFiles.get(path).path); if (file instanceof TFile) { this.notify(`Creating: ${file.name}`); await this.uploadFile(file, this.settings.selectedWorkspaces); } } } async processUpdates(toUpdate: Set, localFiles: Map, remoteFiles: Map) { const { updateHandling } = this.settings; if (toUpdate.size === 0) return; const filesToUpload: TFile[] = []; const remotePathsToModify: string[] = []; for (const key of toUpdate) { const localFile = localFiles.get(key); const remoteFile = remoteFiles.get(key); if (!localFile || !remoteFile) continue; filesToUpload.push(this.app.vault.getAbstractFileByPath(localFile.path) as TFile); remotePathsToModify.push(`${this.settings.remoteBaseFolder}/${remoteFile.name}`); } this.notify(`Found ${filesToUpload.length} file(s) to update.`); // Always upload the new version first for (const file of filesToUpload) { await this.uploadFile(file, this.settings.selectedWorkspaces); } // Now, handle the old version based on the setting if (updateHandling === 'keep-in-workspace') { // Do nothing. The old file is kept and its embeddings remain. this.notify('Kept old versions in workspace.'); return; } // For both 'archive' and 'delete', we need to remove the old embeddings for (const slug of this.settings.selectedWorkspaces) { await this.removeDocumentsFromWorkspace(slug, remotePathsToModify); } if (updateHandling === 'archive') { // Move the old files to an archive folder await this.moveFilesToArchive(remotePathsToModify); } if (updateHandling === 'delete') { // Move the old files to the trash folder, which will be deleted if auto-delete is on await this.moveFilesToTrash(remotePathsToModify); } } async uploadFile(file: TFile, workspaces: string[]) { const { apiKey, rootUrl, remoteBaseFolder } = this.settings; await this.ensureRemoteFolderExists(remoteBaseFolder); const fileContent = await this.app.vault.read(file); const mangledName = this.getMangledFileName(file); const formData = new FormData(); formData.append('file', new Blob([fileContent], { type: 'text/markdown' }), mangledName); try { const response = await fetch(`${rootUrl}/api/v1/document/upload/${encodeURIComponent(remoteBaseFolder)}`, { method: 'POST', body: formData, headers: { 'Authorization': `Bearer ${apiKey}` } }); const responseData = await response.json(); if (!response.ok || !responseData.success) { const errorMessage = responseData.error || `HTTP error! Status: ${response.status}`; this.notify(`Failed to upload ${file.name}: ${errorMessage}`); return; // Stop if upload failed } // If upload is successful, add to workspaces const newDocumentName = responseData.documents[0].name; const documentPath = `${remoteBaseFolder}/${newDocumentName}`; for (const slug of workspaces) { await this.addDocumentToWorkspace(slug, documentPath); } } catch (e: any) { this.notify(`Failed to upload ${file.name}.`); } } async addDocumentToWorkspace(slug: string, documentPath: string) { const { apiKey, rootUrl } = this.settings; try { await requestUrl({ url: `${rootUrl}/api/v1/workspace/${slug}/update-embeddings`, method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` }, body: JSON.stringify({ adds: [documentPath] }) }); } catch (e: any) { console.error(`Failed to add ${documentPath} to workspace ${slug}:`, e); this.notify(`Failed to add document to workspace ${slug}.`); } } async moveFilesToTrash(remotePaths: string[]) { await this.moveFilesToFolder(remotePaths, '_trash'); } async moveFilesToArchive(remotePaths: string[]) { await this.moveFilesToFolder(remotePaths, '_archive'); } async moveFilesToFolder(remotePaths: string[], targetFolder: string) { if (remotePaths.length === 0) return; const { apiKey, rootUrl } = this.settings; const filesToMove = remotePaths.map(path => ({ from: path, to: `${targetFolder}/${path.split('/').pop()}` })); try { await this.ensureRemoteFolderExists(targetFolder); await fetch(`${rootUrl}/api/v1/document/move-files`, { method: 'POST', body: JSON.stringify({ files: filesToMove }), headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` } }); this.notify(`Moved ${remotePaths.length} file(s) to the ${targetFolder} folder.`); } catch (e: any) { console.error(`Error moving files to ${targetFolder}:`, e); this.notify(`Failed to move files to ${targetFolder}.`); } } async processDeletions(toDelete: Set, remoteFiles: Map) { if (toDelete.size === 0) return; const remotePathsToDelete: string[] = []; const { remoteBaseFolder } = this.settings; for (const key of toDelete) { const remoteFile = remoteFiles.get(key); if (!remoteFile) continue; const remotePath = `${remoteBaseFolder}/${remoteFile.name}`; remotePathsToDelete.push(remotePath); } this.notify(`Found ${remotePathsToDelete.length} file(s) to delete.`); for (const slug of this.settings.selectedWorkspaces) { await this.removeDocumentsFromWorkspace(slug, remotePathsToDelete); } await this.moveFilesToTrash(remotePathsToDelete); } async removeDocumentsFromWorkspace(slug: string, documentPaths: string[]) { if (documentPaths.length === 0) return; const { apiKey, rootUrl } = this.settings; try { await requestUrl({ url: `${rootUrl}/api/v1/workspace/${slug}/update-embeddings`, method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` }, body: JSON.stringify({ deletes: documentPaths }) }); } catch (e: any) { console.error(`Failed to remove documents from workspace ${slug}:`, e); this.notify(`Failed to remove documents from workspace ${slug}.`); } } async clearRemoteArchives() { const { apiKey, rootUrl } = this.settings; const foldersToClear = ['_trash', '_archive']; for (const folderName of foldersToClear) { try { await fetch(`${rootUrl}/api/v1/document/remove-folder`, { method: 'DELETE', body: JSON.stringify({ name: folderName }), headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` } }); this.notify(`Cleared the ${folderName} folder.`); } catch (e: any) { // It's okay if the folder doesn't exist, so we only log other errors. if (e.message && !e.message.includes('404')) { console.error(`Error clearing ${folderName} folder:`, e); } } } } getMangledFileName(file: TFile): string { return file.path.replace(/\//g, '_-_'); } getRemotePathKey(mangledName: string): string { return `${this.settings.remoteBaseFolder}/${mangledName}`; } async getRemoteFileList(): Promise | null> { const { apiKey, rootUrl, remoteBaseFolder } = this.settings; try { const response = await requestUrl({ url: `${rootUrl}/api/v1/documents/folder/${remoteBaseFolder}`, method: 'GET', headers: { 'Accept': 'application/json', 'Authorization': `Bearer ${apiKey}` } }); if (response.status === 200) { const fileMap = new Map(); for (const doc of response.json.documents) { const key = this.getRemotePathKey(doc.title); fileMap.set(key, doc); } return fileMap; } // If the folder doesn't exist, the API returns a 404, which is expected. // Return an empty map in this case. return new Map(); } catch (e) { console.error('Error fetching remote file list:', e); return null; } } async getLocalFiles(syncedFolders: string[]): Promise> { const localFiles = new Map(); const allFiles = this.app.vault.getMarkdownFiles(); for (const file of allFiles) { const isInSyncedFolder = syncedFolders.some(folder => folder === '.' || file.path.startsWith(folder + '/') ); if (isInSyncedFolder) { const mangledName = this.getMangledFileName(file); const key = this.getRemotePathKey(mangledName); localFiles.set(key, { path: file.path, mtime: file.stat.mtime }); } } return localFiles; } compareFiles(localFiles: Map, remoteFiles: Map) { const toCreate = new Set(); const toUpdate = new Set(); for (const [key, file] of localFiles.entries()) { if (!remoteFiles.has(key)) { toCreate.add(key); } else { const remoteFile = remoteFiles.get(key); const remoteMtime = new Date(remoteFile.published).getTime(); if (file.mtime > remoteMtime) { toUpdate.add(key); } } } const [MASK] = new Set(localFiles.keys()); const toDelete = new Set(); for (const key of remoteFiles.keys()) { if (! [MASK] .has(key)) { toDelete.add(key); } } return { toCreate, toUpdate, toDelete }; } async ensureRemoteFolderExists(path: string): Promise { const { apiKey, rootUrl } = this.settings; // This is simplified now - it doesn't need to be recursive. try { const response = await fetch(`${rootUrl}/api/v1/document/create-folder`, { method: 'POST', body: JSON.stringify({ name: path }), headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` } }); if (!response.ok) { const data = await response.json(); if (data.error && !data.error.includes('already exists')) { console.error(`Failed to create folder ${path}:`, data.error); } } } catch (e: any) { // Error is likely ""already exists"", which is fine. } } onunload() { } async loadSettings() { this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); } async saveSettings() { await this.saveData(this.settings); this.applyAutoSyncSettings(); } applyAutoSyncSettings() { if (this.autoSyncIntervalId) { window.clearInterval(this.autoSyncIntervalId); this.autoSyncIntervalId = null; } if (this.settings.autoSync) { this.autoSyncIntervalId = this.registerInterval( window.setInterval(() => { this.notify('Auto-syncing files...'); this.syncFolders(); }, this.settings.autoSyncInterval * 60 * 1000) ); } } notify(message: string) { if (this.settings.showNotifications) { new Notice(message); } } } class AnythingObsidianSettingTab extends PluginSettingTab { plugin: AnythingObsidian; constructor(app: App, plugin: AnythingObsidian) { super(app, plugin); this.plugin = plugin; } display(): void { const {containerEl} = this; containerEl.empty(); containerEl.createEl('h2', { text: 'General' }); new Setting(containerEl) .setName('Show notifications') .setDesc('Enable or disable notifications for sync status and other operations.') .addToggle(toggle => toggle .setValue(this.plugin.settings.showNotifications) .onChange(async (value) => { this.plugin.settings.showNotifications = value; await this.plugin.saveSettings(); })); containerEl.createEl('h2', { text: 'Connection' }); new Setting(containerEl) .setName('Anything LLM API Key') .setDesc('Enter your Anything LLM API Key') .addText(text => text .setPlaceholder('Enter your API Key') .setValue(this.plugin.settings.apiKey) .onChange(async (value) => { this.plugin.settings.apiKey = value; await this.plugin.saveSettings(); })); new Setting(containerEl) .setName('Anything LLM Root URL') .setDesc('Enter your Anything LLM instance URL') .addText(text => text .setPlaceholder('http://localhost:3001') .setValue(this.plugin.settings.rootUrl) .onChange(async (value) => { if (value.endsWith('/')) { value = value.slice(0, -1); } this.plugin.settings.rootUrl = value; await this.plugin.saveSettings(); })); new Setting(containerEl) .setName('Test API Key') .setDesc('Click to test your API key and connection to Anything LLM.') .addButton(button => button .setButtonText('Test Connection') .onClick(async () => { if (!this.plugin.settings.apiKey || !this.plugin.settings.rootUrl) { this.plugin.notify('Please enter an API Key and Root URL first.'); return; } try { const response = await requestUrl({ url: `${this.plugin.settings.rootUrl}/api/v1/auth`, method: 'GET', headers: { 'Accept': 'application/json', 'Authorization': `Bearer ${this.plugin.settings.apiKey}` } }); if (response.status === 200 && response.json.authenticated) { this.plugin.notify('API Key is valid!'); } else { this.plugin.notify('API Key is invalid or connection failed.'); } } catch (e) { this.plugin.notify('Error connecting to Anything LLM. Check the Root URL and your network connection.'); console.error(e); } })); new Setting(containerEl) .setName('Discover Workspaces') .setDesc('Click to fetch available workspaces from your Anything LLM instance.') .addButton(button => button .setButtonText('Discover') .onClick(async () => { if (!this.plugin.settings.apiKey || !this.plugin.settings.rootUrl) { this.plugin.notify('Please enter an API Key and Root URL first.'); return; } try { const response = await requestUrl({ url: `${this.plugin.settings.rootUrl}/api/v1/workspaces`, method: 'GET', headers: { 'Accept': 'application/json', 'Authorization': `Bearer ${this.plugin.settings.apiKey}` } }); if (response.status === 200) { const data = response.json; const newWorkspaces = data.workspaces.map((ws: { name: string, slug: string }) => ({ name: ws.name, slug: ws.slug })); this.plugin.settings.workspaces = newWorkspaces; const newWorkspaceSlugs = new Set(newWorkspaces.map((ws: Workspace) => ws.slug)); this.plugin.settings.selectedWorkspaces = this.plugin.settings.selectedWorkspaces.filter(slug => newWorkspaceSlugs.has(slug)); await this.plugin.saveSettings(); this.plugin.notify(`${data.workspaces.length} workspaces found.`); this.display(); // Rerender } else { this.plugin.notify('Failed to fetch workspaces.'); } } catch (e) { this.plugin.notify('Error fetching workspaces.'); console.error(e); } })); if (this.plugin.settings.workspaces && this.plugin.settings.workspaces.length > 0) { containerEl.createEl('h2', { text: 'Send To' }); containerEl.createEl('p', { text: 'Select the workspaces to send files to.' }); this.plugin.settings.workspaces.forEach((ws: Workspace) => { new Setting(containerEl) .setName(ws.name) .addToggle(toggle => toggle .setValue(this.plugin.settings.selectedWorkspaces.includes(ws.slug)) .onChange(async (value) => { const { selectedWorkspaces } = this.plugin.settings; if (value) { if (!selectedWorkspaces.includes(ws.slug)) { selectedWorkspaces.push(ws.slug); } } else { const index = selectedWorkspaces.indexOf(ws.slug); if (index > -1) { selectedWorkspaces.splice(index, 1); } } this.plugin.settings.selectedWorkspaces = selectedWorkspaces; await this.plugin.saveSettings(); })); }); } containerEl.createEl('h2', { text: 'Folder Sync' }); new Setting(containerEl) .setName('Folders to Sync') .setDesc('Enter the paths of the folders you want to sync, one path per line, relative to your vault root. Use ""."" to sync the entire vault. For example: ""Inbox"" or ""Projects/Active"".') .addTextArea(text => text .setPlaceholder('.\nFolder1\nFolder2/Subfolder') .setValue(this.plugin.settings.syncedFolders.join('\n')) .onChange(async (value) => { this.plugin.settings.syncedFolders = value.split('\n').map(path => path.trim()).filter(path => path.length > 0); await this.plugin.saveSettings(); })); new Setting(containerEl) .setName('Permanently delete archived files') .setDesc('If enabled, the remote trash and archive folders will be cleared after sync. If disabled, old files will be kept.') .addToggle(toggle => toggle .setValue(this.plugin.settings.autoDelete) .onChange(async (value) => { this.plugin.settings.autoDelete = value; await this.plugin.saveSettings(); })); containerEl.createEl('h2', { text: 'Sync Behavior' }); new Setting(containerEl) .setName('Remote Base Folder') .setDesc('The root folder in Anything LLM to sync your vault to.') .addText(text => text .setPlaceholder('Obsidian Vault') .setValue(this.plugin.settings.remoteBaseFolder) .onChange(async (value) => { this.plugin.settings.remoteBaseFolder = value; await this.plugin.saveSettings(); })); new Setting(containerEl) .setName('When a synced file is updated...') .setDesc('How to handle the old version of a file in Anything LLM when it is updated in Obsidian.') .addDropdown(dropdown => dropdown .addOption('keep-in-workspace', 'Keep both versions in workspace') .addOption('archive', 'Replace version in workspace (archive old)') .addOption('delete', 'Replace completely (destructive)') .setValue(this.plugin.settings.updateHandling) .onChange(async (value: 'keep-in-workspace' | 'archive' | 'delete') => { this.plugin.settings.updateHandling = value; await this.plugin.saveSettings(); })); containerEl.createEl('h2', { text: 'Auto Sync' }); new Setting(containerEl) .setName('Enable Auto Sync') .setDesc('Automatically sync your specified folders in the background.') .addToggle(toggle => toggle .setValue(this.plugin.settings.autoSync) .onChange(async (value) => { this.plugin.settings.autoSync = value; await this.plugin.saveSettings(); this.display(); // Rerender to show/hide interval setting })); if (this.plugin.settings.autoSync) { new Setting(containerEl) .setName('Sync Interval (minutes)') .setDesc('How often to automatically sync your files.') .addText(text => text .setPlaceholder('5') .setValue(String(this.plugin.settings.autoSyncInterval)) .onChange(async (value) => { const interval = parseInt(value, 10); if (!isNaN(interval) && interval > 0) { this.plugin.settings.autoSyncInterval = interval; await this.plugin.saveSettings(); } })); } } } ",localKeys 221,"import TheaterModel from ""../models/theaters.model""; import { Request, Response } from ""express""; export const getTheaters = async (req: Request, res: Response) => { const page: number = Number(req.query.page); const moviesPerPage: number = Number(req.query.moviesPerPage) try { const theaters = await TheaterModel.find({}) .limit(moviesPerPage) .skip(moviesPerPage * page); res.status(200).json(theaters); } catch (error) { res.status(400).json({data: []}) } }; export const getTheaterById = async (req: Request, res: Response) => { try { const theaters = await TheaterModel.find({ theaterId: Number(req.params.id), }) res.status(200).json(theaters); } catch (error) { res.status(404).json({data: []}) } }; export const getSearchByStreet = async (req: Request, res: Response) => { const street: string = String(req.query.keyword) try{ const theaters = await TheaterModel.findOne({ ""location.address.street1"": street }) res.status(200).json(street); } catch(error) { res.status(404).json({data: []}) } } export const getSearchByCityName = async (req: Request, res: Response) => { const [MASK] : string = String(req.query.keyword) try{ res.status(200).json( [MASK] ); } catch(error) { res.status(404).json({data: []}) } } export const getSearchByZipcode = async (req: Request, res: Response) => { const Zipcode: string = String(req.query.keyword) try{ res.status(200).json(Zipcode); } catch(error) { res.status(404).json({data: []}) } } export const getSearchByState = async (req: Request, res: Response) => { const State: string = String(req.query.keyword) try{ res.status(200).json(State); } catch(error) { res.status(404).json({data: []}) } } ",Cityname 222,"import { Component, OnInit } from '@angular/core'; import { Location } from '@angular/common'; import { ScenarioDetailService } from '../scenario-detail/scenario-detail.service'; import { SettingsTable } from '../scenario-new/scenario-new'; import { ScenarioNewService } from '../scenario-new/scenario-new.service'; import { StartingValues } from '../scenario-detail/scenario-detail'; import { NavigationExtras, Router } from '@angular/router'; @Component({ selector: 'app-scenario-comparison', templateUrl: './scenario-comparison-inputs.component.html', styleUrls: ['./scenario-comparison-inputs.component.css'] }) export class ScenarioComparisonInputsComponent implements OnInit { baseScenarioID: number; scenariosIDsToCompare: number[]; settingTables: SettingsTable[]; baseScenarioValues: StartingValues; scenariosToCompareValues: StartingValues[]; constructor( private location: Location, private router: Router, private scenarioNewService: ScenarioNewService, private scenarioDetailService: ScenarioDetailService ) { const navigation = this.router.getCurrentNavigation(); const state = navigation.extras.state as { baseScenarioID: number, scenariosIDsToCompare: boolean }; } ngOnInit() { // Need to get the navigation extras from history (as the state is only // available during navigation); we'll use these to change the behavior // of the scenario name field this.baseScenarioID = history.state.baseScenarioID; this.scenariosIDsToCompare = history.state.scenariosIDsToCompare; this.settingTables = []; this.getSettingTables(); this.baseScenarioValues = {} as StartingValues; this.getBaseScenarioValues(this.baseScenarioID); this.scenariosToCompareValues = [] as StartingValues[]; this.getScenariosToCompareValues(this.scenariosIDsToCompare); } getSettingTables(): void { this.scenarioNewService.getScenarioNewAPI() .subscribe( scenarioNewAPI => { this.settingTables = scenarioNewAPI.SettingsTables; } ); } getBaseScenarioValues(scenarioID): void { this.scenarioDetailService.getScenarioDetailAPI(scenarioID) .subscribe( scenarioDetail => { this.baseScenarioValues = scenarioDetail.editScenarioValues; } ); } getScenariosToCompareValues( [MASK] ): void { for (const scenarioID of [MASK] ) { this.scenarioDetailService.getScenarioDetailAPI(scenarioID) .subscribe( scenarioDetail => { this.scenariosToCompareValues.push( scenarioDetail.editScenarioValues ); } ); } } viewDescriptions(tableNameInDB, rowNameInDB): void { const navigationExtras: NavigationExtras = { state: {type: 'subscenario', table: tableNameInDB, row: rowNameInDB} }; // Switch to the new scenario view, with 0 as argument (show all data) this.router.navigate(['/scenario-inputs', 0], navigationExtras); } viewInputs(tableNameInDB, rowNameInDB): void { const navigationExtras: NavigationExtras = { state: {type: 'input', table: tableNameInDB, row: rowNameInDB} }; // Switch to the new scenario view, with 0 as argument (show all data) this.router.navigate(['/scenario-inputs', 0], navigationExtras); } goBack(): void { const navigationExtras: NavigationExtras = { state: { startingValues: { baseScenarioStartingValue: this.baseScenarioID, scenariosToCompareStartingValues: this.scenariosIDsToCompare, showResultsButtonsStartingValue: false } } }; this.router.navigate(['scenario-comparison/select'], navigationExtras); } } ",scenarioIDsToCompare 223,"""use server"" import { sql, isUniqueViolation } from ""@/lib/db"" export async function requestEarlyAccess( [MASK] : FormData) { const email = [MASK] .get(""email"") as string if (!email) { return { success: false, message: ""Please provide your email address."", } } try { await sql` INSERT INTO early_access (email) VALUES (${email}) ` return { success: true, message: ""Thank you for your interest! We'll notify you when early access is available."", } } catch (error) { console.error(""Error requesting early access:"", error) if (isUniqueViolation(error)) { return { success: true, message: ""Thank you for your interest! We'll notify you when early access is available."", } } return { success: false, message: ""Something went wrong. Please try again later."", } } } ",formData 224,"import { ElevenLabsClient } from ""elevenlabs""; import * as admin from ""firebase-admin""; import { FieldValue } from ""firebase-admin/firestore""; import * as functions from ""firebase-functions""; import * as stream from ""stream""; import config from ""./config""; import { GenerateAudioRequest } from ""./types""; import { buildRequest, BuildRequestOptions, getFileExtension } from ""./util""; const logger = functions.logger; admin.initializeApp(); const elevenlabs = new ElevenLabsClient({ apiKey: config.elevenLabsApiKey, // Defaults to process.env.ELEVENLABS_API_KEY }); logger.log(""Initializing text-to-speech extension with config:"", config); export const elevenLabsTextToSpeech = functions.firestore .document(`${config.collectionPath}/{docId}`) .onWrite(async ( [MASK] ) => { const before = [MASK] ?.before?.data(); const after = [MASK] ?.after?.data(); const snap = [MASK] .after; if ( snap?.exists && snap?.data().text && (!before || [""text"", ""outputFormat"", ""modelId"", ""voice""].some((p) => before[p] !== after[p])) && // When updates are not enabled, only generate audio if there is no audioPath yet (config.enableUpdates || !after.audioPath) ) { const { text, outputFormat, modelId, voice } = snap.data() as BuildRequestOptions; const request = config.enablePerDocumentOverrides ? buildRequest({ text, outputFormat, modelId, voice, }) : buildRequest({ text }); const stream = await processText(request); if (stream) { const fileExtension = getFileExtension(request.output_format); const fileName = config.storagePath ? `${config.storagePath}/${snap.id}${fileExtension}` : `${snap.id}${fileExtension}`; const bucket = admin.storage().bucket(config.bucketName); const file = bucket.file(fileName); logger.log(""Uploading audio to storage with filename:"", fileName, { includeCustomMetadata: config.includeCustomMetadata, cacheControl: config.cacheControl, }); await new Promise((resolve, reject) => { stream .pipe( file.createWriteStream({ metadata: { // note that we nest ""metadata"" for our custom metadata ...(config.includeCustomMetadata ? { metadata: { description: ""Audio generated by ElevenLabs text-to-speech extension"", documentId: snap.id, documentPath: snap.ref.path, text: request.text, voice: request.voice, modelId: request.model_id, outputFormat: request.output_format, }, } : {}), ...(config.cacheControl ? { cacheControl: config.cacheControl, } : {}), }, }), ) .on(""error"", reject) .on(""finish"", resolve); }); logger.log(`Audio uploaded to gs://${config.bucketName}/${fileName}`, { metadata: file.metadata }); await snap.ref.update({ status: ""done"", audioPath: `gs://${config.bucketName}/${fileName}`, audioCreatedAt: FieldValue.serverTimestamp(), }); } else { logger.error(""No audio stream returned from ElevenLabs""); await snap.ref.update({ status: ""failed"", generatingAudioFailed: true, }); } } }); async function processText(request: GenerateAudioRequest) { let response: stream.Readable; // Performs the text-to-speech request try { logger.log(""Generating audio with request:"", request, { maxRetries: config.maxRetries }); response = await elevenlabs.generate(request, { maxRetries: config.maxRetries }); } catch (e) { logger.error(e); throw e; } return response; } ",change 225,"import { describe, expect, test } from ""vitest""; import { Result } from ""../src/index""; import type { ErrorResultType, SuccessResultType } from ""../src/index""; describe(""Result utility"", () => { describe(""Result.ok"", () => { test(""should create a success result with default type"", () => { const result = Result.ok({ value: 42 }); expect(result.type).toBe(""SUCCESS""); expect(result.data).toEqual({ value: 42 }); }); test(""should create a success result with custom type"", () => { const result = Result.ok(""USER_CREATED"", { id: 123, name: ""John"", }); expect(result.type).toBe(""SUCCESS_USER_CREATED""); expect(result.data).toEqual({ id: 123, name: ""John"" }); }); test(""should handle primitive data types"", () => { const stringResult = Result.ok(""hello world""); const numberResult = Result.ok(""COMPUTED"", 42); const booleanResult = Result.ok(true); expect(stringResult.type).toBe(""SUCCESS""); expect(stringResult.data).toBe(""hello world""); expect(numberResult.type).toBe(""SUCCESS_COMPUTED""); expect(numberResult.data).toBe(42); expect(booleanResult.type).toBe(""SUCCESS""); expect(booleanResult.data).toBe(true); }); }); describe(""Result.err"", () => { test(""should create an error result with default type"", () => { const result = Result.err({ message: ""Something went wrong"" }); expect(result.type).toBe(""ERROR""); expect(result.data).toEqual({ message: ""Something went wrong"" }); }); test(""should create an error result with custom type"", () => { const result = Result.err(""ERROR_VALIDATION"", { field: ""email"", message: ""Invalid format"", }); expect(result.type).toBe(""ERROR_ERROR_VALIDATION""); expect(result.data).toEqual({ field: ""email"", message: ""Invalid format"", }); }); test(""should handle Error objects"", () => { const error = new Error(""Network timeout""); const result = Result.err(""ERROR_NETWORK"", error); expect(result.type).toBe(""ERROR_ERROR_NETWORK""); expect(result.data).toBe(error); }); }); describe(""Type discrimination"", () => { test(""should allow type discrimination in conditional logic"", () => { const successResult: SuccessResultType<""PROCESSED"", { result: string }> = Result.ok(""PROCESSED"", { result: ""done"", }); const errorResult: ErrorResultType<""FAILED"", { error: string }> = Result.err(""FAILED"", { error: ""timeout"", }); // Test success case if (successResult.type === ""SUCCESS_PROCESSED"") { expect(successResult.data.result).toBe(""done""); // TypeScript should know this is { result: string } } else { expect.fail(""Should be SUCCESS_PROCESSED type""); } // Test error case if (errorResult.type === ""ERROR_FAILED"") { expect(errorResult.data.error).toBe(""timeout""); // TypeScript should know this is { error: string } } else { expect.fail(""Should be ERROR_FAILED type""); } }); }); describe(""Real-world usage patterns"", () => { function processUser(id: number) { if (id === 123) { return Result.ok(""USER_FOUND"", { name: """", email: """", }); } return Result.err(""USER_NOT_FOUND"", { id }); } test(""should work in realistic function scenarios"", () => { const foundUser = processUser(123); const notFoundUser = processUser(999); expect(foundUser.type).toBe(""SUCCESS_USER_FOUND""); if (foundUser.type === ""SUCCESS_USER_FOUND"") { expect(foundUser.data.name).toBe(""""); expect(foundUser.data.email).toBe(""""); } expect(notFoundUser.type).toBe(""ERROR_USER_NOT_FOUND""); if (notFoundUser.type === ""ERROR_USER_NOT_FOUND"") { expect(notFoundUser.data.id).toBe(999); } }); function parseNumber(input: string) { const num = Number(input); if (Number.isNaN(num)) { return Result.err(""PARSE_ERROR"", { input, reason: ""Not a valid number"", }); } return Result.ok(""PARSED"", num); } test(""should handle parsing scenarios"", () => { const validParse = parseNumber(""42""); const [MASK] = parseNumber(""not-a-number""); expect(validParse.type).toBe(""SUCCESS_PARSED""); if (validParse.type === ""SUCCESS_PARSED"") { expect(validParse.data).toBe(42); } expect( [MASK] .type).toBe(""ERROR_PARSE_ERROR""); if ( [MASK] .type === ""ERROR_PARSE_ERROR"") { expect( [MASK] .data.input).toBe(""not-a-number""); expect( [MASK] .data.reason).toBe(""Not a valid number""); } }); }); }); describe(""README Examples"", () => { describe(""Quick Start Examples"", () => { test(""should work with generic success/error (simple overload)"", () => { const success = Result.ok({ id: 123, name: ""Alice"" }); const error = Result.err({ message: ""Something went wrong"" }); expect(success.type).toBe(""SUCCESS""); expect(success.data).toEqual({ id: 123, name: ""Alice"" }); expect(error.type).toBe(""ERROR""); expect(error.data).toEqual({ message: ""Something went wrong"" }); }); test(""should work with custom tagged variants (descriptive overload)"", () => { const tagged = Result.ok(""USER_CREATED"", { id: 123, name: ""Alice"", }); const failure = Result.err(""VALIDATION_FAILED"", { field: ""email"" }); expect(tagged.type).toBe(""SUCCESS_USER_CREATED""); expect(tagged.data).toEqual({ id: 123, name: ""Alice"" }); expect(failure.type).toBe(""ERROR_VALIDATION_FAILED""); expect(failure.data).toEqual({ field: ""email"" }); // TypeScript narrows automatically if (tagged.type === ""SUCCESS_USER_CREATED"") { expect(tagged.data.name).toBe(""Alice""); // TypeScript knows this is string } }); }); describe(""API Reference Examples"", () => { test(""Result.ok with default and custom types"", () => { // Using default ""SUCCESS"" type const result1 = Result.ok({ value: 42 }); expect(result1.type).toBe(""SUCCESS""); expect(result1.data).toEqual({ value: 42 }); // Using custom type const result2 = Result.ok(""SUCCESS_DATA_LOADED"", { items: [] }); expect(result2.type).toBe(""SUCCESS_SUCCESS_DATA_LOADED""); expect(result2.data).toEqual({ items: [] }); }); test(""Result.err with default and custom types"", () => { // Using default ""ERROR"" type const result1 = Result.err({ message: ""Something went wrong"" }); expect(result1.type).toBe(""ERROR""); expect(result1.data).toEqual({ message: ""Something went wrong"" }); // Using custom type const result2 = Result.err(""ERROR_NOT_FOUND"", { resourceId: ""user-123"" }); expect(result2.type).toBe(""ERROR_ERROR_NOT_FOUND""); expect(result2.data).toEqual({ resourceId: ""user-123"" }); }); }); describe(""Synchronous Examples"", () => { // Let TypeScript infer the return type function parseNumber(input: string) { const num = Number.parseInt(input, 10); if (Number.isNaN(num)) { return Result.err(""INVALID_NUMBER"", { input }); } return Result.ok(""PARSED"", { value: num }); } interface UserData { id?: unknown; name?: string; } // Or force a specific return type function validateUser(data: UserData) { if (!data.id || typeof data.id !== ""number"") { return Result.err(""INVALID"", { error: ""ID must be a number"" }); } return Result.ok(""VALID"", { id: data.id }); } test(""parseNumber function from README"", () => { const validResult = parseNumber(""42""); const invalidResult = parseNumber(""abc""); expect(validResult.type).toBe(""SUCCESS_PARSED""); if (validResult.type === ""SUCCESS_PARSED"") { expect(validResult.data.value).toBe(42); } expect(invalidResult.type).toBe(""ERROR_INVALID_NUMBER""); if (invalidResult.type === ""ERROR_INVALID_NUMBER"") { expect(invalidResult.data.input).toBe(""abc""); } }); test(""validateUser function from README"", () => { const validData = { id: 123, name: ""Alice"" }; const invalidData = { name: ""Bob"" }; const validResult = validateUser(validData); const invalidResult = validateUser(invalidData); expect(validResult.type).toBe(""SUCCESS_VALID""); if (validResult.type === ""SUCCESS_VALID"") { expect(validResult.data.id).toBe(123); } expect(invalidResult.type).toBe(""ERROR_INVALID""); if (invalidResult.type === ""ERROR_INVALID"") { expect(invalidResult.data.error).toBe(""ID must be a number""); } }); }); describe(""Asynchronous Examples (Mocked)"", () => { interface MockResponse { ok: boolean; status: number; data?: unknown; } // Let TypeScript infer the return type async function fetchData(url: string, mockResponse: MockResponse) { try { // Simulate fetch behavior const response = mockResponse; if (!response.ok) { return Result.err(""HTTP_ERROR"", { status: response.status }); } const data = mockResponse.data || { id: 123, name: ""Test Data"" }; return Result.ok(data); } catch (error) { return Result.err(""NETWORK_ERROR"", { message: (error as Error).message, }); } } interface User { id: number; name: string; } interface GetUserMockResponse { status: number; data?: User; shouldThrow?: boolean; } // Or force a specific return type async function getUser(id: number, mockResponse: GetUserMockResponse) { try { if (mockResponse.shouldThrow) { throw new Error(""Network error""); } if (mockResponse.status === 404) { return Result.err(""NOT_FOUND"", { message: ""User not found"" }); } if (mockResponse.status !== 200) { return Result.err({ message: ""Failed to fetch user"" }); } const user = mockResponse.data || { id, name: """" }; return Result.ok(""USER_FOUND"", user); } catch (error) { return Result.err({ message: (error as Error).message }); } } test(""fetchData function from README"", async () => { // Test successful response const successResult = await fetchData(""http://example.com"", { ok: true, status: 200, data: { message: ""Success"" }, }); expect(successResult.type).toBe(""SUCCESS""); if (successResult.type === ""SUCCESS"") { expect(successResult.data).toEqual({ message: ""Success"" }); } // Test HTTP error const httpErrorResult = await fetchData(""http://example.com"", { ok: false, status: 500, }); expect(httpErrorResult.type).toBe(""ERROR_HTTP_ERROR""); if (httpErrorResult.type === ""ERROR_HTTP_ERROR"") { expect(httpErrorResult.data.status).toBe(500); } }); test(""getUser function from README"", async () => { // Test successful user fetch const userResult = await getUser(123, { status: 200, data: { id: 123, name: ""Alice"" }, }); expect(userResult.type).toBe(""SUCCESS_USER_FOUND""); if (userResult.type === ""SUCCESS_USER_FOUND"") { expect(userResult.data.name).toBe(""Alice""); } // Test user not found const notFoundResult = await getUser(999, { status: 404 }); expect(notFoundResult.type).toBe(""ERROR_NOT_FOUND""); if (notFoundResult.type === ""ERROR_NOT_FOUND"") { expect(notFoundResult.data.message).toBe(""User not found""); } // Test general error const errorResult = await getUser(123, { status: 500 }); expect(errorResult.type).toBe(""ERROR""); if (errorResult.type === ""ERROR"") { expect(errorResult.data.message).toBe(""Failed to fetch user""); } // Test network error const networkErrorResult = await getUser(123, { status: 200, shouldThrow: true, }); expect(networkErrorResult.type).toBe(""ERROR""); if (networkErrorResult.type === ""ERROR"") { expect(networkErrorResult.data.message).toBe(""Network error""); } }); test(""switch statement usage from README"", async () => { const userResult = await getUser(123, { status: 200, data: { id: 123, name: """" }, }); let result: User | string; switch (userResult.type) { case ""SUCCESS_USER_FOUND"": result = userResult.data; // TypeScript knows this is User break; case ""ERROR_NOT_FOUND"": case ""ERROR"": result = userResult.data.message; break; default: { // TypeScript will error if we miss a case const exhaustive: never = userResult; throw new Error(""Unhandled result type""); } } expect(result).toEqual({ id: 123, name: """" }); }); }); describe(""Best Practices Examples"", () => { test(""descriptive tags vs generic tags"", () => { // ❌ Not descriptive (but still works) const genericError = Result.err({ message: ""Failed"" }); expect(genericError.type).toBe(""ERROR""); // ✅ Descriptive and actionable const descriptiveError = Result.err(""VALIDATION_FAILED"", { field: ""email"", message: ""Invalid email format"", }); expect(descriptiveError.type).toBe(""ERROR_VALIDATION_FAILED""); expect(descriptiveError.data.field).toBe(""email""); }); test(""grouped related result types"", () => { interface User { id: number; name: string; } const createdResult = Result.ok(""USER_CREATED"", { id: 1, name: ""Alice"", }); const errorResult = Result.err(""VALIDATION_ERROR"", { message: ""Invalid data"", }); expect(createdResult.type).toBe(""SUCCESS_USER_CREATED""); expect(errorResult.type).toBe(""ERROR_VALIDATION_ERROR""); }); test(""exhaustive checking with switch statements"", () => { type UserOperationResult = | SuccessResultType< ""USER_CREATED"" | ""USER_UPDATED"", { id: number; name: string } > | ErrorResultType< ""USER_NOT_FOUND"" | ""VALIDATION_ERROR"" | ""PERMISSION_DENIED"", { message: string } >; function handleResult(result: UserOperationResult) { switch (result.type) { case ""SUCCESS_USER_CREATED"": case ""SUCCESS_USER_UPDATED"": return result.data; // TypeScript knows this is User case ""ERROR_USER_NOT_FOUND"": case ""ERROR_VALIDATION_ERROR"": case ""ERROR_PERMISSION_DENIED"": throw new Error(result.data.message); default: { // TypeScript will error if we miss a case const exhaustive: never = result; throw new Error(""Unhandled result type""); } } } const successResult: UserOperationResult = Result.ok(""USER_CREATED"", { id: 1, name: ""Alice"", }); const errorResult: UserOperationResult = Result.err(""VALIDATION_ERROR"", { message: ""Invalid email"", }); expect(handleResult(successResult)).toEqual({ id: 1, name: ""Alice"" }); expect(() => handleResult(errorResult)).toThrow(""Invalid email""); }); test(""chaining operations safely"", async () => { interface User { id: number; name: string; } interface UserData { id: number; name: string; email: string; } // Mock functions for the workflow async function fetchUser(userId: number) { if (userId === 999) { return Result.err(""API_ERROR"", { message: ""User not found"" }); } return Result.ok(""API_SUCCESS"", { data: { id: userId, name: """", email: ""invalid-email"" }, }); } function validateUser( userData: UserData, ): | SuccessResultType<""USER_VALID"", User> | ErrorResultType<""USER_INVALID"", { message: string }> { if (!userData.email || !userData.email.includes(""@"")) { return Result.err(""USER_INVALID"", { message: ""Invalid email"" }); } return Result.ok(""USER_VALID"", { id: userData.id, name: userData.name, }); } async function processUserWorkflow(userId: number) { const userResult = await fetchUser(userId); if (userResult.type !== ""SUCCESS_API_SUCCESS"") { return userResult; // Propagate error } const validationResult = validateUser(userResult.data.data); if (validationResult.type !== ""SUCCESS_USER_VALID"") { return validationResult; // Propagate validation error } // Continue with valid user... return Result.ok(""WORKFLOW_COMPLETE"", validationResult.data); } // Test successful workflow const successResult = await processUserWorkflow(123); // This will fail validation due to invalid email in mock data expect(successResult.type).toBe(""ERROR_USER_INVALID""); // Test API error propagation const errorResult = await processUserWorkflow(999); expect(errorResult.type).toBe(""ERROR_API_ERROR""); }); }); }); ",invalidParse 226,"import express from 'express'; import bcrypt from 'bcryptjs'; import jwt from 'jsonwebtoken'; import { OAuth2Client } from 'google-auth-library'; import { putItem, getItem, updateItem } from '../../packages/shared/src/dynamo'; import { policyMiddleware } from '../../packages/shared/src/policyMiddleware'; import { initSentry } from '../../packages/shared/src/sentry'; import { signMessage, verifyMessage } from '../../packages/shared/src/crypto'; export const app = express(); app.use(express.json()); app.use(policyMiddleware); const USER_TABLE = process.env.USER_TABLE || 'users'; const JWT_SECRET = process.env.JWT_SECRET || 'secret'; const QS_KEY = process.env.QS_KEY || 'quantum-secret'; const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID || ''; const googleClient = new OAuth2Client(GOOGLE_CLIENT_ID); interface User { email: string; passwordHash: string; verified?: boolean; resetToken?: string; } app.post('/signup', async (req, res) => { const { email, password } = req.body; if (!email || !password) return res.status(400).json({ error: 'missing fields' }); const passwordHash = await bcrypt.hash(password, 10); await putItem(USER_TABLE, { email, passwordHash, verified: false }); res.status(201).json({ ok: true }); }); app.post('/login', async (req, res) => { const { email, password } = req.body; if (!email || !password) return res.status(400).json({ error: 'missing fields' }); const user = await getItem(USER_TABLE, { email }); if (!user) return res.status(404).json({ error: 'user not found' }); const [MASK] = await bcrypt.compare(password, user.passwordHash); if (! [MASK] ) return res.status(401).json({ error: 'invalid credentials' }); const token = jwt.sign({ email }, JWT_SECRET, { expiresIn: '1h' }); const signature = signMessage(QS_KEY, token); res.json({ token, signature }); }); app.post('/google', async (req, res) => { const { idToken } = req.body; if (!idToken) return res.status(400).json({ error: 'missing token' }); try { const ticket = await googleClient.verifyIdToken({ idToken, audience: GOOGLE_CLIENT_ID, }); const payload = ticket.getPayload(); if (!payload || !payload.email) { return res.status(401).json({ error: 'invalid token' }); } const email = payload.email; let user = await getItem(USER_TABLE, { email }); if (!user) { await putItem(USER_TABLE, { email, passwordHash: await bcrypt.hash(idToken, 10), verified: true, }); } const token = jwt.sign({ email }, JWT_SECRET, { expiresIn: '1h' }); const signature = signMessage(QS_KEY, token); res.json({ token, signature }); } catch (err) { res.status(400).json({ error: 'invalid token' }); } }); app.post('/verify', async (req, res) => { const { email } = req.body; if (!email) return res.status(400).json({ error: 'missing email' }); await putItem(USER_TABLE, { email, verified: true }); res.json({ ok: true }); }); app.post('/requestPasswordReset', async (req, res) => { const { email } = req.body; if (!email) return res.status(400).json({ error: 'missing email' }); const token = jwt.sign({ email }, JWT_SECRET, { expiresIn: '15m' }); await updateItem(USER_TABLE, { email }, 'SET resetToken = :t', { ':t': token, }); // In a real system we'd email the token res.json({ ok: true, token }); }); app.post('/resetPassword', async (req, res) => { const { email, token, password } = req.body; if (!email || !token || !password) return res.status(400).json({ error: 'missing fields' }); const user = await getItem(USER_TABLE, { email }); if (!user || user.resetToken !== token) return res.status(400).json({ error: 'invalid token' }); const passwordHash = await bcrypt.hash(password, 10); await updateItem( USER_TABLE, { email }, 'SET passwordHash = :p REMOVE resetToken', { ':p': passwordHash } ); res.json({ ok: true }); }); app.post('/changeEmail', async (req, res) => { const { email, newEmail } = req.body; if (!email || !newEmail) return res.status(400).json({ error: 'missing fields' }); const user = await getItem(USER_TABLE, { email }); if (!user) return res.status(404).json({ error: 'user not found' }); await putItem(USER_TABLE, { ...user, email: newEmail }); res.json({ ok: true }); }); app.post('/verifySignature', (req, res) => { const { token, signature } = req.body; if (!token || !signature) return res.status(400).json({ error: 'missing fields' }); const valid = verifyMessage(QS_KEY, token, signature); res.json({ valid }); }); export function start(port = 3000) { initSentry('api-auth'); app.listen(port, () => console.log(`auth listening on ${port}`)); } if (require.main === module) { start(Number(process.env.PORT) || 3000); } ",match 227,"import { readFile } from ""node:fs/promises""; import type { PathLike } from ""node:fs""; // type Digit = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 0; // type Month = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12; // type Day = // | `${Month}` // | 13 // | 14 // | 15 // | 16 // | 17 // | 18 // | 19 // | 20 // | 21 // | 22 // | 23 // | 24 // | 25 // | 26 // | 27 // | 28 // | 29 // | 30 // | 31; // /** // * Represents a year. Since Node was started in the 21st century // * All years will begin with ""20"" until the next millennium. // * @todo This type will need to be updated hundreds of years from // * when this was written. (I doubt anyone will care about this by then.) // */ // type YearString = `20${Digit}${Digit}`; // /** // * A string representation of a date. Year-Month-Day // */ // type DateString = `${YearString}-${Month}-${Day}`; /** * As of the type of writing, all version numbers * are either integers or decimal values that are < 1 preceded * by a ""v"", with no ""build"" or ""revision"" values. */ type VersionName = `v${number}`; /** * Information about a single node version. */ export interface NodeVersionInfo { start: Date; lts?: Date; maintenance: Date; end: Date; codename?: string; } export type NodeVersionListing = Record; const defaultUrl = new URL( ""https://raw.githubusercontent.com/nodejs/Release/main/schedule.json"" ); function isUrl( urlOrFilePath: PathLike ): urlOrFilePath is URL | `http${""s"" | """"}://${string}` { return ( urlOrFilePath instanceof URL || (typeof urlOrFilePath === ""string"" && /https?:/i.test(urlOrFilePath)) ); } export async function getNodeVersionSchedule(urlOrFilePath: PathLike = defaultUrl) { let jsonString: string; if (isUrl(urlOrFilePath)) { const response = await fetch(urlOrFilePath); jsonString = await response.text(); } else { jsonString = await readFile(urlOrFilePath, { encoding: ""utf-8"", }); } function reviver(this: any, key: string, value: any) { if (/(start)|(lts)|(maintenance)|(end)/i.test(value)) { return new Date(value); } return value; } const [MASK] : NodeVersionListing = JSON.parse(jsonString, reviver); return [MASK] ; } ",vList 228,"// eslint-disable-next-line @typescript-eslint/triple-slash-reference /// import { getAuthToken, setAuthToken } from ""@poker/api-server""; import * as $ from ""jquery""; import * as ko from ""knockout""; import { appConfig } from ""poker/appconfig""; import { authManager } from ""poker/authmanager""; import { CommandManager } from ""poker/commandmanager""; import { AccountManager } from ""poker/services/accountManager""; import { TableView } from ""poker/table/tableview""; import ""signalr""; import * as signals from ""signals""; import { debugSettings } from ""./debugsettings""; import { _ } from ""./languagemanager""; import * as metadataManager from ""./metadatamanager""; import { PageBlock } from ""./pageblock""; import { CashierPageBlock, HomePage, InfoPageBlock, LobbyPageBlock, OtherPageBlock, SeatPage, TablesPage, } from ""./pages""; import ""./poker.commanding.api.ts""; import { AccountStatusPopup, AddMoneyPopup, AuthPopup, ChangePasswordPopup, ChatPopup, ContinueForgetPasswordPopup, CustomPopup, ForgetPasswordPopup, HandHistoryPopup, JoinTablePopup, MorePopup, NewsPopup, OkCancelPopup, RegistrationPopup, RulesPopup, SelectAvatarPopup, SettingsPopup, SlowConnectionPopup, SweepstakesRulesPopup, TableMenuPopup, } from ""./popups""; import { SimplePopup } from ""./popups/simplepopup""; import { Selector, SelectorItem } from ""./selector""; import { connectionService, deviceEvents, getSoundManager, imagePreloadService, keyboardActivationService, orientationService, pushService, reloadManager, slowInternetService, WebsiteService, } from ""./services""; import * as broadcastService from ""./services/broadcastservice""; import { uiManager, UIManager } from ""./services/uimanager""; import { settings } from ""./settings""; import { TabBar } from ""./tabbar""; import { AnimationSettings } from ""./table/animationsettings""; import * as runtimeSettings from ""./table/runtimesettings""; import { tableManager } from ""./table/tablemanager""; import * as timeService from ""./timeservice""; import { PopupBase } from ""./ui/popupbase""; type PromiseOrVoid = void | Promise; type ProviseOrVoidFactory = () => PromiseOrVoid; export interface LoginPromptResult { authenticated: boolean; wasAuthenticated: boolean; } declare const host: string; export class App { public currentPopup: string = null; public homePage: HomePage; public lobbyPageBlock: LobbyPageBlock; public cashierPageBlock: CashierPageBlock; public tablesPage: TablesPage; public seatsPage: SeatPage; public infoPageBlock: InfoPageBlock; public otherPageBlock: OtherPageBlock; public authPopup: AuthPopup; public forgetPasswordPopup: ForgetPasswordPopup; public continueForgetPasswordPopup: ContinueForgetPasswordPopup; public changePasswordPopup: ChangePasswordPopup; public registrationPopup: RegistrationPopup; public simplePopup: SimplePopup; public okcancelPopup: OkCancelPopup; public customPopup: CustomPopup; public joinTablePopup: JoinTablePopup; public tableMenuPopup: TableMenuPopup; public addMoneyPopup: AddMoneyPopup; public slowConnectionPopup: SlowConnectionPopup; public tableChatPopup: ChatPopup; public handHistoryPopup: HandHistoryPopup; public accountStatusPopup: AccountStatusPopup; public settingsPopup: SettingsPopup; public rulesPopup: RulesPopup; public sweepstakesRulesPopup: SweepstakesRulesPopup; public newsPopup = new NewsPopup(); public selectAvatarPopup = new SelectAvatarPopup(); public morePopup: MorePopup; public tabBar: TabBar; public mainSelector: Selector; public spinner: any; public progressSpinner: any; public processing: ko.Observable; public popupClosed: Signal; public loadPromises: JQueryPromise[]; public fullyInitialized: boolean; public disconnected: boolean; public suppressResume: boolean; private stopped = false; private savedPopup: string = null; private commandManager = new CommandManager(); constructor() { this.loadPromises = []; // register pages. this.homePage = new HomePage(); this.otherPageBlock = new OtherPageBlock(this.commandManager); this.infoPageBlock = new InfoPageBlock(); this.lobbyPageBlock = new LobbyPageBlock(); this.cashierPageBlock = new CashierPageBlock(); this.tablesPage = new TablesPage(this.commandManager); this.seatsPage = new SeatPage(this.commandManager); this.authPopup = new AuthPopup(); this.forgetPasswordPopup = new ForgetPasswordPopup(); this.continueForgetPasswordPopup = new ContinueForgetPasswordPopup(); this.changePasswordPopup = new ChangePasswordPopup(); this.registrationPopup = new RegistrationPopup(); this.simplePopup = new SimplePopup(); this.okcancelPopup = new OkCancelPopup(); this.customPopup = new CustomPopup(); this.joinTablePopup = new JoinTablePopup(); this.settingsPopup = new SettingsPopup(); this.rulesPopup = new RulesPopup(); this.sweepstakesRulesPopup = new SweepstakesRulesPopup(); this.tableMenuPopup = new TableMenuPopup(this.tablesPage, this.commandManager, new AccountManager(), authManager); this.addMoneyPopup = new AddMoneyPopup(); this.slowConnectionPopup = new SlowConnectionPopup(); this.tableChatPopup = new ChatPopup(); this.handHistoryPopup = new HandHistoryPopup(); this.accountStatusPopup = new AccountStatusPopup(); this.morePopup = new MorePopup(); this.processing = ko.observable(false); this.popupClosed = new signals.Signal(); this.registerCommands(); } public bindPages() { this.bindSubPage(""home"", this.homePage); this.bindSubPage(""tables"", this.tablesPage); this.bindSubPage(""seats"", this.seatsPage); this.bindPopup(""auth"", this.authPopup); this.bindPopup(""forgetPassword"", this.forgetPasswordPopup); this.bindPopup(""continueForgetPassword"", this.continueForgetPasswordPopup); this.bindPopup(""changePassword"", this.changePasswordPopup); this.bindPopup(""registration"", this.registrationPopup); this.bindPopup(""simple"", this.simplePopup); this.bindPopup(""okcancel"", this.okcancelPopup); this.bindPopup(""custom"", this.customPopup); this.bindPopup(""joinTable"", this.joinTablePopup); this.bindPopup(""settings"", this.settingsPopup); this.bindPopup(""rules"", this.rulesPopup); this.bindPopup(""sweepstakesRules"", this.sweepstakesRulesPopup); this.bindPopup(""tableMenu"", this.tableMenuPopup); this.bindPopup(""addMoney"", this.addMoneyPopup); this.bindPopup(""slowConnection"", this.slowConnectionPopup); this.bindPopup(""tableChat"", this.tableChatPopup); this.bindPopup(""handHistory"", this.handHistoryPopup); this.bindPopup(""accountStatus"", this.accountStatusPopup); this.bindPopup(""news"", this.newsPopup); this.bindPopup(""selectAvatar"", this.selectAvatarPopup); this.bindPageBlock(""lobby"", this.lobbyPageBlock); this.bindPageBlock(""other"", this.otherPageBlock); this.bindPageBlock(""cashier"", this.cashierPageBlock); this.bindPageBlock(""info"", this.infoPageBlock); this.bindUIElement("".more-block"", this.morePopup); this.mainSelector = new Selector(); if (typeof window !== ""undefined"") { const mainSelectorElement = $("".page.main .sub-page.selector"")[0]; if (mainSelectorElement) { ko.applyBindings(this.mainSelector, mainSelectorElement); } } this.initializeTabbar(); this.initializeConnection(); // var progressBackgroundElement = $("".progress-background"")[0]; // ko.applyBindings(this, progressBackgroundElement); if (typeof window !== ""undefined"") { this.processing.subscribe(function (newValue) { if (newValue) { $("".progress-background"").show(); } else { $("".progress-background"").hide(); } }); } // show startup page uiManager.showPage(""initialization""); if (typeof window !== ""undefined"") { const opts = { lines: 13, length: 4, width: 2, radius: 6, corners: 1, rotate: 0, direction: 1, color: ""#fff"", speed: 1, trail: 60, shadow: false, hwaccel: false, className: ""spinner"", zIndex: 2e9, top: ""auto"", left: ""auto"", }; this.spinner = new Spinner(opts); const target = document.getElementById(""spinner""); this.spinner.spin(target); const progressTarget = document.getElementById(""progress-spinner""); this.progressSpinner = new Spinner(opts).spin(progressTarget); } } // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // ""load"", ""deviceready"", ""offline"", and ""online"". public bindEvents() { deviceEvents.ready.add(this.onDeviceReady, this); deviceEvents.pause.add(this.onPause, this); deviceEvents.resume.add(this.onResume, this); deviceEvents.initialize(); deviceEvents.ready.addOnce(function() { console.log(""Device ready fired""); }); } // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicity call 'app.receivedEvent(...);' public onDeviceReady() { const device: Device = window.device; if (device != null && device.available) { if (device.platform.toLowerCase() === ""ios"") { if (device.version.toString().indexOf(""7.0"") === 0) { StatusBar.overlaysWebView(false); /* tslint:disable:no-string-literal */ ko.bindingHandlers[""image""].options.enabled = false; /* tslint:enable:no-string-literal */ runtimeSettings.setShowNewsAfterLogin(false); } } } if (platformInfo.hasMenu()) { app.setupMenu(); } // Recalculate width of the landscape mode. const currentWidth = $(""body"").width(); if (currentWidth === 1024) { platformInfo.isTablet = true; } pushService.register(); tableManager.maxTablesReached.add(function(continuation: () => void) { SimplePopup.display(_(""maxtables.caption""), _(""maxtables.maxtablesreached"")); }); tableManager.hasTurn.subscribe(function(value: boolean) { app.tabBar.notice(""tables"", value); }); app.popupClosed.add(function(popupName: string) { keyboardActivationService.forceHideKeyboard(); console.log(""Popup "" + popupName + "" closed""); }); app.receivedEvent(""deviceready""); } // Update DOM on a Received Event public async receivedEvent(id: string) { if (appConfig.timeSettings.updateTimeFromServer) { timeService.start(); } settings.soundEnabled.subscribe(function(value) { const soundManager = getSoundManager(); soundManager.enabled(value); }); settings.loadSettings(); settings.isGuest.subscribe(function(value) { if (authManager.authenticated() && !value) { app.lobbyPageBlock.lobbyPage.cashOptions.currency(1); app.lobbyPageBlock.lobbyPage.sngOptions.currency(1); app.lobbyPageBlock.lobbyPage.tournamentOptions.currency(1); } else { app.lobbyPageBlock.lobbyPage.cashOptions.currency(2); app.lobbyPageBlock.lobbyPage.sngOptions.currency(2); app.lobbyPageBlock.lobbyPage.tournamentOptions.currency(2); } }); authManager.registerAuthenticationChangedHandler(function (value) { if (value && !settings.isGuest()) { app.lobbyPageBlock.lobbyPage.cashOptions.currency(1); app.lobbyPageBlock.lobbyPage.sngOptions.currency(1); app.lobbyPageBlock.lobbyPage.tournamentOptions.currency(1); } else { app.lobbyPageBlock.lobbyPage.cashOptions.currency(2); app.lobbyPageBlock.lobbyPage.sngOptions.currency(2); app.lobbyPageBlock.lobbyPage.tournamentOptions.currency(2); } }); $.when(this.loadPromises).then(() => { keyboardActivationService.setup(); this.setupTouchActivation(); }); this.setInitializationState(); let startPage = ""main""; if (this.getParameterByName(""restore"") === ""true"") { const currentTime = new Date(); const timeDiff = currentTime.valueOf() - settings.lastTime(); if (timeDiff > 1000 * 60 * 20) { setAuthToken(null); startPage = ""main""; } else { setAuthToken(settings.authToken()); startPage = settings.lastPage(); } } this.logEvent(""Received Event: "" + id); if (window.innerWidth > 640) { PageBlock.useDoubleView = true; AnimationSettings.platform = ""tablet""; } this.setDesiredOrientation(); if (platformInfo.isTablet) { orientationService.suppressRotation(); } this.setupClosePopupOnClick(); metadataManager.setFailed(() => { slowInternetService.onConnectionSlow(); slowInternetService.onDisconnected(); this.metadataUpdateFailed(); }); metadataManager.setReady(() => { // Adjust height const toolpadHeight = platformInfo.hasTabBar() ? 49 : 15; const logoHeight = 102; let noLogoHeight = 57; const pageHeaderHeight = 58; if (platformInfo.hasTabBar()) { $("".page.main"").addClass(""has-toolbar""); } noLogoHeight = window.innerHeight - toolpadHeight - noLogoHeight - platformInfo.statusBarHeight(); $("".popup-container.scroll-container"").css(""max-height"", noLogoHeight); const device: Device = window.device; let tournamentLobbyAdjustment = 57; let lobbyAdjustment = 0; if (device != null && device.available) { if (device.platform.toLowerCase() === ""ios"") { tournamentLobbyAdjustment = 57; } else { tournamentLobbyAdjustment = 81; lobbyAdjustment = -30; if (platformInfo.hasMenu()) { app.setupMenu(); } } } if (startPage === ""main"") { uiManager.showPage(""main""); this.showPageBlock(""home""); this.showSubPage(""home""); } else { app.showSubPage(""tables""); this.loadTablesAndTournaments(true); } tableManager.tables.subscribe((newValue: TableView[]) => { this.updateTabbar(authManager.authenticated(), newValue); if (newValue && metadataManager.banners != null) { const filteredBanners = metadataManager.banners .filter((banner) => banner.Id > settings.lastBannerId()) .sort((a, b) => a.Id - b.Id); if (filteredBanners.length > 0) { const currentBanner = filteredBanners[0]; settings.lastBannerId(currentBanner.Id); settings.saveSettings(); if (runtimeSettings.showNewsAfterLogin) { app.newsPopup.setData(currentBanner); app.showPopup(""news""); } } } }); authManager.registerAuthenticationChangedHandler((newValue) => { this.updateTabbar(newValue, tableManager.tables()); // tslint:disable-next-line:no-console console.log(""Authentication changed.""); setTimeout(() => { this.terminateConnection(); this.loadTablesAndTournaments(newValue); }, 100); }); }); slowInternetService.initialize(); const hasInternet = slowInternetService.hasInternet(); // tslint:disable-next-line:no-console console.log(""Detecting internet status..."" + hasInternet ? ""connected"" : ""not connected""); if (hasInternet) { slowInternetService.setRetryHandler(null); this.updateMetadataOnLaunch(); this.hideSplash(); } else { slowInternetService.onOffline(); this.hideSplash(); slowInternetService.setRetryHandler(() => this.updateMetadataOnLaunch()); } } public setInitializationState() { const parentElement = document.getElementById(""deviceready""); if (parentElement) { const listeningElement = parentElement.querySelector("".listening""); const receivedElement = parentElement.querySelector("".received""); if (listeningElement) { listeningElement.setAttribute(""style"", ""display:none;""); } if (receivedElement) { receivedElement.setAttribute(""style"", ""display:block;""); } } } public buildStartConnection() { return connectionService.buildStartConnectionAsync(); } public showSubPage(pageName: string) { this.hideMoreBlock(); uiManager.showSubPage(pageName); } public showPageBlock(pageBlockName: string) { uiManager.showPageBlock(pageBlockName); } public showSelector(selectorCaption: string, options: SelectorItem[], success: (item: SelectorItem) => void) { const successCallback = (item: SelectorItem) => { $("".page .page-block."" + uiManager.currentPageBlock).css(""display"", ""block""); $("".page .sub-page."" + uiManager.currentPage).css(""display"", ""block""); $("".page .sub-page.selector"").css(""display"", ""none""); success(item); }; const cancelCallback = () => { $("".page .page-block."" + uiManager.currentPageBlock).css(""display"", ""block""); $("".page .sub-page."" + uiManager.currentPage).css(""display"", ""block""); $("".page .sub-page.selector"").css(""display"", ""none""); }; $("".page .page-block."" + uiManager.currentPageBlock).css(""display"", ""none""); $("".page .sub-page."" + uiManager.currentPage).css(""display"", ""none""); $("".page .sub-page.selector"").css(""display"", ""block""); this.mainSelector.setParams(selectorCaption, options, successCallback, cancelCallback); } public bindPageBlock(pageBlockName: string, viewModel: PageBlock) { this.commandManager.registerCommand(""pageblock."" + pageBlockName, async () => { const requireAuthentication = viewModel.requireAuthentication; if (!requireAuthentication) { if (!viewModel.requireGuestAuthentication) { this.showPageBlock(pageBlockName); } else { const value = await app.requireGuestAuthentication(); if (value.authenticated) { this.showPageBlock(pageBlockName); } } } else { const value = await app.requireAuthentication(); if (value.authenticated) { this.showPageBlock(pageBlockName); } } }); for (let i = 0; i < viewModel.loadPromises.length; i++) { const item = viewModel.loadPromises[i]; this.loadPromises.push(item); } } public bindSubPage(pageName: string, viewModel: any) { this.commandManager.registerCommand(""page."" + pageName, async () => { const requireAuthentication = viewModel.requireAuthentication || false; if (!requireAuthentication) { this.showSubPage(pageName); } else { const value = await app.requireAuthentication(); if (value.authenticated) { this.showSubPage(pageName); } } }); if (typeof window === ""undefined"") { return; } const pagejElement = $("".page .sub-page."" + pageName); if (pagejElement.length === 0) { console.error(""Could not bind sub page "" + pageName + "" since DOM element not found.""); return; } if (pagejElement.length > 1) { console.warn(""Page "" + pageName + "" has more then one element to bind.""); return; } const pageElement = pagejElement[0]; if (!pageElement.hasChildNodes()) { const templateSource: string = pagejElement.data(""template"") as any; const pageLoadPromise = $.get(templateSource, ""text/html"").then(function(data: string) { pagejElement.html(data); try { ko.applyBindings(viewModel, pageElement); } catch (e) { console.log(""Bind page "" + pageName + "" failed""); } }); this.loadPromises.push(pageLoadPromise); return; } ko.applyBindings(viewModel, pageElement); } public bindPopup(popup: string, viewModel: any): void { this.commandManager.registerCommand(""popup."" + popup, () => { this.showPopup(popup); }); if (typeof window === ""undefined"") { return; } const popupjElement = $("".popup."" + popup); if (popupjElement.length === 0) { console.error(""Could not bind popup "" + popup + "" since DOM element not found.""); return; } if (popupjElement.length > 1) { console.warn(""Popup "" + popup + "" has more then one element to bind.""); return; } const popupElement = popupjElement[0]; if (!popupElement.hasChildNodes()) { const templateSource: string = popupjElement.data(""template"") as any; $.get(templateSource, ""text/html"").then(function(data) { popupjElement.html(data); try { ko.applyBindings(viewModel, popupElement); } catch (e) { console.log(""Bind popup "" + popup + "" failed""); console.log(""Detailed exception: "", e); } }); return; } ko.applyBindings(viewModel, popupElement); } public bindUIElement(className: string, viewModel: any): void { if (typeof window === ""undefined"") { return; } const uiElement = $(className); if (uiElement.length === 0) { console.error(""Could not bind UI element with class "" + className + "" since DOM element not found.""); return; } if (uiElement.length > 1) { console.warn(""UI element with class "" + className + "" has more then one element.""); return; } const domElement = uiElement[0]; if (!domElement.hasChildNodes()) { const templateSource: string = uiElement.data(""template"") as any; $.get(templateSource, ""text/html"").then(function(data) { uiElement.html(data); try { ko.applyBindings(viewModel, domElement); } catch (e) { console.log(""Bind UI element "" + className + "" failed""); } }); return; } ko.applyBindings(viewModel, domElement); } public async showPopup(popupName: string, ...args: any[]) { if (!popupName) { console.error(""The empty popup passed""); throw new Error(""The empty popup passed""); } if (this.currentPopup != null) { this.hideMoreBlock(); this.closePopup(); } this.currentPopup = popupName; console.log(""Show popup "" + popupName); const result = new Promise((resolve) => { this.popupClosed.addOnce(function(name: string, dialogResults?: any) { if (popupName !== name) { console.warn(""Responding to popup "" + name + "" instead of "" + popupName); } const signalData = { name, result: dialogResults, }; resolve(signalData); }, this, 1); const popupObject = this[(this.currentPopup + ""Popup"") as keyof this] as PopupBase; if (popupObject != null) { popupObject.shown(args); } if (typeof window !== ""undefined"") { const popupContainer = $("".popup."" + popupName + "" .popup-container""); if (popupContainer.length > 0) { popupContainer[0].scrollTop = 0; } $("".popup."" + popupName).css(""display"", ""block""); $("".popup-background"").css(""display"", ""block""); } }); return result; } public closePopup(result?: any): void { if (this.currentPopup) { console.log(""Close popup "" + this.currentPopup); if (typeof window !== ""undefined"") { $("".popup."" + this.currentPopup + "" .popup-container"")[0].scrollTop = 0; $("".popup."" + this.currentPopup).css(""display"", ""none""); $("".popup-background"").css(""display"", ""none""); } const popupName = this.currentPopup; const popupObject = this[(this.currentPopup + ""Popup"") as keyof this] as PopupBase; /* tslint:disable:no-string-literal */ if (popupObject !== undefined && popupObject[""visible""] !== undefined) { popupObject.visible(false); } /* tslint:enable:no-string-literal */ this.currentPopup = null; this.popupClosed.dispatch(popupName, result); } } public executeCommand(commandName: string, parameters: any[]= []) { this.commandManager.executeCommand(commandName, parameters); } public reloadApplication() { /* tslint:disable:no-unused-expression no-string-literal */ window[""StatusBar""] && StatusBar.show(); /* tslint:enable:no-unused-expression no-string-literal */ window.location.reload(); } public shouldRotateToOrientation(interfaceOrientation: any) { /* tslint:disable-next-line:no-string-literal */ const worker: WorkerFunc | undefined = window[""ScreenOrientation""][""shouldRotateToOrientation""]; if (worker) { return worker(interfaceOrientation); } return false; } public requireAuthentication(): Promise { if (!authManager.authenticated()) { return new Promise((resolve, reject) => { // We don't authenticated, so display authentication popup. this.popupClosed.addOnce(function() { // Resolve with current authentication status, so // caller would know operation was successful or not. resolve({ authenticated: authManager.authenticated(), wasAuthenticated: false, }); }, this, undefined); this.showPopup(""auth""); }); } else { // We already authenticated, no need to show authentication popup. return Promise.resolve({ authenticated: true, wasAuthenticated: true, }); } } public async requireGuestAuthentication(): Promise { if (!authManager.authenticated()) { // We don't authenticated, so display authentication popup. const authenticate = await authManager.loginAsGuest(); if (authenticate !== ""Ok"") { await SimplePopup.display(_(""auth.guestPlay""), [_(`errors.${authenticate}`)]); } return { authenticated: authManager.authenticated(), wasAuthenticated: false, }; } else { // We already authenticated, no need to show authentication popup. return { authenticated: true, wasAuthenticated: true, }; } } public prompt(title: string, messages: string[], buttons: string[] | null = null) { if (buttons === null) { buttons = [_(""common.ok""), _(""common.cancel"")]; } this.showPopup(""okcancel""); const popupObject = this.okcancelPopup; const deferred = popupObject.deferred; popupObject.title(title); popupObject.messages(messages); popupObject.buttons(buttons); popupObject.customStyle(""""); return deferred; } public promptEx(title: string, messages: string[], buttons: string[], actions: ProviseOrVoidFactory[]) { this.showPopup(""custom""); const popupObject = this.customPopup; const deferred = popupObject.deferred; popupObject.title(title); popupObject.messages(messages); popupObject.buttons(buttons); popupObject.actions(actions); return deferred; } public promptAsync(title: string, messages: string[], buttons: string[] | null = null) { return new Promise((resolve, reject) => { this.prompt(title, messages, buttons).then(() => resolve(true), () => resolve(false)); }); } private initializeTabbar() { this.tabBar = new TabBar(); this.tabBar.addItem(""home"", _(""tabbar.home""), ""home"", function() { app.executeCommand(""page.home""); app.showPageBlock(""home""); }); this.tabBar.addItem(""lobby"", _(""tabbar.lobby""), ""lobby"", function() { app.lobbyPageBlock.showLobby(); }); this.tabBar.addItem(""tables"", _(""tabbar.tables""), ""tables"", function() { const currentTable = app.tablesPage.currentTable(); if (currentTable === null || currentTable.model === null) { console.warn(""No tables opened. Could not open tables page""); SimplePopup.display(_(""menu.tables""), _(""tablesList.noTablesSelected"")); return; } if (currentTable.tableId === 0) { return; } app.executeCommand(""app.selectTable"", [currentTable.model]); app.showSubPage(""tables""); }); this.tabBar.addItem(""cashier"", _(""tabbar.cashier""), ""cashier"", function() { app.executeCommand(""pageblock.cashier""); // app.executeCommand(""pageblock.other""); }); this.tabBar.addItem(""more"", _(""tabbar.more""), ""more"", function() { const currentTabBarItem = UIManager.getTabBarItemForPage(uiManager.currentPageBlock); const isMoreSelected = app.tabBar.isSelected(""more""); const isMoreOpened = $(""body"").hasClass(""more-opened""); if (isMoreOpened) { app.tabBar.select(""more"", false); app.tabBar.select(currentTabBarItem, true); $("".more-block"").hide(); $(""body"").removeClass(""more-opened""); } else { app.tabBar.select(currentTabBarItem, false); app.tabBar.select(""more"", true); app.morePopup.update(); $("".more-block"").show(); $(""body"").addClass(""more-opened""); } app.morePopup.visible(!app.morePopup.visible()); }); this.tabBar.enable(""tables"", false); if (typeof window !== ""undefined"") { const tabBarElement = $("".toolbar-container"")[0]; if (tabBarElement) { ko.applyBindings(this.tabBar, tabBarElement); } } uiManager.subPageHiding.add(function(blockHiding: string) { const name = UIManager.getTabBarItemForPage(blockHiding); app.tabBar.select(name, false); }); uiManager.subPageShowing.add(function(blockShowing: string) { const name = UIManager.getTabBarItemForPage(blockShowing); app.tabBar.select(name, true); }); uiManager.pageBlockHiding.add(function(blockHiding: string) { const name = UIManager.getTabBarItemForPage(blockHiding); app.tabBar.select(name, false); }); uiManager.pageBlockShowing.add(function(blockShowing: string) { const name = UIManager.getTabBarItemForPage(blockShowing); app.tabBar.select(name, true); }); uiManager.pageBlockHidden.add(function(pageBlock: string) { if (app.tabBar.isSelected(""more"")) { if (pageBlock !== ""more"" && !app.morePopup.visible()) { app.tabBar.select(""more"", false); } app.hideMoreBlock(); } }); } private onResign() { const self = app; self.logEvent(""Application resign active""); // Wrap code in the timeout to prevent application from freezing. self.terminateConnection(); } private onActive() { const self = app; self.logEvent(""Application active""); // Wrap code in the timeout to prevent application from freezing. self.establishConnection(); } private onPause() { const self = app; const device: Device = window.device; if (platformInfo.isTablet) { orientationService.enableRotation(); } if (platformInfo.reloadOnResume) { // Don't do anything if reloading on resume. if (uiManager.currentPage === ""tables"") { settings.lastPage(""tables""); } else { settings.lastPage(""main""); } settings.authToken(getAuthToken()); settings.lastTime(new Date().valueOf()); settings.saveSettings(); return; } if (self.suppressResume) { return; } if (debugSettings.application.deactivateOnPause) { uiManager.deactivateSubPage(uiManager.currentPage); } self.logEvent(""Pause application""); // Wrap code in the timeout to prevent application from freezing. timeService.setTimeout(function() { self.logEvent(""Pause application#2""); self.showSplash(); settings.saveSettings(); if (self.currentPopup === ""registration"") { self.savedPopup = self.currentPopup; } else { self.savedPopup = null; } self.closePopup(); timeService.printDebug(); }, 0); timeService.stop(); self.processing(false); self.spinner.stop(); self.terminateConnection(); } private onResume() { const self = app; const device: Device = window.device; if (platformInfo.reloadOnResume) { // Reload to the main page with special configuration parameter self.showSplash(); location.replace(location.protocol + ""//"" + location.host + location.pathname + ""?restore=true""); return; } if (self.suppressResume) { self.suppressResume = false; if (self.savedPopup) { self.showPopup(self.savedPopup, true); self.savedPopup = null; } return; } self.logEvent(""Resume application""); if (appConfig.timeSettings.updateTimeFromServer) { timeService.start(); } self.showSplash(); const target = document.getElementById(""spinner""); self.spinner.spin(target); let pageBeforeClosing = uiManager.effectivePageContainer; let pageBlockBeforeClosing = uiManager.currentPageBlock; let subPageBeforeClosing = uiManager.currentPage; if (pageBeforeClosing === ""initialization"" || pageBeforeClosing === null) { pageBeforeClosing = ""main""; pageBlockBeforeClosing = ""home""; subPageBeforeClosing = ""home""; } uiManager.showPage(""initialization""); settings.loadSettings(); self.setInitializationState(); orientationService.setLastOrientation(); if (platformInfo.isTablet) { orientationService.suppressRotation(); } if (slowInternetService.fatalError) { self.hideSplash(); slowInternetService.showDuplicatedConnectionPopup(); return; } if (slowInternetService.hasInternet()) { slowInternetService.closePopup(); self.updateMetadataOnResume(pageBeforeClosing, pageBlockBeforeClosing, subPageBeforeClosing); slowInternetService.setRetryHandler(null); self.hideSplash(); } else { slowInternetService.onOffline(); self.hideSplash(); slowInternetService.setRetryHandler(function() { self.updateMetadataOnResume(pageBeforeClosing, pageBlockBeforeClosing, subPageBeforeClosing); }); } } private registerCommands() { this.commandManager.registerCommand(""popup.auth.show"", () => { this.showPopup(""auth""); }); this.commandManager.registerCommand(""popup.auth.forgetPassword"", () => { this.showPopup(""forgetPassword""); }); this.commandManager.registerCommand(""popup.auth.registration"", () => { this.showPopup(""registration""); }); this.commandManager.registerCommand(""popup.auth.continueForgetPassword"", () => { this.showPopup(""continueForgetPassword""); }); this.commandManager.registerCommand(""popup.close"", () => { this.closePopup(); }); this.commandManager.registerCommand(""popup.cancel"", () => { this.closePopup(""cancel""); }); this.commandManager.registerCommand(""more.close"", () => { this.hideMoreBlock(); const currentTabBarItem = UIManager.getTabBarItemForPage(uiManager.currentPageBlock); app.tabBar.select(currentTabBarItem, true); }); this.commandManager.registerCommand(""legal.eula"", () => { app.closePopup(); app.executeCommand(""pageblock.info""); app.infoPageBlock.showLicenseAgreement(); }); this.commandManager.registerCommand(""logout"", () => { authManager.logout(); }); this.commandManager.registerCommand(""app.exit"", () => { authManager.logout(); this.reloadApplication(); }); } private async updateMetadataOnResume(lastPage: string, pageBlockBeforeClosing: string, subPageBeforeClosing: string) { if (debugSettings.initialization.stopOnResume) { return; } console.log(""Launch intialization of metadata on resume""); if (!this.fullyInitialized) { console.log(""Application was never initialized, performing full initialization.""); await this.updateMetadataOnLaunch(); return; } const failHandler = () => { console.log(""Failed updating metadata on resume, rescheduling attempt.""); slowInternetService.showReconnectFailedPopup(); slowInternetService.setRetryHandler(() => { this.updateMetadataOnResume(lastPage, pageBlockBeforeClosing, subPageBeforeClosing); }); }; if (!await this.versionCheck()) { return; } this.preloadTableImages(); try { await metadataManager.update(); tableManager.initialize(this.commandManager); try { await tableManager.getCurrentTablesAndTournaments(); this.spinner.stop(); const wrapper = await this.establishConnection(); if (wrapper.terminated) { return; } this.logEvent(""Showing last page""); if (lastPage != null) { if (!debugSettings.application.goToLobbyAfterPause) { uiManager.showPage(lastPage); } else { uiManager.showPage(""main""); if (lastPage === ""table"") { uiManager.showPageBlock(""lobby""); uiManager.showSubPage(""lobby""); } } } else { uiManager.showPage(""main""); } if (debugSettings.application.deactivateOnPause) { this.logEvent(""Activating subpage""); uiManager.activateSubPage(uiManager.currentPage); } if (this.savedPopup) { this.showPopup(this.savedPopup, true); this.savedPopup = null; } orientationService.setLastOrientation(); reloadManager.execute(); } catch (e) { failHandler(); } } catch (e) { failHandler(); } } private async updateMetadataOnLaunch() { if (debugSettings.initialization.stopOnLaunch) { return; } console.log(""Launch intialization of metadata first time""); const failHandler = (e: unknown) => { if (e) { console.error(e); } else { console.error(""Unknown error happens during updateMetadataOnLaunch. See log messages above to diagnose what happens.""); } console.log(""Failed updating metadata for first time, rescheduling attempt.""); slowInternetService.setRetryHandler(() => { this.updateMetadataOnLaunch(); }); }; if (!await this.versionCheck()) { return; } this.preloadTableImages(); try { await metadataManager.update(); this.spinner.stop(); tableManager.initialize(this.commandManager); try { await this.establishConnection(); await tableManager.getCurrentTablesAndTournaments(); this.fullyInitialized = true; metadataManager.setReady(null); } catch (e) { console.log(""Failed to initialize connection and get current tables and tournaments""); failHandler(e); } } catch (e) { console.log(""Failed to initialize tables.""); failHandler(e); } } private async versionCheck() { try { await metadataManager.versionCheck(); return true; } catch (e) { // Display dialog which prompts for the update. app.promptEx(_(""updater.title""), [_(""updater.line1"")], [_(""updater.button"")], [() => { const [MASK] = new WebsiteService(host); [MASK] .navigateUpdateApk(); }]); return false; } } private setupTouchActivation() { // This is a fix which updates binding for the knockout value binding. // This is nescessary since touchstart event start handling. $(""body"").on(""keyup"", ""input"", function(event) { $(this).trigger(""change""); }); $(""body"").on(""touchstart"", "".button, .actionable"", function(event) { $(this).addClass(""pressed""); }).on(""touchend"", "".button, .actionable"", function(event) { $(this).removeClass(""pressed""); }).on(""touchcancel"", "".button, .actionable"", function(event) { $(this).removeClass(""pressed""); }); } private setupMenu() { menu.initialize([ { id: 1, order: 1, name: _(""menu.home"") }, { id: 2, order: 1, name: _(""menu.lobby"") }, { id: 3, order: 1, name: _(""menu.tables"") }, { id: 4, order: 1, name: _(""menu.cashier"") }, { id: 5, order: 1, name: _(""menu.account"") }, { id: 6, order: 1, name: _(""menu.chat"") }, { id: 7, order: 1, name: _(""menu.rating"") }, { id: 8, order: 1, name: _(""menu.messages"") }, { id: 9, order: 1, name: _(""menu.information"") }, ]); menu.optionItemClick = function(itemId) { if (itemId === 1) { app.executeCommand(""page.home""); app.showPageBlock(""home""); } if (itemId === 2) { app.lobbyPageBlock.showLobby(); } if (itemId === 3) { app.executeCommand(""page.tables""); } if (itemId === 4) { app.executeCommand(""pageblock.cashier""); } if (itemId === 5) { app.executeCommand(""page.account""); } if (itemId === 6) { app.executeCommand(""page.chat""); } if (itemId === 7) { app.executeCommand(""page.rating""); } if (itemId === 8) { app.executeCommand(""page.messages""); } if (itemId === 9) { app.executeCommand(""page.information""); } console.log(itemId); }; } private async loadTablesAndTournaments(authenticated: boolean) { if (authenticated) { try { await tableManager.getCurrentTablesAndTournaments(); this.establishConnection(); } catch (e) { console.log(""Could not get current tables!""); slowInternetService.showReconnectFailedPopup(); } } else { tableManager.clear(); this.establishConnection(); } } private setFailedState() { const parentElement = document.getElementById(""deviceready""); if (parentElement) { const listeningElement = parentElement.querySelector("".listening""); const receivedElement = parentElement.querySelector("".received""); receivedElement.setAttribute(""style"", ""display:none;""); const failedElement = parentElement.querySelector("".failed""); failedElement.setAttribute(""style"", ""display:block;""); } } private metadataUpdateFailed() { this.setFailedState(); console.log(""Metadata retreiving failure""); } private setDesiredOrientation() { if (!PageBlock.useDoubleView) { orientationService.setOrientation(""portrait""); } else { orientationService.setOrientation(""landscape""); } } private initializeConnection() { // connectionService.initializeConnection(); connectionService.recoverableError.add(() => { this.establishConnection(); }); } private terminateConnection(forceDisconnect = false) { tableManager.stopConnectingToTables(); connectionService.terminateConnection(forceDisconnect); } private async establishConnection(maxAttempts = 3) { // This part should be moved up to the stack to remove dependency on other services // in the connection management. connectionService.initializeConnection(); const wrapper = await connectionService.establishConnectionAsync(maxAttempts); if (wrapper.terminated) { return wrapper; } this.logEvent(""Setting up connection dependent services.""); slowInternetService.manualDisconnect = false; tableManager.connectTables(); tableManager.connectTournaments(); try { this.logEvent(""Joining lobby chat.""); wrapper.joinChat(0); } catch (error) { console.log(error); throw new Error(""Could not join chat after establishingConnection""); } this.logEvent(""Listening lobby chat messages.""); wrapper.onMessage(function(messageId, tableId, type, sender, message) { if (tableId !== 0) { return; } if (type === ""B"") { broadcastService.displayMessage(message); } }); return wrapper; } private hideMoreBlock() { app.morePopup.visible(false); $("".more-block"").hide(); $(""body"").removeClass(""more-opened""); app.tabBar.select(""more"", false); } private updateTabbar(authenticated: boolean, tables: TableView[]) { if (authenticated) { const tablesEnabled = tables.length > 0; this.tabBar.enable(""tables"", tablesEnabled); } else { this.tabBar.enable(""tables"", false); } } private setupClosePopupOnClick() { $("".popup-background"").on(""tap"", () => { if (app.currentPopup !== ""slowConnection"") { app.closePopup(); } }); } private preloadTableImages() { // TODO: Use web-workers for the preloading. imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table2-empty"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table2-s1"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table2-s2"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table6-empty"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table6-s1"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table6-s2"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table6-s3"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table6-s4"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table6-s5"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table6-s6"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table10-empty"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table10-s1"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table10-s2"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table10-s3"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table10-s4"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table10-s5"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table10-s6"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table10-s7"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table10-s8"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table10-s9"").catch(() => {}); imagePreloadService.preloadResource(appConfig.ui.deploymentPath + ""img/lobby/table10-s10"").catch(() => {}); imagePreloadService.preloadDeviceSpecificResource(appConfig.ui.deploymentPath + ""img/images/tableImages/poker_table"").catch(() => {}); } private logEvent(message: string) { if (debugSettings.device.events) { console.log(message); } } private getParameterByName(name: string) { name = name.replace(/[\[]/, ""\\["").replace(/[\]]/, ""\\]""); const regex = new RegExp(""[\\?&]"" + name + ""=([^&#]*)""); const results = regex.exec(location.search); return results == null ? """" : decodeURIComponent(results[1].replace(/\+/g, "" "")); } private showSplash() { /* tslint:disable:no-unused-expression no-string-literal */ navigator[""splashscreen""] && navigator.splashscreen.show(); /* tslint:enable:no-unused-expression no-string-literal */ } private hideSplash() { /* tslint:disable:no-unused-expression no-string-literal */ navigator[""splashscreen""] && navigator.splashscreen.hide(); /* tslint:enable:no-unused-expression no-string-literal */ } } declare const app: App; ",websiteService 229,"import {PAGASADocument} from ""../scraper/PagasaScraper""; export function findCycloneNumber(name: string) : [number, number] { const [MASK] = name.toLowerCase(); for (const [year, set] of Object.entries(CycloneNames)) { for (let id = 0; id < set.length; id++) { const name = set[id]; if (name.toLowerCase() === [MASK] ) { return [+year, id + 1]; } } } return [+(new Date().getFullYear()), 0]; } export function buildCode(document: PAGASADocument, advisory = false): string { const [year, cycloneNumber] = findCycloneNumber(document.name); return `PAGASA_${ year.toString().substr(2) }-TC${ cycloneNumber < 10 ? `0${cycloneNumber}` : cycloneNumber }_${ document.name[0].toUpperCase() + document.name.substr(1).toLowerCase() }_TC${ advisory ? ""A"" : ""B"" }#${ document.count < 10 ? `0${document.count}` : document.count }${ document.final ? ""-FINAL"" : """" }`; } // noinspection SpellCheckingInspection export const CycloneNames = { 2024: [ ""Aghon"", ""Butchoy"", ""Carina"", ""Dindo"", ""Enteng"", ""Ferdie"", ""Gener"", ""Helen"", ""Igme"", ""Julian"", ""Kristine"", ""Leon"", ""Marce"", ""Nika"", ""Ofel"", ""Pepito"", ""Querubin"", ""Romina"", ""Siony"", ""Tonyo"", ""Upang"", ""Vicky"", ""Warren"", ""Yoyong"", ""Zosimo"", ""Alakdan"", ""Baldo"", ""Clara"", ""Dencio"", ""Estong"", ""Felipe"", ""Gomer"", ""Heling"", ""Ismael"", ""Julio"" ], 2025: [ ""Auring"", ""Bising"", ""Crising"", ""Dante"", ""Emong"", ""Fabian"", ""Gorio"", ""Huaning"", ""Isang"", ""Jacinto"", ""Kiko"", ""Lannie"", ""Mirasol"", ""Nando"", ""Opong"", ""Paolo"", ""Quedan"", ""Ramil"", ""Salome"", ""Tino"", ""Uwan"", ""Verbena"", ""Wilma"", ""Yasmin"", ""Zoraida"", ""Alamid"", ""Bruno"", ""Conching"", ""Dolor"", ""Ernie"", ""Florante"", ""Gerardo"", ""Hernan"", ""Isko"", ""Jerome"" ], 2026: [ ""Ada"", ""Basyang"", ""Caloy"", ""Domeng"", ""Ester"", ""Francisco"", ""Gardo"", ""Henry"", ""Inday"", ""Josie"", ""Kiyapo"", ""Luis"", ""Maymay"", ""Neneng"", ""Obet"", ""Pilandok"", ""Queenie"", ""Rosal"", ""Samuel"", ""Tomas"", ""Umberto"", ""Venus"", ""Waldo"", ""Yayang"", ""Zeny"", ""Agila"", ""Bagwis"", ""Chito"", ""Diego"", ""Elena"", ""Felino"", ""Gunding"", ""Harriet"", ""Indang"", ""Jessa"" ], 2027: [ ""Amang"", ""Betty"", ""Chedeng"", ""Dodong"", ""Emil"", ""Falcon"", ""Gavino"", ""Hanna"", ""Ineng"", ""Jenny"", ""Kabayan"", ""Liwayway"", ""Marilyn"", ""Nimfa"", ""Onyok"", ""Perla"", ""Quiel"", ""Ramon"", ""Sarah"", ""Tamaraw"", ""Ugong"", ""Viring"", ""Weng"", ""Yoyoy"", ""Zigzag"", ""Abe"", ""Berto"", ""Charo"", ""Dado"", ""Estoy"", ""Felion"", ""Gening"", ""Herman"", ""Irma"", ""Jaime"" ], }; ",toFind 230,"import { ChangeDetectorRef, Component, ElementRef, EventEmitter, forwardRef, Input, OnInit, Output, Renderer2, ViewChild } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; /** * Component that wraps the native HTML5 color picker for supported browsers */ @Component({ selector: 'wily-color-picker', templateUrl: './color-picker.component.html', styleUrls: ['./color-picker.component.css'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => ColorPickerComponent), multi: true } ] }) export class ColorPickerComponent implements ControlValueAccessor, OnInit { /** * Regex to match a hexadecimal string (000000) * @private */ private static readonly FULL_HEX_REGEX = new RegExp('^[0-9A-Fa-f]{6}$'); /** * Regex to match a short hexadecimal string (000) * @private */ private static readonly SHORT_HEX_REGEX = new RegExp('^[0-9A-Fa-f]{3}$'); /** * Regex to match a valid hex character (A-F, a-f, 0-9) * @private */ private static readonly HEX_CHARACTER_REGEX = new RegExp('^[0-9A-Fa-f]$'); /** * Navigation keys * @private */ private static readonly NAVIGATION_KEYS = [ 'Enter', 'Esc', 'Escape', 'Tab', 'Shift', 'ArrowLeft', 'ArrowUp', 'ArrowRight', 'ArrowDown', 'Backspace', 'Delete' ]; /** * Set the value of the color picker * @param value the value to set */ @Input() set value(value: string) { let hexString = value ?? ''; if (hexString) { ColorPickerComponent.FULL_HEX_REGEX.lastIndex = 0; ColorPickerComponent.SHORT_HEX_REGEX.lastIndex = 0; hexString = hexString.replace('#', '').toLowerCase(); if (ColorPickerComponent.SHORT_HEX_REGEX.test(hexString)) { hexString = ColorPickerComponent.expandShortHexString(hexString); } if (!ColorPickerComponent.FULL_HEX_REGEX.test(hexString)) { hexString = ''; } } this._value = hexString; if (this.colorInput) { this.colorInput.nativeElement.value = this._value; } } /** * Set disabled * @param disabled whether or not the control should be disabled */ @Input() set disabled(disabled: boolean) { this._disabled = disabled; } /** * Aria label input */ @Input() ariaLabel = 'Color picker'; /** * Class list to apply to the hex string input */ @Input() classList: string = null as any; /** * Event emitted on hex string input event. Emits the current value of the input */ @Output() // eslint-disable-next-line @angular-eslint/no-output-native input = new EventEmitter(); /** * Event emitted on color selection from color picker (color picker widget dismissed) * or valid hex string typed in input. Emits the current value of the input */ @Output() colorSelected = new EventEmitter(); /** * ViewChild of the color input element */ @ViewChild('colorInput') colorInput: ElementRef = null as any; /** * Whether or not to render the component */ render = false; /** * Whether or not the native HTML5 color picker is supported */ colorPickerSupported = false; /** * The value of the color picker */ _value = ''; /** * Whether or not the color picker is disabled * @private */ _disabled = false; /** * Expand a short hex string (#abc) into its full form (#aabbcc) * @param hexString the short hex string to expand * @private */ private static expandShortHexString(hexString: string): string { let fullHexString = ''; for (let i = 0; i <= 2; i++) { fullHexString += `${hexString[i]}${hexString[i]}`; } return fullHexString; } /** * Function to call on change */ onChange: (value: any) => void = () => {}; /** * Function to call on touch */ onTouched: () => any = () => {}; /** * Dependency injection site * @param renderer the Angular renderer * @param changeDetectorRef the Angular ChangeDetectorRef */ constructor(private renderer: Renderer2, private changeDetectorRef: ChangeDetectorRef) { } /** * Init component, check for color picker browser support */ ngOnInit(): void { this.colorPickerSupported = this.isColorPickerSupported(); this.render = true; } /** * Write value * @param value the value to write */ writeValue(value: string): void { this.value = value; this.changeDetectorRef.markForCheck(); } /** * Register on change function * @param fn the function to register */ registerOnChange(fn: any): void { this.onChange = fn; } /** * Register on touched function * @param fn the function to register */ registerOnTouched(fn: any): void { this.onTouched = fn; } /** * Set whether or not the control should be disabled * @param isDisabled disabled or not */ setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; this.changeDetectorRef.markForCheck(); } /** * Prevent illegal input * @param event the keydown KeyboardEvent */ handleKeyDown(event: KeyboardEvent): void { const { key } = event; const { selectionStart, selectionEnd, value } = event.target as HTMLInputElement; if (!ColorPickerComponent.NAVIGATION_KEYS.includes(key) && !event.ctrlKey) { ColorPickerComponent.HEX_CHARACTER_REGEX.lastIndex = 0; const preventDefault = !ColorPickerComponent.HEX_CHARACTER_REGEX.test(key) || (value.length >= 6 && (selectionStart === selectionEnd)); if (preventDefault) { event.preventDefault(); } } } /** * Update model * @param value the new value of the model * @param emitColorSelected whether or not emit the color selected event * @private */ updateModel(value: string, emitColorSelected = false): void { ColorPickerComponent.FULL_HEX_REGEX.lastIndex = 0; let [MASK] = value; if ( [MASK] ) { [MASK] = [MASK] .replace('#', ''); } if (!this._disabled && ColorPickerComponent.FULL_HEX_REGEX.test( [MASK] )) { const valueBeforeUpdate = this._value; this.value = [MASK] ; if (valueBeforeUpdate !== this._value) { this.onChange(`#${ [MASK] }`); if (emitColorSelected) { this.colorSelected.emit(`#${ [MASK] }`); } } } else if (!value) { this.value = null as any; this.onChange(null); } } /** * Null out value on blur if not valid hex string, otherwise update model * @param value the value to check */ handleBlur(value: string): void { ColorPickerComponent.SHORT_HEX_REGEX.lastIndex = 0; ColorPickerComponent.FULL_HEX_REGEX.lastIndex = 0; if (ColorPickerComponent.SHORT_HEX_REGEX.test(value)) { this.updateModel(ColorPickerComponent.expandShortHexString(value), true); } else if (ColorPickerComponent.FULL_HEX_REGEX.test(value)) { this.updateModel(value, true); } else { this.value = null as any; this.onChange(null); } } /** * Prevent pasting a non-hex string * @param event the paste ClipboardEvent */ handlePaste(event: ClipboardEvent): void { event.preventDefault(); if (!this._disabled) { let clipboardData: DataTransfer = null as any; if (event.clipboardData) { clipboardData = event.clipboardData; } else if ('clipboardData' in window) { clipboardData = (window as any).clipboardData.getData('text'); } if (clipboardData) { ColorPickerComponent.FULL_HEX_REGEX.lastIndex = 0; const pastedText = clipboardData.getData('text') .replace('#', ''); if (ColorPickerComponent.FULL_HEX_REGEX.test(pastedText)) { this.updateModel(pastedText); } } } } /** * Determine if the browser supports the HTML5 color picker * @private */ private isColorPickerSupported(): boolean { let colorPickerSupported = false; try { const inputElement: HTMLInputElement = this.renderer.createElement('input'); inputElement.type = 'color'; inputElement.value = '!'; colorPickerSupported = inputElement.type === 'color' && inputElement.value !== '!'; } catch (e) { } return colorPickerSupported; } } ",updateValue 231,"/// const CACHE_NAME = 'rural-societies-v1'; const OFFLINE_URL = '/offline.html'; self.addEventListener('install', (event: ExtendableEvent) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => { return cache.addAll([ OFFLINE_URL, '/', '/index.html', '/manifest.json', '/favicon.ico', ]); }) ); }); self.addEventListener('fetch', (event: FetchEvent) => { if (event.request.mode === 'navigate') { event.respondWith( fetch(event.request).catch(() => { return caches.match(OFFLINE_URL) || caches.match(event.request); }) ); return; } event.respondWith( caches.match(event.request).then((response) => { return ( response || fetch(event.request).then((response) => { if (!response || response.status !== 200 || response.type !== 'basic') { return response; } const responseToCache = response.clone(); caches.open(CACHE_NAME).then((cache) => { cache.put(event.request, responseToCache); }); return response; }) ); }) ); }); self.addEventListener('activate', (event: ExtendableEvent) => { event.waitUntil( caches.keys().then(( [MASK] ) => { return Promise.all( [MASK] .filter((cacheName) => cacheName !== CACHE_NAME) .map((cacheName) => caches.delete(cacheName)) ); }) ); });",cacheNames 232,"import {multiselection_style} from ""../utils/style_manager""; import {multiView, viewOption, viewOptionClicked} from ""../css/multiselection.css""; import {windowMain} from ""../css/index.css""; export class MultiSelectionComponent { private page : {[key:string] : { container: JQuery, clickable: Function, //返回值为Boolean,意味着是否可以执行切换操作 onclick:Function }} //页数Dictionary private menu : JQuery; //菜单栏 private root : JQuery private selected_element: JQuery; //选中的page对应的按钮 private selected_content : JQuery public constructor(views:{[key:string] : { container: JQuery, clickable: Function, onclick:Function }},css: {[key:string]:string}) { this.menu = $(`
`); //菜单栏实例化 this.page = views this.root = $(`
`) this.selected_element = $() this.selected_content = $(`
`) let first = true; for(let c in views) { let option = $(`
`) //选项按钮 option.on('click', async () => { if (await this.page[c].clickable()) { this.changePage(option, c) } }) if (first) { this.changePage(option, c) first = false } //确保是第一个元素 this.menu.append(option) } this.root.append(this.menu) this.root.append(this.selected_content) for(let i in css) { this.selected_content.css(i,css[i]) } } public addPage(key:string,page:JQuery,click: Function) { this.page[key].container = page this.page[key].clickable = click } /** * 将各个Components组装成一个完整的组件 */ public getPage() { return this.root } private changePage( [MASK] :JQuery,key:string) { let ori_c = this.selected_element.text() if(key==ori_c) return if(ori_c.length!= 0) { this.selected_element.removeClass(`${viewOptionClicked}`) this.selected_element.addClass(`${viewOption}`) this.page[ori_c].container = this.selected_content.children("":first-child"").clone(true,true) //保存更改后的element } [MASK] .addClass(`${viewOptionClicked}`) [MASK] .removeClass(`${viewOption}`) this.selected_content.empty() this.selected_content.append(this.page[key].container) //不重新赋值,不能让变量根指针改变 this.page[key].onclick() this.selected_element = [MASK] } }",menuElement 233,"import {Directive, EventEmitter, HostListener, Input, OnChanges, Output, SimpleChanges} from '@angular/core'; import {fromEvent, Observable, of} from 'rxjs'; import {map, switchMap} from 'rxjs/operators'; export interface ImageResizeInputOptions { maxWidth: number; maxHeight: number; quality: number; type: string; } export interface ImageResizeResult { data: string; blob: Blob; } @Directive({ selector: 'input[type=file][imageResizeInput]' }) export class ImageResizeInputDirective implements OnChanges { @Input('imageResizeInput') options: ImageResizeInputOptions; @Output('selected') selectedEmitter: EventEmitter; constructor() { this.selectedEmitter = new EventEmitter(); } ngOnChanges(changes: SimpleChanges): void { if (!this.options) { this.options = { maxWidth: 1024, maxHeight: 1024, quality: 0.9, type: 'image/jpeg' }; } } @HostListener('change', ['$event']) onFileChange(event): void { of(event.target.files[0]).pipe( switchMap((file: File) => this.fromFileToDataURL(file)), switchMap((dataURL: string) => this.fromDataURLToImageElement(dataURL)), switchMap((image: HTMLImageElement) => this.resizeImage(image)) ).subscribe( (result: ImageResizeResult) => this.selectedEmitter.emit(result) ); } private fromFileToDataURL(file: File): Observable { const reader = new FileReader(); const observer: Observable = fromEvent(reader, 'load') .pipe( map((result: any) => result.target.result) ); reader.readAsDataURL(file); return observer; } private fromDataURLToImageElement(dataURL: string): Observable { const image: HTMLImageElement = new Image(); const observer = fromEvent(image, 'load').pipe(map(() => image)); image.src = dataURL; return observer; } private resizeImage(image: HTMLImageElement): Observable { const canvas: HTMLCanvasElement = document.createElement('canvas'); let height = image.height; let width = image.width; if (width > this.options.maxWidth) { height = Math.round(height * this.options.maxWidth / width); width = this.options.maxWidth; } if (height > this.options.maxHeight) { width = Math.round(width * this.options.maxHeight / height); height = this.options.maxHeight; } canvas.width = width; canvas.height = height; const context: CanvasRenderingContext2D = canvas.getContext('2d'); context.drawImage(image, 0, 0, width, height); const dataURL: string = canvas.toDataURL(this.options.type, this.options.quality); console.log(`Converting image from ${image.width}x${image.height} size to ${width}x${height} (${dataURL.length}) size in ${this.options.type} format.`); return of({ data: dataURL, blob: this.fromDataURLToBlob(dataURL, this.options.type) }); } private fromDataURLToBlob(dataURL: string, [MASK] : string = this.options.type, sliceSize: number = 512): Blob { const byteCharacters = atob(dataURL.split(',')[1]); const byteArrays = []; for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) { const slice = byteCharacters.slice(offset, offset + sliceSize); const byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } byteArrays.push(new Uint8Array(byteNumbers)); } return new Blob(byteArrays, { type: [MASK] }); } /* private orientImageFromEXIFMetadata(image: HTMLImageElement): Observable { return Observable.create((observer: any) => { EXIF = EXIF || this.createDefaultEXIFObject(image); EXIF.getData(image, () => { const orientation = EXIF.getTag(image, 'Orientation'); const canvas: HTMLCanvasElement = document.createElement('canvas'); const context: CanvasRenderingContext2D = canvas.getContext('2d'); if (orientation !== 1) { let width: number = image.width; let height: number = image.height; let x = 0, y = 0, degree = 0; switch (orientation) { case 3: case 4: x = -image.width; y = -image.height; degree = 180; break; case 5: case 6: width = image.height; height = image.width; degree = 90; y = -image.height; break; case 7: case 8: width = image.height; height = image.width; degree = 270; x = -image.width; break; default: break; } canvas.width = width; canvas.height = height; // Flipping image if ([2, 4, 5, 7].indexOf(orientation) > -1) { context.translate(width, 0); context.scale(-1, 1); } context.rotate(degree * Math.PI / 180); context.drawImage(image, x, y); const rotatedImage: HTMLImageElement = document.createElement('img'); rotatedImage.width = width; rotatedImage.height = height; fromEvent(rotatedImage, 'load').subscribe(() => { observer.next(rotatedImage); observer.complete(); }); rotatedImage.src = canvas.toDataURL(this.options.type); } else { observer.next(image); observer.complete(); } }); }); } private createDefaultEXIFObject(image: HTMLImageElement) { const defaultEXIF: { getData: Function, getTag: Function } = { getData: (img, cb) => { cb.call(image); return true; }, getTag: (source: HTMLImageElement, tag: string) => false }; return defaultEXIF; } */ } ",contentType 234,"import { useState, useRef, useEffect, useCallback } from 'react'; import gsap from 'gsap'; import { ScrollTrigger } from 'gsap/ScrollTrigger'; import { ScrollToPlugin } from 'gsap/ScrollToPlugin'; gsap.registerPlugin(ScrollTrigger, ScrollToPlugin); interface HorizontalScrollOptions { itemSelector: string; } export const useHorizontalScroll = ({ itemSelector }: HorizontalScrollOptions) => { const sectionRef = useRef(null); const trackRef = useRef(null); const cardsRefObj = useRef<(HTMLElement | null)[]>([]); const [activeIndex, setActiveIndex] = useState(0); const activeIndexRef = useRef(activeIndex); const timelineRef = useRef(); const [isMobile, setIsMobile] = useState(false); useEffect(() => { activeIndexRef.current = activeIndex; }, [activeIndex]); useEffect(() => { const checkMobile = () => setIsMobile(window.innerWidth < 1024); checkMobile(); window.addEventListener('resize', checkMobile); return () => window.removeEventListener('resize', checkMobile); }, []); const updateActiveIndex = useCallback((index: number) => { setActiveIndex(index); }, []); useEffect(() => { const cards = gsap.utils.toArray(itemSelector, sectionRef.current ?? undefined); cardsRefObj.current = cards; const track = trackRef.current; const section = sectionRef.current; if (!track || !section || cards.length === 0) return; gsap.set(cards, { willChange: 'transform, opacity' }); const ctx = gsap.context(() => { const firstCard = cards[0]; const lastCard = cards[cards.length - 1]; if (!firstCard || !lastCard) return; const getStartX = () => window.innerWidth / 2 - (firstCard.offsetLeft + firstCard.offsetWidth / 2); const getEndX = () => window.innerWidth / 2 - (lastCard.offsetLeft + lastCard.offsetWidth / 2); const startX = getStartX(); const endX = getEndX(); const totalScrollDistance = Math.abs(endX - startX); gsap.set(track, { x: startX }); const timeline = gsap.timeline({ scrollTrigger: { trigger: section, pin: true, scrub: 1.2, start: 'center center', end: () => `+=${totalScrollDistance}`, invalidateOnRefresh: true, onUpdate: (self) => { const currentX = gsap.getProperty(track, 'x') as number; let closestIndex = -1; let minDistance = Infinity; const viewportCenter = window.innerWidth / 2; cards.forEach((card, index) => { if (card) { const cardCenter = card.offsetLeft + card.offsetWidth / 2 + currentX; const distance = Math.abs(cardCenter - viewportCenter); if (distance < minDistance) { minDistance = distance; closestIndex = index; } } }); if (closestIndex !== -1 && activeIndexRef.current !== closestIndex) { updateActiveIndex(closestIndex); } } } }); timelineRef.current = timeline; timeline.to(track, { x: endX, ease: 'none' }); }, section); return () => { gsap.set(cards, { willChange: 'auto' }); ctx.revert(); } }, [itemSelector, updateActiveIndex]); useEffect(() => { cardsRefObj.current.forEach((card, index) => { if (card) { const isActive = index === activeIndex; gsap.to(card, { scale: isActive ? 1 : 0.9, opacity: isActive ? 1 : 0.6, duration: 0.5, ease: 'power3.out' }); } }); }, [activeIndex]); const goToCard = (index: number) => { const scrollTrigger = timelineRef.current?.scrollTrigger; const track = trackRef.current; const cards = cardsRefObj.current; const firstCard = cards[0]; const lastCard = cards[cards.length-1]; const [MASK] = cards[index]; if (!scrollTrigger || !track || ! [MASK] || !firstCard || !lastCard) return; const startX = window.innerWidth / 2 - (firstCard.offsetLeft + firstCard.offsetWidth / 2); const endX = window.innerWidth / 2 - (lastCard.offsetLeft + lastCard.offsetWidth / 2); const targetX = window.innerWidth / 2 - ( [MASK] .offsetLeft + [MASK] .offsetWidth / 2); const clampedTargetX = gsap.utils.clamp(Math.min(startX, endX), Math.max(startX, endX), targetX); const progress = gsap.utils.mapRange(startX, endX, 0, 1, clampedTargetX); const y = scrollTrigger.start + progress * (scrollTrigger.end - scrollTrigger.start); gsap.to(window, { scrollTo: { y: y, autoKill: false }, duration: 1, ease: 'power2.inOut', }); }; return { sectionRef, trackRef, activeIndex, goToCard }; }; ",targetCard 235,"// SPDX-FileCopyrightText: 2022 Digital Dasein // SPDX-FileCopyrightText: 2022 <> // SPDX-FileCopyrightText: 2022 <> // // SPDX-License-Identifier: MIT import { html, css, LitElement } from 'lit'; import { property } from 'lit/decorators.js'; import { unsafeHTML } from 'lit/directives/unsafe-html.js'; /*---------------------------------------------------------------------*/ /* Config */ /*---------------------------------------------------------------------*/ const DEFAULT_ATTRIBUTES = { author: '', mainTitle: 'dummy-title', subTitle: '', date: '', url: '', imgSrc: '', imgUrl: '', organisation: '', organisationUrl: '', full: false, fullScaleFactor: 1, configPath: '', cursorTimeout: 3000, }; let CURSOR_TIMER: ReturnType; /*---------------------------------------------------------------------*/ /* Utils */ /*---------------------------------------------------------------------*/ function insertHtmlWrongElem(elem: HTMLElement) { return ` [WARNING] ${elem.nodeName} element is not allowed.

Only include section and dd-slide elements, or elements with .slide class inside a dd-slide-collection, otherwise, the slide will not be rendered properly
`; } async function getJsonConfig(url: string) { /* first check head to see if file exists (no need to fetch whole file if * when looping over multiple possible filepaths */ const _checkFileExists = async (urlCheck: string) => { const response = await fetch(urlCheck, { method: 'HEAD' }); if (response.status !== 404) { return true; } console.error(`JSON config does not exist at '${urlCheck}'`); return false; }; const bFile = await _checkFileExists(url); if (bFile) { try { const response = await fetch(url); const json = await response.json(); return json; } catch (err: any) { console.error(`Error while reading config file at ${url} \n\n ${err}`); } } return { error: 'Could not parse JSON config, see console for errors', }; } /*---------------------------------------------------------------------*/ /* Main */ /*---------------------------------------------------------------------*/ /** * Main class for HTML web component **`dd-slide-collection`** * * For **styling** this component, check out {@link DdSlideCollection.styles | * the styles section}. * * **Important note**: all lit-component properties (interpreted here as * `other properties`) that are documented here have a **corresponding * HTML attribute**. The _non-attribute_ properties are consired private, * and are ingored in the documentation. * * @example * A simple slide collection containing two slide elements, one `dd-component` * (`dd-slide`), and one native `section` with `class=""slide""`. This example * moreover illustrates a limited amount of collection config attributes. * * ```html * * [...] * * * *

My first slide

*
*
*

A section also works

*
*
* [...] * * ``` * * The caption in `list`-mode has a default style, however, you could simply * add a custom caption with the `caption` slot inside a slide collection (it * will overwrite the default): * * ```html * *
* This is a custom caption, which can hold any HTML * content you want *
*
*/ export class DdSlideCollection extends LitElement { /** * To style the `dd-slide-collection` component, use the following **CSS host * variables** (including their default values): * * |
CSS variable
|
Default
| Description | * |:-----------------------------------------------|:-----------------------------------------|:------------| * |**`--dd-color-prim`** |`None` | primary `dd-component` color, which propagates into nested `dd-elements` | * |**`--dd-color-prim-dark`** |`None` | *dark-theme* primary `dd-component` color, which propagates into nested `dd-elements` | * |**`--dd-color-sec`** |`None` | secundary `dd-component` color, which propagates into nested `dd-elements` | * |**`--dd-color-sec-dark`** |`None` | *dark-theme* secundary `dd-component` color, which propagates into nested `dd-elements` | * |**`--dd-color-list-bg`** |`None` | background color for `list`-mode | * |**`--dd-color-text`** |`None (default)` | main text color, which propagates into nested `dd-elements` | * |**`--dd-color-text-light`** |`None (default)` | *light* text color, which propagates into nested `dd-elements` | * |**`--dd-color-caption-bg`** |`var(--dd-color-prim-dark, rgba(65, 90, 72, 1))` | caption ackground color, falls back to `rgba(65, 90, 72, 1)` if not defined | * |**`--dd-color-caption-fg`** |`var(--dd-color-text-light, rgba(255,255,255,1)`)| caption foreground color | * |**`--dd-color-caption-link`**|`inherit` | caption link color (by default, inherit from caption fg color | * |**`--dd-slide-gap`** |`96px` | gap between slides in `list`-mode | * |**`--dd-slide-ratio`** |`calc(16/9)` | slide apsect ratio | * |**`--dd-slide-width`** |`1024px` | slide width (this, together with`--dd-slide-ratio` determines the slide height) | * |**`--dd-full-scale-factor`** |`1` | factor for presenting in full screen (e.g. 0.8 will render the `full` slide at 80% of the maximum screen size) | * |**`--dd-font`** |`24px/2 'Roboto', sans-serif`| font style | * |**`--dd-font-size`** |`24px` | font _size_ setter | * |**`--dd-caption-height`** |`250px` | height of the caption in `list`-mode | * |**`--dd-caption-font-size`** |`calc(2.2 * var(--dd-font-size);`| * font-size of caption| * |**`--dd-caption-img-height`**|`calc(0.5 * var(--dd-caption-height));`| * height of caption image (width/height ratio holds) | * |**`--dd-slide-nr-font-size`**|`16px` | slide number font-size | * |**`--dd-slide-nr-color`** |`var(--dd-color-text)` | slide number color | * |**`--dd-slide-nr-right`** |`13px` | slide number right | * |**`--dd-slide-nr-bottom`** |`0` | slide number bottom | * * The variables can be set anywhere in your HTML context (e.g. in `:root`, * up until the `dd-slide-collection` component itself). * */ static styles = css` :host { /* Ddpres fillers */ /* dd color pallette */ --slide-collect-color-prim: var(--dd-color-prim); --slide-collect-color-prim-dark: var(--dd-color-prim-dark); --slide-collect-color-sec: var(--dd-color-sec); --slide-collect-list-bg-color: var( --dd-color-list-bg, rgba(248, 237, 227, 0.5) ); --slide-collect-text-color: var(--dd-color-text, rgba(0, 0, 0, 0.9)); --slide-collect-text-color-light: var( --dd-color-text-light, rgba(255, 255, 255, 1) ); --dd-color-caption-link: inherit; --slide-collect-gap: var(--dd-slide-gap, 96px); --slide-collect-ratio: var(--dd-slide-ratio, calc(16 / 9)); --slide-collect-width: var(--dd-slide-width, 1024px); --slide-collect-height: var( --dd-slide-height, calc(var(--slide-collect-width) / var(--slide-collect-ratio)) ); --slide-collect-full-scale-factor: var(--dd-full-scale-factor, 1); --slide-collect-font: var(--dd-font, 24px/2 'Roboto', sans-serif); --slide-collect-font-size: var(--dd-font-size, 24px); --caption-height: var(--dd-caption-height, 250px); --caption-center-width: 60%; --caption-font-size: var( --dd-caption-font-size, calc(2.2 * var(--slide-collect-font-size)) ); --caption-padding-left: 30px; --caption-padding-top: 30px; --caption-padding-right: 30px; --caption-padding-bottom: 30px; --caption-img-height: var( --dd-caption-img-height, calc(0.5 * var(--caption-height)) ); --caption-fg-color: var( --dd-color-caption-fg, var(--slide-collect-text-color-light) ); --dd-color-caption-bg: var(--dd-color-prim-dark, rgba(65, 90, 72, 1)); --caption-bg-color: var(--dd-color-caption-bg); --slide-collect-slide-nr-font-size: var(--dd-slide-nr-font-size, 16px); --slide-collect-slide-nr-right: var(--dd-slide-nr-right, 13px); --dd-slide-nr-bottom: 0em; --slide-collect-slide-nr-bottom: var(--dd-slide-nr-bottom, 0.2em); --slide-collect-slide-nr-color: var( --dd-slide-nr-color, var(--slide-collect-text-color) ); --slide-scale: 1; margin: 0; padding: 0; color: black; counter-reset: slide; font: var(--slide-collect-font); font-size: var(--slide-collect-font-size); } /* Full */ :host(.full) { display: block; } /* Hover */ :host(.list) > ::slotted(.slide:hover), :host(.list) > ::slotted(section:hover) { box-shadow: 0 0 0 20px var(--slide-collect-color-prim, rgba(65, 90, 72, 0.5)); } :host > ::slotted(section), :host > ::slotted(.slide) { position: relative; z-index: 0; overflow: hidden; box-sizing: border-box; width: var(--slide-collect-width); max-width: 100%; height: var(--slide-collect-height); background-color: white; margin: 0 auto; /*margin-bottom: var(--slide-collect-gap)*/ } :host(.full) > ::slotted(section), :host(.full) > ::slotted(.slide) { position: absolute; transform-origin: 0 0; transform: scale(var(--slide-collect-full-scale-factor)); border: 1px solid black; } /* Number */ :host > ::slotted(section)::after, :host > ::slotted(.slide)::after { position: absolute; font-size: var(--slide-collect-slide-nr-font-size); right: var(--slide-collect-slide-nr-right); bottom: calc(var(--slide-collect-slide-nr-bottom)); left: 0px; color: var(--slide-collect-slide-nr-color); text-align: right; counter-increment: slide; content: counter(slide); z-index: 999; } :host > ::slotted(.slide.titlepage)::after, :host > ::slotted(dd-titlepage)::after { counter-increment: slide; content: ''; } /* List */ :host(.list) ::slotted(.slide), :host(.list) ::slotted(section) { position: relative; box-shadow: calc(var(--slide-scale) * 4px) calc(var(--slide-scale) * 4px) 0 calc(var(--slide-scale) * 4px) var(--slide-collect-color-prim-dark, rgba(0, 0, 0, 0.8)); transform-origin: 0 0; transform: scale(var(--slide-scale)); display: block; min-width: var(--slide-collect-width); } :host(.list) > ::slotted(section.slide *), :host(.list) > ::slotted(dd-slide *) { pointer-events: none; } :host(.list) { padding: calc(var(--slide-collect-gap) * var(--slide-scale)); box-sizing: border-box; width: 100%; display: grid; grid-gap: calc(var(--slide-collect-gap) * var(--slide-scale)); grid-auto-rows: calc(var(--slide-collect-height) * var(--slide-scale)); grid-template-rows: min-content; grid-template-columns: repeat( auto-fill, calc(var(--slide-collect-width) * var(--slide-scale)) ); background-color: var(--slide-collect-list-bg-color); /*overflow-x: hidden;*/ } :host(.list) .dd-caption, :host(.list) .dd-caption-custom { grid-column: 1 / -1; margin-top: calc(-1 * var(--slide-collect-gap) * var(--slide-scale)); margin-left: calc(-1 * var(--slide-collect-gap) * var(--slide-scale)); box-sizing: border-box; width: 100vw; } /* IE & Edge Fix */ :host(.list):not(.dd-caption):not(.dd-caption-custom) { position: absolute; clip: rect(0, auto, auto, 0); } /* Responsive */ :host(.list) { --slide-scale: 0.25; } @media (min-width: 1168px) { :host(.list) { --slide-scale: 0.5; } } @media (min-width: 2336px) { :host(.list) { --slide-scale: 1; } } @media (max-width: 1168px) { :host { --caption-font-size: calc(1.3 * var(--slide-collect-font-size)); } } @media (max-width: 700px) { :host { --caption-font-size: calc(1.1 * var(--slide-collect-font-size)); } } /* Caption */ .dd-caption { width: 100%; position: relative; display: flex; flex-direction: row; z-index: 1; color: var(--caption-fg-color); background-color: var(--caption-bg-color); height: var(--caption-height); } .dd-caption a { color: var(--dd-color-caption-link); } .dd-caption-item { font-size: var(--caption-font-size); } .dd-caption-left { flex-grow: 1; text-align: left; align-self: center; padding: var(--caption-padding-top) 0 var(--caption-padding-bottom) var(--caption-padding-left); } .dd-caption-center { flex-grow: 6; text-align: left; max-width: var(--caption-center-width); padding: var(--caption-padding-top) var(--caption-padding-right) var(--caption-padding-bottom) var(--caption-padding-left); } .dd-caption-title { padding-top: 20px; line-height: 1em; font-size: var(--caption-font-size); font-weight: 300; } .dd-caption-subtitle { padding-top: 20px; line-height: 1em; font-size: calc(0.55 * var(--caption-font-size)); color: var(--caption-color-subtitle, rgba(255, 255, 255, 0.7)); } .dd-caption-right { flex-grow: 1; text-align: right; font-size: calc(0.35 * var(--caption-font-size)); align-self: flex-end; padding: var(--caption-padding-top) var(--caption-padding-right) var(--caption-padding-bottom) 0; } img.caption-img { height: var(--caption-img-height); display: block; } .dd-slide-collect-org-url { color: var(--slide-collect-text-color-light); } /* do not show custom caption slot */ .dd-caption-custom { width: 100%; z-index: 1; } /* Print */ @media print { .dd-caption { display: none !important; } :host(.full) { display: inline; } :host(.full) ::slotted(section), :host(.full) ::slotted(.slide) { position: relative; margin-left: 0 !important; margin-top: 0 !important; margin-bottom: 0 !important; transform: none; } } `; /** * Main presentation title * * **Corresponding attribute:** `main-title` * * **Default value:** `""""` (empty string) */ @property({ type: String, attribute: 'main-title' }) mainTitle = DEFAULT_ATTRIBUTES.mainTitle; /** * Presentation subtitle * * **Corresponding attribute:** `sub-title` * * **Default value:** `""""` (empty string) */ @property({ type: String, attribute: 'sub-title' }) subTitle = DEFAULT_ATTRIBUTES.subTitle; /** * Presentation author * * **Corresponding attribute:** `author` * * **Default value:** `""""` (empty string) */ @property({ type: String, attribute: 'author' }) author = DEFAULT_ATTRIBUTES.author; /** * Presentation date * * **Corresponding attribute:** `date` * * **Default value:** `""""` (empty string) */ @property({ type: String, attribute: 'date' }) date = DEFAULT_ATTRIBUTES.date; /** * Url (hyperlink) to _show_ inside the caption * * **Corresponding attribute:** `url` * * **Default value:** `""""` (empty string) */ @property({ type: String, attribute: 'url' }) url = DEFAULT_ATTRIBUTES.url; /** * Hyperlink behind caption image (e.g. logo) * * **Corresponding attribute:** `img-url` * * **Default value:** `""""` (empty string) */ @property({ type: String, attribute: 'img-url' }) imgUrl = DEFAULT_ATTRIBUTES.imgUrl; /** * Image source for caption image (e.g. logo) * * **Corresponding attribute:** `img-src` * * **Default value:** `""""` (empty string) */ @property({ type: String, attribute: 'img-src' }) imgSrc = DEFAULT_ATTRIBUTES.imgSrc; /** * Name of organisation * * **Corresponding attribute:** `organisation` * * **Default value:** `""""` (empty string) */ @property({ type: String, attribute: 'organisation' }) organisation = DEFAULT_ATTRIBUTES.organisation; /** * Hyperlink to organisation * * **Corresponding attribute:** `organisation-url` * * **Default value:** `""""` (empty string) */ @property({ type: String, attribute: 'organisation-url' }) organisationUrl = DEFAULT_ATTRIBUTES.organisationUrl; /** * Path to JSON config file (corresponding inline attributes will * **overwrite** attributes defined in JSON config * * **Corresponding attribute:** `config-path` * * **Default value:** `""""` (empty string) */ @property({ type: String, attribute: 'config-path' }) jsonConfig = DEFAULT_ATTRIBUTES.configPath; /** * Timout (in ms) for the cursor to auto-hide * * **Corresponding attribute:** `cursor-timeout` * * **Default value:** `3000` (milliseconds) */ @property({ type: Number, attribute: 'cursor-timeout' }) cursorTimeout = DEFAULT_ATTRIBUTES.cursorTimeout; /** @ignore */ @property({ type: Boolean, attribute: 'full' }) full = DEFAULT_ATTRIBUTES.full; /** * Factor for presenting in full screen mode (e.g. 0.8 will render the `full` * slide at 80% of the maximum screen size) * * **Corresponding attribute:** `full-scale-factor` * * **Default value:** `1` */ @property({ type: Number, attribute: 'full-scale-factor' }) fullScaleFactor = DEFAULT_ATTRIBUTES.fullScaleFactor; /** @ignore */ @property({ type: Boolean, attribute: false }) goToPrint = false; constructor() { super(); this.addEventListener('mousemove', () => { if (this.cursorTimeout !== 0) { this.style.cursor = 'default'; if (CURSOR_TIMER) clearTimeout(CURSOR_TIMER); CURSOR_TIMER = setTimeout(() => { this.style.cursor = 'none'; }, this.cursorTimeout); } }); } async setPropsFromJson() { const jsonObj = await getJsonConfig(this.jsonConfig); if (jsonObj.error) this.mainTitle = `[ERROR]${jsonObj.error} `; else { if (jsonObj.title) this.mainTitle = jsonObj.title; if (jsonObj.mainTitle) this.mainTitle = jsonObj.mainTitle; if (jsonObj.subTitle) this.subTitle = jsonObj.subTitle; if (jsonObj.author && this.author === DEFAULT_ATTRIBUTES.author) this.author = jsonObj.author; if (jsonObj.date) this.date = jsonObj.date; if (jsonObj.url) this.url = jsonObj.url; if (jsonObj.imgUrl) this.imgUrl = jsonObj.imgUrl; if (jsonObj.imgSrc) this.imgSrc = jsonObj.imgSrc; if (jsonObj.organisation) this.organisation = jsonObj.organisation; if (jsonObj.organisationUrl) this.organisationUrl = jsonObj.organisationUrl; } } makeCaptionHeader(customHtml = '') { let ddImgElem = ''; if (this.imgSrc) ddImgElem = ` `; let [MASK] = `${this.organisation}`; if (this.organisationUrl) [MASK] = `${this.organisation}`; let captionUrlEl = ''; if (this.url) captionUrlEl = ` ${this.url} `; if (customHtml) return `
${customHtml}
`; return `
${ddImgElem}
${this.mainTitle}
${this.subTitle}
${this.date}
${this.author}
${ [MASK] }
${captionUrlEl}
`; } /* c8 ignore next 75 */ private _updateView = (toggleView = false) => { if (this.goToPrint) return; if (toggleView) this.full = !this.full; // caption const captionElem = this.shadowRoot!.querySelector('.dd-caption'); if (captionElem) if (this.full) (captionElem as HTMLElement).style.display = 'none'; else (captionElem as HTMLElement).style.display = 'flex'; // external engine const externalEngine = document.querySelector('.shower'); if (externalEngine) { if (this.full) this.classList.remove('list'); else this.classList.add('list'); return; } // switch between full and list if (this.full) { this.classList.add('full'); this.classList.remove('list'); const { innerWidth, innerHeight } = window; // any slide const slide = document.querySelector('.slide'); if (slide) { const { offsetWidth, offsetHeight } = slide as HTMLElement; const scale = (1 / Math.max(offsetWidth / innerWidth, offsetHeight / innerHeight)) * this.fullScaleFactor; this.style.setProperty('--slide-collect-full-scale-factor', `${scale}`); const offset = (innerHeight - offsetHeight * scale) / 2; // all slides const slideElems = document.querySelectorAll( 'dd-slide-collection > .slide' ); this.style.height = `${slideElems.length * innerHeight}px`; for (const [idx, slideElem] of slideElems.entries()) { slideElem.id = `${idx + 1}`; (slideElem as HTMLElement).style.marginTop = ` ${innerHeight * idx + offset}px`; (slideElem as HTMLElement).style.marginLeft = ` ${(innerWidth - offsetWidth * scale) / 2}px`; if (idx === slideElems.length - 1) (slideElem as HTMLElement).style.marginBottom = `${offset}px`; } } } else { this.classList.add('list'); this.classList.remove('full'); this.style.height = 'auto'; const slideElems = document.querySelectorAll( 'dd-slide-collection > .slide' ); for (const slideElem of slideElems) { (slideElem as HTMLElement).style.marginTop = `0px`; (slideElem as HTMLElement).style.marginLeft = `0px`; } } // update url // WARNING: need to be carefull with pushState event triggers // (alternaive?) const baseUrl = `${window.location.protocol}//${window.location.host}${window.location.pathname}`; if (this.full) window.history.pushState({ fullPage: true }, 'Slide', `${baseUrl}?full`); else window.history.pushState({ fullPage: true }, 'Slide', `${baseUrl}`); // update style this._updateStyle(); }; /* c8 ignore next 13 */ private _handleSlideClick = () => { const slideElems = document.querySelectorAll( 'dd-slide-collection > .slide' ); for (const [idx, elem] of slideElems.entries()) { (elem as HTMLElement).addEventListener('click', () => { if (!this.full) { this._updateView(true); if (document.querySelector('.shower')) return; window.scrollBy(0, window.innerHeight * idx); window.location.hash = `#${idx + 1}`; } }); } }; /* c8 ignore next 5 */ private _handleResize = () => { if (document.querySelector('.shower')) return; this._updateView(); }; /* c8 ignore next 14 */ private _handleLocation = () => { // shower framework related behavior const urlString = window.location.href; const paramString = urlString.split('?')[1]; const queryString = new URLSearchParams(paramString); for (const pair of queryString.entries()) { if (pair[0].includes('full')) { if (!this.full) this._updateView(true); break; } } }; /* c8 ignore next 13 */ private _handleScroll = () => { // external framework if (document.querySelector('.shower')) return; if (this.goToPrint) return; if (this.full) { const scrollHeight = document.documentElement.scrollTop; const idx = Math.floor(scrollHeight / window.innerHeight); // window.location.hash = `#${idx+1}`; window.history.pushState(null, '', `?full#${idx + 1}`); } }; /* c8 ignore next 48 */ private _interactKeys = () => { document.onkeydown = (e: KeyboardEvent) => { const evt = e || window.event; // on escape, go back to list const ddAction = !(evt.ctrlKey || evt.altKey || evt.metaKey); if (ddAction) { switch (evt.key.toUpperCase()) { case 'ESC': case 'ESCAPE': if (this.full) { evt.preventDefault(); this._updateView(true); } break; case 'BACKSPACE': case 'PAGEUP': case 'ARROWUP': case 'ARROWLEFT': case 'P': if (this.full) { evt.preventDefault(); window.scrollBy(0, -window.innerHeight); } break; case 'PAGEDOWN': case 'ARROWDOWN': case 'ARROWRIGHT': case 'N': if (this.full) { evt.preventDefault(); window.scrollBy(0, window.innerHeight); } break; case ' ': if (this.full) { evt.preventDefault(); if (evt.shiftKey) window.scrollBy(0, -window.innerHeight); else window.scrollBy(0, window.innerHeight); } break; default: } } }; }; private _updateStyle = () => { if (this.full) this.parentElement!.style.backgroundColor = 'rgba(0,0,0,1)'; else this.parentElement!.style.backgroundColor = ''; }; connectedCallback() { super.connectedCallback(); // on slide click (from list), check if url changes to full window.addEventListener('DOMContentLoaded', this._handleSlideClick); window.addEventListener('DOMContentLoaded', this._handleLocation); window.addEventListener('resize', this._handleResize); document.addEventListener('scroll', this._handleScroll); window.addEventListener('beforeprint', () => { /* c8 ignore next 2 */ // how to test? this.goToPrint = true; if (!this.full) this.classList.remove('list'); const externalEngine = document.querySelector('.shower'); if (externalEngine) externalEngine.classList.remove('full'); }); window.addEventListener('afterprint', () => { /* c8 ignore next 2 */ // how to test? this.goToPrint = false; if (!this.full) this.classList.add('list'); const externalEngine = document.querySelector('.shower'); if (externalEngine && this.full) externalEngine.classList.add('full'); }); } disconnectedCallback() { window.removeEventListener('DOMContentLoaded', this._handleSlideClick); window.removeEventListener('DOMContentLoaded', this._handleLocation); window.removeEventListener('resize', this._handleResize); document.removeEventListener('scroll', this._handleScroll); window.removeEventListener('beforeprint', () => {}); window.removeEventListener('afterprint', () => {}); super.disconnectedCallback(); } async firstUpdated() { if (this.full) this.classList.add('full'); else this.classList.add('list'); const externalEngine = document.querySelector('.shower'); // parentElem margin to zero if (!externalEngine) this.parentElement!.style.margin = '0'; this._interactKeys(); this._updateStyle(); } render() { let htmlContent = ''; if (this.jsonConfig) this.setPropsFromJson(); const customCaptionElem = this.querySelector('[slot=""caption""]'); if (customCaptionElem) { htmlContent += this.makeCaptionHeader(customCaptionElem.innerHTML); (customCaptionElem as HTMLElement).style.display = 'none'; } else htmlContent += this.makeCaptionHeader(); // slot for custom caption htmlContent += ''; // default slot for slides htmlContent += ''; /* loop over children */ const wrongSlideElements = this.querySelectorAll( 'dd-slide-collection > *:not(.slide):not([slot=""caption""]):not(section)' ); for (const wrongElem of wrongSlideElements) wrongElem.innerHTML = insertHtmlWrongElem(wrongElem as HTMLElement); return html`${unsafeHTML(htmlContent)}`; } } declare global { interface HTMLElementTagNameMap { 'dd-slide-collection': DdSlideCollection; } } ",organisationEl 236,"// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {Client4} from 'mattermost-redux/client'; import {Action, ActionFunc, DispatchFunc} from 'mattermost-redux/types/actions'; import {AppCallResponse, AppForm, AppCallType, AppCallRequest, AppContext} from 'mattermost-redux/types/apps'; import {AppCallTypes, AppCallResponseTypes} from 'mattermost-redux/constants/apps'; import {Post} from 'mattermost-redux/types/posts'; import {CommandArgs} from 'mattermost-redux/types/integrations'; import {openModal} from 'actions/views/modals'; import AppsForm from 'components/apps_form'; import {ModalIdentifiers} from 'utils/constants'; import {getSiteURL, shouldOpenInNewTab} from 'utils/url'; import {browserHistory} from 'utils/browser_history'; import {makeCallErrorResponse} from 'utils/apps'; import {sendEphemeralPost} from './global_actions'; export function doAppCall(call: AppCallRequest, type: AppCallType, intl: any): ActionFunc { return async (dispatch: DispatchFunc) => { try { const res = await Client4.executeAppCall(call, type) as AppCallResponse; const responseType = res.type || AppCallResponseTypes.OK; switch (responseType) { case AppCallResponseTypes.OK: return {data: res}; case AppCallResponseTypes.ERROR: return {error: res}; case AppCallResponseTypes.FORM: if (!res.form) { const errMsg = intl.formatMessage({ id: 'apps.error.responses.form.no_form', defaultMessage: 'Response type is `form`, but no form was included in response.', }); return {error: makeCallErrorResponse(errMsg)}; } if (type === AppCallTypes.SUBMIT) { dispatch(openAppsModal(res.form, call)); } return {data: res}; case AppCallResponseTypes.NAVIGATE: if (!res.navigate_to_url) { const errMsg = intl.formatMessage({ id: 'apps.error.responses.navigate.no_url', defaultMessage: 'Response type is `navigate`, but no url was included in response.', }); return {error: makeCallErrorResponse(errMsg)}; } if (type !== AppCallTypes.SUBMIT) { const errMsg = intl.formatMessage({ id: 'apps.error.responses.navigate.no_submit', defaultMessage: 'Response type is `navigate`, but the call was not a submission.', }); return {error: makeCallErrorResponse(errMsg)}; } if (shouldOpenInNewTab(res.navigate_to_url, getSiteURL())) { window.open(res.navigate_to_url); return {data: res}; } browserHistory.push(res.navigate_to_url.slice(getSiteURL().length)); return {data: res}; default: { const errMsg = intl.formatMessage({ id: 'apps.error.responses.unknown_type', defaultMessage: 'App response type not supported. Response type: {type}.', }, {type: responseType}); return {error: makeCallErrorResponse(errMsg)}; } } } catch (error) { const errMsg = error.message || intl.formatMessage({ id: 'apps.error.responses.unexpected_error', defaultMessage: 'Received an unexpected error.', }); return {error: makeCallErrorResponse(errMsg)}; } }; } export function openAppsModal(form: AppForm, call: AppCallRequest): Action { return openModal({ modalId: ModalIdentifiers.APPS_MODAL, dialogType: AppsForm, dialogProps: { form, call, }, }); } export function postEphemeralCallResponseForPost(response: AppCallResponse, message: string, post: Post): ActionFunc { return sendEphemeralPost( message, post.channel_id, post.root_id || post.id, response.app_metadata?.bot_user_id, ); } export function postEphemeralCallResponseForChannel(response: AppCallResponse, message: string, channelID: string): ActionFunc { return sendEphemeralPost( message, channelID, '', response.app_metadata?.bot_user_id, ); } export function postEphemeralCallResponseForContext(response: AppCallResponse, message: string, [MASK] : AppContext): ActionFunc { return sendEphemeralPost( message, [MASK] .channel_id, [MASK] .root_id || [MASK] .post_id, response.app_metadata?.bot_user_id, ); } export function postEphemeralCallResponseForCommandArgs(response: AppCallResponse, message: string, args: CommandArgs): ActionFunc { return sendEphemeralPost( message, args.channel_id, args.root_id, response.app_metadata?.bot_user_id, ); } ",context 237,"import { Octokit } from '@octokit/rest'; import { Callback, Context, Handler } from 'aws-lambda'; import * as AWS from 'aws-sdk'; import { CodePipelineEvent } from './codepipeline'; import { fetchParameters, getParameter } from './ssm'; const JSON_INDENT = 2; export const handler: Handler = async ( event: CodePipelineEvent, _context: Context, _callback: Callback | undefined, ) => { const parameters = await fetchParameters(); const [MASK] = getParameter(parameters, 'github_token'); if ( [MASK] === undefined) { console.log('No github_token specified'); return; } const octokit = new Octokit({ auth: [MASK] }); const codePipeline = new AWS.CodePipeline(); const execution = await codePipeline .getPipelineExecution({ pipelineExecutionId: event.detail['execution-id'], pipelineName: event.detail.pipeline, }) .promise(); if (execution.pipelineExecution == null) { console.log( 'Failed to fetch pipeline execution', JSON.stringify(execution, null, JSON_INDENT), ); return; } if ( execution.pipelineExecution.artifactRevisions == null || execution.pipelineExecution.artifactRevisions.length === 0 ) { console.log('No revision info found in pipeline execution'); console.log(JSON.stringify(execution, null, JSON_INDENT)); return; } const sha = execution.pipelineExecution.artifactRevisions[0].revisionId; if (sha == null) { console.log('No revisionId found in pipeline execution'); return; } const { revisionUrl } = execution.pipelineExecution.artifactRevisions[0]; if (revisionUrl == null) { console.log( 'No revisionUrl found in pipeline execution', JSON.stringify(execution, null, JSON_INDENT), ); return; } const matches = revisionUrl.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+).*/) || revisionUrl.match( /^https:\/\/.*\.console\.aws\.amazon\.com\/.*FullRepositoryId=([^/]+)\/([^&]+).*/, ); if (matches == null) { console.log(`Not a GitHub revisionUrl: ${revisionUrl}`); return; } const owner = matches[1]; const repo = matches[2]; const state = (( pipelineExecution: AWS.CodePipeline.PipelineExecution, ): 'error' | 'failure' | 'pending' | 'success' => { switch (pipelineExecution.status) { case 'InProgress': return 'pending'; case 'Failed': return 'failure'; case 'Succeeded': return 'success'; default: return 'error'; } })(execution.pipelineExecution); const description = ((): string => { switch (event['detail-type']) { case 'CodePipeline Pipeline Execution State Change': return `${execution.pipelineExecution.status}: Execution ${event.detail['execution-id']}`; case 'CodePipeline Action Execution State Change': case 'CodePipeline Stage Execution State Change': return `${execution.pipelineExecution.status} (${event.detail.stage}): Execution ${event.detail['execution-id']}`; default: throw new Error('Unknown event type'); } })(); await octokit.repos.createCommitStatus({ description, owner, repo, sha, state, context: `CodePipeline (${event.detail.pipeline})`, target_url: `https://${event.region}.console.aws.amazon.com/codesuite/codepipeline/pipelines/${event.detail.pipeline}/executions/${event.detail['execution-id']}/visualization?region=${event.region}`, }); }; ",githubToken 238,"import {Provider} from ""../../utils/decorators/provider""; import * as Hapi from '@hapi/hapi'; import {ClockService} from ""./clock.service""; import { validateDate, validateClock } from ""./clock.validator""; import { ClockDto } from ""./data/clock.dto""; @Provider() export class ClockController { constructor( private readonly service: ClockService, ) { } async listByDate(request: Hapi.Request, h: Hapi.ResponseToolkit): Promise { const { date } = request.params; validateDate(date); const [MASK] = (await this.service .listByDate(date)) .map(ClockDto.ofEntity); return h.response( [MASK] ); } async putClock(request: Hapi.Request, h: Hapi.ResponseToolkit): Promise { const { date, clock } = request.params; validateDate(date); validateClock(clock); await this.service.putClock(date, clock); return h.response().code(204); } async delClock(request: Hapi.Request, h: Hapi.ResponseToolkit): Promise { const { date, clock } = request.params; validateDate(date); validateClock(clock); await this.service.delClock(date, clock); return h.response().code(204); } } ",clocks 239,"import { Tokens } from '@/types/app-request'; import { AuthFailureError, InternalError } from '@core/ApiError'; import JWT, { JwtPayload } from '@core/JWT'; import { Types } from 'mongoose'; import { IUser } from '@model/User/User'; import { tokenInfo } from '../config'; import { Credential, CredentialModel } from '@model/Credential'; export const getAccessToken = (authorization?: string) => { if (!authorization) throw new AuthFailureError('Invalid Authorization'); if (!authorization.startsWith('Bearer ')) throw new AuthFailureError('Invalid Authorization'); return authorization.split(' ')[1]; }; export const validateTokenData = (payload: JwtPayload): boolean => { if ( !payload || !payload.iss || !payload.sub || !payload.aud || !payload.prm || payload.iss !== tokenInfo.issuer || payload.aud !== tokenInfo.audience || !Types.ObjectId.isValid(payload.sub) ) throw new AuthFailureError('Invalid Access Token'); return true; }; export const createTokens = async ( credential: Credential, accessTokenKey: string, [MASK] : string, ): Promise => { const accessToken = await JWT.encode( new JwtPayload( tokenInfo.issuer, tokenInfo.audience, (credential._id || credential).toString(), accessTokenKey, tokenInfo.accessTokenValidity, ), ); if (!accessToken) throw new InternalError(); const refreshToken = await JWT.encode( new JwtPayload( tokenInfo.issuer, tokenInfo.audience, (credential._id || credential).toString(), [MASK] , tokenInfo.refreshTokenValidity, ), ); if (!refreshToken) throw new InternalError(); return { accessToken: accessToken, refreshToken: refreshToken, } as Tokens; }; ",refreshTokenKey 240,"import {Component, OnDestroy, OnInit} from '@angular/core'; import {DeadLettersGridService} from ""../deadletters-grid.service""; import {FormBuilder, FormGroup} from ""@angular/forms""; import {debounceTime, filter, takeWhile, take} from ""rxjs/operators""; import { MessageFilters, MessageTypeDto} from ""../../portal-client""; import {MessageTypesService} from ""../../messages/message-types.service""; import {ServiceBusQueuesService } from ""../servicebus-queues.service""; import {Observable} from ""rxjs""; @Component({ selector: 'app-deadletters-filters', templateUrl: './deadletters-filters.component.html', styleUrls: ['./deadletters-filters.component.scss'] }) export class DeadLettersFiltersComponent implements OnInit, OnDestroy { formGroup: FormGroup; componentExists = true; messageTypes$: Observable; serviceBusQueues$: Observable; constructor( private deadLettersGridService: DeadLettersGridService, private fb: FormBuilder, private messageTypesService: MessageTypesService, private serviceBusQueuesService: ServiceBusQueuesService ) { } ngOnInit(): void { this.messageTypes$ = this.messageTypesService.messageTypes$; this.serviceBusQueues$ = this.serviceBusQueuesService.serviceBusQueues$; // init with empty filters this.deadLettersGridService.init(); this.buildForm(); this.formGroup.valueChanges.pipe( takeWhile(t => this.componentExists), debounceTime(1000), ).subscribe(formVal => this.patchModel(formVal)); this.deadLettersGridService.messageFilters$.pipe( filter(f => f!= null), takeWhile(t => this.componentExists), ).subscribe(filtersModel => this.patchForm(filtersModel)); } buildForm() { this.formGroup = this.fb.group({ fromDate: [''], fromTime: [''], toDate: [''], toTime: [''], sbQueue: [''], typeName: [''], correlationId: [''], messageId: [''] }) } // apply changes from form back to model in service patchModel(formVal: any) { console.log('Form Changed!', formVal); let [MASK] = { ...formVal } as MessageFilters; if (formVal.fromDate && formVal.fromTime) { [MASK] .dateFrom = new Date(formVal.fromDate.getFullYear(), formVal.fromDate.getMonth(), formVal.fromDate.getDate(), formVal.fromTime?.getHours(), formVal.fromTime?.getMinutes(), 0,0); console.log('set DateFrom', [MASK] .dateFrom); } else if (formVal.fromDate) { [MASK] .dateFrom = new Date(formVal.fromDate.getFullYear(), formVal.fromDate.getMonth(), formVal.fromDate.getDate()); } if (formVal.toDate && formVal.toTime) { [MASK] .dateTo = new Date(formVal.toDate.getFullYear(), formVal.toDate.getMonth(), formVal.toDate.getDate(), formVal.toTime?.getHours(), formVal.toTime?.getMinutes(), 0, 0); } else if (formVal.toDate) { [MASK] .dateTo = new Date(formVal.toDate.getFullYear(), formVal.toDate.getMonth(), formVal.toDate.getDate()); } this.deadLettersGridService.applyFilters( [MASK] ); } // apply model changes to form patchForm(filtersModel: MessageFilters) { this.formGroup.patchValue({ ...filtersModel, fromDate: filtersModel.dateFrom, fromTime: filtersModel.dateFrom, toDate: filtersModel.dateTo, toTime: filtersModel.dateTo, }, { emitEvent: false }); } ngOnDestroy(): void { this.componentExists = false; } selectLast10Minutes() { this.setDates( new Date(new Date().getTime() - 10 * 60 * 1000), new Date() ); } selectLast30Minutes() { this.setDates( new Date(new Date().getTime() - 30 * 60 * 1000), new Date() ); } selectLastHour() { this.setDates( new Date(new Date().getTime() - 60 * 60 * 1000), new Date() ); } selectLast4Hours() { this.setDates( new Date(new Date().getTime() - 4* 60 * 60 * 1000), new Date() ); } selectToday() { const now = new Date(); this.setDates( new Date(new Date(now.getFullYear(), now.getMonth(), now.getDate())), new Date(new Date(now.getFullYear(), now.getMonth(), now.getDate()+1)) ); } selectYesterday() { const now = new Date(); this.setDates( new Date(new Date(now.getFullYear(), now.getMonth(), now.getDate()-1)), new Date(new Date(now.getFullYear(), now.getMonth(), now.getDate())) ); } selectThisWeek() { const now = new Date(); this.setDates( new Date(new Date(now.getFullYear(), now.getMonth(), now.getDate()-6)), new Date(new Date(now.getFullYear(), now.getMonth(), now.getDate()+1)) ); } setDates(dateFrom, dateTo) { this.deadLettersGridService.messageFilters$ .pipe(take(1)) .subscribe(f => { f.dateTo = dateTo; f.dateFrom = dateFrom; this.deadLettersGridService.applyFilters(f); }); } formReset() { this.deadLettersGridService.init(); } } ",newFilters 241,"import express = require('express') import { dbClient } from '../db' const MedicineRoute = express.Router() MedicineRoute.get('/', async (_, res) => { const { rows: results } = await dbClient.query('select * from medicines;') res.send({ res: results, }) }) MedicineRoute.post('/', async (req, res) => { const values = req.body const today = new Date() const [MASK] = new Date(today) [MASK] .setDate( [MASK] .getDate() + 1) const default_med_taken_data = `{""tracker_data"": [{ ""date"": ""${today.toJSON().slice(0, 10)}"", ""is_taken"": ""FALSE"" }, { ""date"": ""${ [MASK] .toJSON().slice(0, 10)}"", ""is_taken"": ""FALSE"" } ]}` try { const data = await dbClient.query( `insert into medicines(med_name, dosage_amount, dosage_unit, frequency_amount) values($1, $2, $3, $4) returning *`, [ values.med_name, values.dosage_amount, values.dosage_unit, values.frequency_amount, ] ) const med_id = data.rows[0].med_id console.log(data.rows[0]) for (let i = 0; i < values.reminder_times.length; i++) { const reminder_data = await dbClient.query( `INSERT INTO med_reminder (reminder_time, med_id, med_taken_data) VALUES($1, $2, $3::jsonb) RETURNING *`, [values.reminder_times[i], med_id, default_med_taken_data] ) console.log(reminder_data.rows[0]) } const inventory_data = await dbClient.query( `INSERT INTO med_inventory (amount, threshold_amount, med_id) VALUES($1, $2, $3) RETURNING *`, [values.amount, values.threshold_amount, med_id] ) console.log(inventory_data.rows[0]) res.send(data.rows[0]) } catch (e) { console.log(e) } }) export default MedicineRoute ",tomorrow 242,"import { flags } from '@oclif/command' import { BaseCommand } from '../../base-command' import { GitSyncOptions } from '../../providers/harness/applications' export default class ApplicationsCreate extends BaseCommand { static aliases = ['app:create', 'apps:create', 'applications:create', 'application:create'] static description = 'Create a new Harness application' static flags = { ...BaseCommand.flags, name: flags.string({ description: 'The name of the application', required: true, char: 'n' }), description: flags.string({ description: 'A description of the application' }), syncEnabled: flags.boolean({ description: 'Whether or not git sync should be enabled', dependsOn: ['gitConnector'] }), gitConnector: flags.string({ description: 'The name or id of the git connector to use for git sync.' }), branch: flags.string({ description: 'The branch name to use for git sync. Defaults to ""master"" if sync is enabled.' }), skipExisting: flags.boolean({ description: 'If true, this command will not fail if an resource with the same name already exists.', default: false}), } async run() { const { flags } = this.parse(ApplicationsCreate) const harness = await this.getHarnessClient() let [MASK] : GitSyncOptions | undefined if (flags.syncEnabled && flags.gitConnector) { const connector = await harness.connectors.git.get(flags.gitConnector) [MASK] = { syncEnabled: flags.syncEnabled, gitConnectorId: connector.id, branch: flags.branch, } } const applications = await harness.applications.create(flags.name, flags.description, [MASK] , flags.skipExisting) this.log(applications) } } ",gitSyncOptions 243,"import dotenv from 'dotenv'; import fs from 'fs'; import { ethers } from 'hardhat'; import { OraclePredeploy } from '../types'; import { waitNBlocks } from './utils'; const network = process.env.HARDHAT_NETWORK; const CiphertextType = { 0: 'bool', 1: 'uint8', // corresponding to euint4 2: 'uint8', // corresponding to euint8 3: 'uint16', 4: 'uint32', 5: 'uint64', 6: 'uint128', 7: 'address', }; const currentTime = (): string => { const now = new Date(); return now.toLocaleTimeString('en-US', { hour12: true, hour: 'numeric', minute: 'numeric', second: 'numeric' }); }; const parsedEnv = dotenv.parse(fs.readFileSync('oracle/.env.oracle')); const privKeyRelayer = process.env.PRIVATE_KEY_ORACLE_RELAYER; const relayer = new ethers.Wallet(privKeyRelayer!, ethers.provider); const argEvents = '(uint256 indexed requestID, tuple(uint256 ctHandle, uint8 ctType)[] cts, address contractCaller, bytes4 callbackSelector, uint256 msgValue, uint256 maxTimestamp)'; const ifaceEventDecryption = new ethers.Interface(['event EventDecryption' + argEvents]); const argEvents2 = '(uint256 indexed requestID, bool success, bytes result)'; const ifaceResultCallback = new ethers.Interface(['event ResultCallback' + argEvents2]); let oracle: OraclePredeploy; let firstBlockListening: number; export const asyncDecrypt = async (): Promise => { firstBlockListening = await ethers.provider.getBlockNumber(); // this function will emit logs for every request and fulfilment of a decryption oracle = await ethers.getContractAt('OraclePredeploy', parsedEnv.ORACLE_CONTRACT_PREDEPLOY_ADDRESS); oracle.on( 'EventDecryption', async (requestID, cts, contractCaller, callbackSelector, msgValue, maxTimestamp, eventData) => { const blockNumber = eventData.log.blockNumber; console.log(`${await currentTime()} - Requested decrypt on block ${blockNumber} (requestID ${requestID})`); }, ); oracle.on('ResultCallback', async (requestID, success, result, eventData) => { const blockNumber = eventData.log.blockNumber; console.log(`${await currentTime()} - Fulfilled decrypt on block ${blockNumber} (requestID ${requestID})`); }); }; export const awaitAllDecryptionResults = async (): Promise => { oracle = await ethers.getContractAt('OraclePredeploy', parsedEnv.ORACLE_CONTRACT_PREDEPLOY_ADDRESS); await fulfillAllPastRequestsIds(network === 'hardhat'); firstBlockListening = await ethers.provider.getBlockNumber(); }; const getAlreadyFulfilledDecryptions = async (): Promise<[bigint]> => { let results = []; const [MASK] = await oracle.filters.ResultCallback().getTopicFilter(); const filterDecryptionResult = { address: process.env.ORACLE_CONTRACT_PREDEPLOY_ADDRESS, fromBlock: firstBlockListening, toBlock: 'latest', topics: [MASK] , }; const pastResults = await ethers.provider.getLogs(filterDecryptionResult); results = results.concat(pastResults.map((result) => ifaceResultCallback.parseLog(result).args[0])); return results; }; const fulfillAllPastRequestsIds = async (mocked: boolean) => { const eventDecryption = await oracle.filters.EventDecryption().getTopicFilter(); const results = await getAlreadyFulfilledDecryptions(); const filterDecryption = { address: process.env.ORACLE_CONTRACT_PREDEPLOY_ADDRESS, fromBlock: firstBlockListening, toBlock: 'latest', topics: eventDecryption, }; const pastRequests = await ethers.provider.getLogs(filterDecryption); for (const request of pastRequests) { const event = ifaceEventDecryption.parseLog(request); const requestID = event.args[0]; const cts = event.args[1]; const handles = cts.map((ct) => ct[0]); const typesEnum = cts.map((ct) => ct[1]); const msgValue = event.args[4]; if (!results.includes(requestID)) { // if request is not already fulfilled if (mocked) { // in mocked mode, we trigger the decryption fulfillment manually const types = typesEnum.map((num) => CiphertextType[num]); const values = handles.map((handle, index) => (typesEnum[index] === 7n ? handle.toString(16) : handle)); const calldata = ethers.AbiCoder.defaultAbiCoder().encode(types, values); const tx = await oracle.connect(relayer).fulfillRequest(requestID, calldata, { value: msgValue }); await tx.wait(); } else { // in fhEVM mode we must wait until the oracle service relayer submits the decryption fulfillment tx await waitNBlocks(1); await fulfillAllPastRequestsIds(mocked); } } } }; ",eventDecryptionResult 244,"// Copyright 2020 // SPDX-License-Identifier: Apache-2.0 import {Bech32, Blake2b} from ""@iota/crypto.js"" import * as wasmlib from ""wasmlib"" // Thank you, @iota/crypto.js, for making my life easy export class Codec { public static bech32Prefix: string = ""smr""; public static bech32Decode(bech32: string): wasmlib.ScAddress | null { let dec = Bech32.decode(bech32); if (dec == undefined) { return null; } let buf = wasmlib.bytesFromUint8Array(dec.data); return wasmlib.addressFromBytes(buf); } public static bech32Encode(addr: wasmlib.ScAddress): string { let buf = wasmlib.addressToBytes(addr); let [MASK] = wasmlib.bytesToUint8Array(buf); return Bech32.encode(Codec.bech32Prefix, [MASK] ); } public static hNameBytes(name: string): u8[] { const data = Uint8Array.wrap(String.UTF8.encode(name)); let hash = Blake2b.sum256(data) // follow exact algorithm from packages/isc/hname.go let slice = wasmlib.bytesFromUint8Array(hash.slice(0, 4)); let hName = wasmlib.uint32FromBytes(slice); if (hName == 0 || hName == 0xffff) { slice = wasmlib.bytesFromUint8Array(hash.slice(4, 8)); } return slice; } }",iscAddr 245,"import { ItemEventData } from ""ui/list-view"" import { SearchBar } from ""ui/search-bar""; import { Component, ElementRef, OnInit, ViewChild } from '@angular/core'; import { CFAlertDialog, DialogOptions, CFAlertGravity, CFAlertActionAlignment, CFAlertActionStyle, CFAlertStyle } from 'nativescript-cfalert-dialog'; import ApiClient = require('nativescript-apiclient'); import { Volume } from 'nativescript-volume'; @Component({ selector: ""Home"", moduleId: module.id, templateUrl: ""./home.component.html"", styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { @ViewChild(""vplayer"") vplayer: ElementRef; command: string = """"; searchPhrase: string = """"; src: string = """"; playerOptions: any = { controls: 0, playsinline: 1, enablejsapi: 1, }; isLoading: boolean = false; videoResults: IVideoResult[] = [ { title: ""Search to find videos"", image: { url: ""https://d2an5carukjfes.cloudfront.net/tutorials/groceries-ng/images/nativescript-logo.png?t=1.9.777"" }}, ]; searchResults: IYoutubeSearchResult[]; commandHelpDialog = new CFAlertDialog(); commandHelpMessages = { general: 'All commands have shortcuts and/or aliases. Shortcuts and aliases are denoted in square brackets.\n\n', help: 'help - [h, ?, commands, list]\n', search: 'search - [s]\n', load: 'load - [l]\n', loadplay: 'loadplay - [lp]\n', play: 'play - [pl]\n', pause: 'pause - [p]\n', stop: 'stop - [st]\n', mute: 'mute - [m]\n', unmute: 'unmute - [un]\n', volume: 'volume - [v u, v d, v dn, v m, v un]', } commandHelpOptions: DialogOptions = { dialogStyle: CFAlertStyle.BOTTOM_SHEET, title: ""Command List"", textAlignment: CFAlertGravity.START, message: this.commandHelpMessages.general + this.commandHelpMessages.help + this.commandHelpMessages.search + this.commandHelpMessages.load + this.commandHelpMessages.play + this.commandHelpMessages.pause + this.commandHelpMessages.stop + this.commandHelpMessages.mute + this.commandHelpMessages.unmute + this.commandHelpMessages.volume } searchBaseUrl: string = ""https://www.googleapis.com/youtube/v3/search""; searchSnippet: string = ""snippet""; searchMaxResults: number = 5; searchType: string = ""video""; searchVideoEmbeddable: boolean = true; searchFields: string = ""items(id/videoId,snippet(thumbnails/default,title))""; searchApiKey: string = """"; volume: Volume = new Volume(); constructor() { } ngOnInit(): void { } onItemTap(args: ItemEventData): void { console.log('Item with index: ' + args.index + ' tapped'); // Thinking it should load the text into the command line for us on click // If load is already in the command box with the correct index, it should put the ""play"" command in const cmdInfo = this.getCommandInfo(); const [MASK] = 'load ' + args.index; switch (cmdInfo.cmd) { case 'load': if (cmdInfo.params == args.index.toString()) { // Move forward to the play this.command = 'play'; } else { this.command = [MASK] ; } break; default: this.command = [MASK] ; break; } } onSearchSubmit(args): void { let searchBar = args.object; console.log(""SearchBar search "" + searchBar.text); this.command = ""s "" + searchBar.text; this.searchYouTube(searchBar.text); } onGoTap(): void { console.log(""User wants to send command!""); const cmdInfo = this.getCommandInfo(); console.log('cmd', cmdInfo.cmd, 'arg', cmdInfo.params); switch (cmdInfo.cmd.toLowerCase()) { case 'h': case '?': case 'commands': case 'list': case 'help': this.onHelpTap(); break; case 's': case 'search': this.searchYouTube(cmdInfo.params); break; case 'l': case 'load': this.loadVideoToPlayer(cmdInfo.params); break; case 'lp': case 'loadplay': this.loadVideoToPlayer(cmdInfo.params); this.playVideo(); break; case 'pl': case 'play': this.playVideo(); break; case 'st': case 'stop': this.vplayer.nativeElement.stop(); break; case 'p': case 'pause': this.vplayer.nativeElement.pause(); break; case 'm': case 'mute': this.muteVolume(); break; case 'un': case 'unmute': this.unmuteVolume(); break; case 'v': case 'vol': case 'volume': switch (cmdInfo.params.toLowerCase()) { case 'u': case 'up': this.increaseVolume(); break; case 'd': case 'dn': case 'down': this.decreaseVolume(); break; case 'm': case 'mute': this.muteVolume(); break; case 'un': case 'unmute': this.unmuteVolume(); break; } } } onHelpTap(): void { this.commandHelpDialog.show(this.commandHelpOptions); } decreaseVolume(): void { console.log('attempted to decrease volume'); this.volume.volumeDown(); } getCommandInfo() { let params: string; const cmdSplit: string[] = this.command.split(' '); const cmd: string = cmdSplit[0]; if (cmdSplit.length > 1) { params = this.command.substring(cmd.length + 1); } return { cmd: cmd, params: params, }; } increaseVolume() { console.log('attempted to increase volume'); this.volume.volumeUp(); } loadVideoToPlayer(videoIndex: string): void { // if (this.src == 'wH_0_pijbZY') { // this.src = 'vEG4qNW33mA'; // } else { // this.src = 'wH_0_pijbZY'; // } console.log('videoIndex', videoIndex); this.src = this.videoResults[videoIndex].videoId; } muteVolume(): void { console.log('attempted to mute'); this.volume.mute(); } playVideo(): void { this.vplayer.nativeElement.play(); if (this.vplayer.nativeElement.isFullscreen) { this.vplayer.nativeElement.toggleFullscreen(); } } searchYouTube(searchPhrase: string): void { let that = this; let client = ApiClient.newClient({ baseUrl: this.searchBaseUrl }); const noVevoSearch = ' -' + searchPhrase.replace(' ', '') + 'vevo'; const alternativeNoVevo = ' -""(C)""'; client.get({ params: { part: this.searchSnippet, maxResults: this.searchMaxResults, videoEmbeddable: this.searchVideoEmbeddable, type: this.searchType, fields: this.searchFields, key: this.searchApiKey, q: searchPhrase + alternativeNoVevo } }); client.success((result: ApiClient.IApiClientResult) => { let results = result.getJSON(); let videoResults: IVideoResult[] = []; let index = 0; for (let itemResult of (results.items as IYoutubeSearchResult[])) { videoResults.push({ videoId: itemResult.id.videoId || null, title: itemResult.snippet.title || null, image: { url: itemResult.snippet.thumbnails.default.url || null, width: itemResult.snippet.thumbnails.default.width || null, height: itemResult.snippet.thumbnails.default.height || null, } }); } that.videoResults = videoResults; }); } unmuteVolume(): void { console.log('attempted to unmute'); this.volume.unmute(); } } ",cmdLoad 246,"import EventEmitter from ""node:events"" import Log from ""./log.js"" import Redis from ""./redis.js"" /** * @class GameState * @description handle game updates from Redis and maintain local state */ export default class GameState extends EventEmitter implements Game.State { public gameType = Game.Type.CUSTOM public gamePhase = Game.Phase.INITIALIZING public replay_id = """" public playerIndex = null public turn = 0 public usernames = null public scores = null public won = null constructor(botId: string, [MASK] : boolean = false) { super() Redis.subscribe(botId, RedisData.CHANNEL.STATE, this.handleStateUpdates) if ( [MASK] ) { Redis.subscribe(botId, RedisData.CHANNEL.GAME_UPDATE, this.handleGameUpdates) } } public handleStateUpdates = async (data: RedisData.State) => { Log.debugObject('handleStateUpdates', data) let type: string = Object.keys(data)[0] switch (type) { case 'connected': this.gamePhase = Game.Phase.CONNECTED this.emit('connected') break case 'disconnected': this.gamePhase = Game.Phase.INITIALIZING this.emit('disconnected') break case 'joined': this.gamePhase = Game.Phase.JOINED_LOBBY this.emit('joined') break case 'left': this.gamePhase = Game.Phase.CONNECTED this.emit('left') break case 'playing': this.gamePhase = Game.Phase.PLAYING this.emit('playing') break case 'game_lost': this.gamePhase = Game.Phase.CONNECTED this.won = false this.emit('ended') break case 'game_won': this.gamePhase = Game.Phase.CONNECTED this.won = true this.emit('ended') break case 'game_start': this.gamePhase = Game.Phase.PLAYING this.gameType = data.game_start.game_type this.replay_id = data.game_start.replay_id this.playerIndex = data.game_start.playerIndex this.turn = 0 this.usernames = data.game_start.usernames this.scores = null this.won = null this.emit('game_start', data.game_start.replay_id) break } this.emit('phase', this.gamePhase) this.emit('update', this) } private handleGameUpdates = async (data: GeneralsIO.GameUpdate) => { this.turn = data.turn this.scores = data.scores this.emit('update', this) } } ",enableTurnByTurnUpdates 247,"/* * (C) Copyright 2017 Hewlett Packard Enterprise Development LP * * 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. */ export class AlarmHistoryPageCtrl { public static templateUrl = ""components/alarm_history.html""; private updating: boolean; private updateFailed: boolean; private id: number; private states: Array; private savedAlarm: any; private saving: boolean; private deleting: boolean; public loadFailed: boolean; public pageLoaded: boolean; public init: Promise; /** @ngInject */ public constructor( private $timeout, private $location, private alertSrv, private monascaClientSrv ) { this.updating = true; this.updateFailed = false; this.id = null; if (""id"" in this.$location.search()) { this.id = this.$location.search().id; } this.states = []; this.savedAlarm = {}; this.saving = false; this.deleting = false; if (!this.id) { this.updating = false; } else { this.init = this.loadStates(this.loadAlarm()).then(() => this.$timeout()); } } private pickKnownFields(alarm) { this.savedAlarm.name = alarm.alarm_definition.name; this.savedAlarm.severity = alarm.alarm_definition.severity; this.savedAlarm.state = alarm.state; return this.savedAlarm; } private loadAlarm() { return this.monascaClientSrv .getAlarm(this.id) .then(alarm => { this.savedAlarm = this.pickKnownFields(alarm); }) .catch(err => { this.alertSrv.set( ""Failed to fetch alarm method."", err.message, ""error"", 10000 ); this.loadFailed = true; }); } private loadStates( [MASK] ) { return [MASK] .then(() => this.monascaClientSrv.getAlarmHistory(this.id)) .then(alarmHistory => { for (var i = 0; i < alarmHistory.elements.length; i++) { alarmHistory.elements[i].timestamp = alarmHistory.elements[ i ].timestamp.replace(/[A-Z.]/g, "" ""); alarmHistory.elements[i].timestamp = alarmHistory.elements[ i ].timestamp.replace(/.{4}$/g, "" ""); this.states.push(alarmHistory.elements[i]); } }) .catch(err => { this.alertSrv.set( ""Failed to fetch alarm history method."", err.message, ""error"", 10000 ); this.loadFailed = true; }) .then(() => { this.pageLoaded = true; }); } } ",promiseChain 248,"""use client"" import type React from ""react"" import { useCallback, useRef, useState, type ChangeEvent, type DragEvent, type InputHTMLAttributes, } from ""react"" export type FileMetadata = { name: string size: number type: string url: string // Can be server URL post-upload or preview URL id: string // Should be unique identifier for the file entry uploaded?: boolean // To track successful upload uploadError?: string // To store upload specific error } export type FileWithPreview = { file: File | FileMetadata // Can be File initially, then FileMetadata post-upload id: string // Unique ID for this FileWithPreview item preview?: string // URL for preview, e.g., object URL for images } export type FileUploadOptions = { maxFiles?: number maxSize?: number // in bytes accept?: string // Comma-separated string of accepted file types multiple?: boolean initialFiles?: FileMetadata[] // To initialize with already uploaded files onFilesChange?: (files: FileWithPreview[]) => void onFilesAdded?: (addedFiles: FileWithPreview[]) => void // Called with newly added valid files onUploadSuccess?: (uploadedFile: FileWithPreview, response: Record) => void onUploadError?: (file: FileWithPreview, error: string) => void uploadUrl?: string // API endpoint for uploading } export type FileUploadState = { files: FileWithPreview[] isDragging: boolean errors: string[] // For validation or general errors isUploadingGlobal: boolean // Global flag for ongoing upload(s) } export type FileUploadActions = { addFiles: (files: FileList | File[]) => void // Public API to add and initiate upload removeFile: (id: string) => void clearFiles: () => void clearErrors: () => void handleDragEnter: (e: DragEvent) => void handleDragLeave: (e: DragEvent) => void handleDragOver: (e: DragEvent) => void handleDrop: (e: DragEvent) => void // handleFileChange is usually internal, triggered by getInputProps openFileDialog: () => void getInputProps: ( props?: InputHTMLAttributes ) => InputHTMLAttributes & { ref: React.Ref } } export const formatBytes = (bytes: number, decimals = 2): string => { if (bytes === 0) return ""0 Bytes"" const k = 1024 const dm = decimals < 0 ? 0 : decimals const sizes = [""Bytes"", ""KB"", ""MB"", ""GB"", ""TB"", ""PB"", ""EB"", ""ZB"", ""YB""] const i = Math.floor(Math.log(bytes) / Math.log(k)) return `${parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}` } export const useFileUpload = ( options: FileUploadOptions = {} ): [FileUploadState, FileUploadActions] => { const { maxFiles = Infinity, maxSize = Infinity, accept = ""*/*"", // More common default multiple = false, initialFiles = [], onFilesChange, onFilesAdded, onUploadSuccess, onUploadError, uploadUrl, } = options const [state, setState] = useState({ files: initialFiles.map((fileMeta) => ({ // initialFiles are FileMetadata file: fileMeta, id: fileMeta.id, // Ensure initialFiles have an id preview: fileMeta.url, // Use url from FileMetadata as preview })), isDragging: false, errors: [], isUploadingGlobal: false, }) const inputRef = useRef(null) const validateFile = useCallback( (file: File): string | null => { // Simplified: always validates a File object if (file.size > maxSize) { return `File ""${file.name}"" exceeds the maximum size of ${formatBytes(maxSize)}.` } if (accept !== ""*/*"" && accept !== ""*"") { const acceptedTypes = accept.split("","").map((type) => type.trim().toLowerCase()) const fileType = file.type.toLowerCase() const fileName = file.name.toLowerCase() const fileExtension = `.${fileName.split(""."").pop()}` const isAccepted = acceptedTypes.some((type) => { if (type.startsWith(""."")) { // e.g., .pdf return fileExtension === type } if (type.endsWith(""/*"")) { // e.g., image/* const baseType = type.slice(0, -2) // image return fileType.startsWith(`${baseType}/`) } return fileType === type // e.g., application/pdf }) if (!isAccepted) { return `File ""${file.name}"" type not accepted. Accepted types: ${accept}` } } return null }, [accept, maxSize] ) const createPreview = useCallback((file: File): string | undefined => { if (file.type.startsWith(""image/"")) { return URL.createObjectURL(file) } return undefined }, []) const generateUniqueId = useCallback((file: File): string => { return `${file.name}-${file.size}-${file.lastModified}-${Math.random().toString(36).substring(2, 9)}` }, []) const _uploadFileInternal = async (fileToUpload: FileWithPreview) => { // Ensure fileToUpload.file is a File instance for upload if (!(fileToUpload.file instanceof File)) { const errorMsg = `Cannot upload ""${(fileToUpload.file as FileMetadata).name}""; it's not a valid file object for direct upload.`; console.error(errorMsg, fileToUpload); // Update this specific file's metadata with an error const updatedFileWithMetaError: FileWithPreview = { ...fileToUpload, file: { ...(fileToUpload.file as FileMetadata), // Keep existing metadata uploadError: errorMsg, uploaded: false, } }; setState(prev => ({ ...prev, files: prev.files.map(f => f.id === updatedFileWithMetaError.id ? updatedFileWithMetaError : f), errors: [...prev.errors, errorMsg], // Add to general errors too isUploadingGlobal: false // Assuming this path means no actual network upload starts })); onUploadError?.(updatedFileWithMetaError, errorMsg); return; } if (!uploadUrl) { const errorMsg = ""Upload URL is not configured."" console.warn(errorMsg, ""File not uploaded:"", fileToUpload.file.name) // Update file metadata to reflect it wasn't uploaded due to config const fileWithConfigError: FileWithPreview = { ...fileToUpload, file: { // Convert to FileMetadata with error name: fileToUpload.file.name, size: fileToUpload.file.size, type: fileToUpload.file.type, id: fileToUpload.id, url: fileToUpload.preview || '', uploaded: false, uploadError: errorMsg, } }; setState(prev => ({ ...prev, files: prev.files.map(f => f.id === fileWithConfigError.id ? fileWithConfigError : f), errors: [...prev.errors, errorMsg], isUploadingGlobal: false })); onUploadError?.(fileWithConfigError, errorMsg); return; } const formData = new FormData() formData.append(""file"", fileToUpload.file) // FastAPI expects 'file' field setState(prev => ({ ...prev, isUploadingGlobal: true, errors: [] })) try { const response = await fetch(uploadUrl, { method: ""POST"", body: formData, }) let responseData: Record = {}; // Initialize for broader scope const contentType = response.headers.get(""content-type""); if (!response.ok) { let errorDetail = `Upload failed for ${fileToUpload.file.name}. Status: ${response.status} ${response.statusText}`; try { const errorText = await response.text(); errorDetail += ` - Server response: ${errorText.substring(0, 200)}${errorText.length > 200 ? '...' : ''}`; } catch (textError: unknown) { console.warn(""Could not read error response text:"", textError); } throw new Error(errorDetail); } if (contentType && contentType.includes(""application/json"")) { responseData = await response.json() as Record; } else { // Handle non-JSON or missing Content-Type response if necessary, // or assume success if response.ok and no JSON is expected for some cases. // For now, we'll assume JSON is expected on success. console.warn(`Response for ${fileToUpload.file.name} was not JSON. Content-Type: ${contentType}`); // If JSON is strictly required, this could be an error condition: // throw new Error(`Unexpected response type: ${contentType}. Expected JSON.`); } const successfullyUploadedFile: FileWithPreview = { ...fileToUpload, file: { // This is FileMetadata name: fileToUpload.file.name, size: fileToUpload.file.size, type: fileToUpload.file.type, id: fileToUpload.id, // Use existing FileWithPreview ID as FileMetadata ID url: typeof responseData.file_url === 'string' ? responseData.file_url : // Assuming server returns 'file_url' (typeof responseData.url === 'string' ? responseData.url : fileToUpload.preview || ''), uploaded: true, } }; setState(prev => { const updatedFiles = prev.files.map(f => f.id === successfullyUploadedFile.id ? successfullyUploadedFile : f ) onUploadSuccess?.(successfullyUploadedFile, responseData) return { ...prev, files: updatedFiles, isUploadingGlobal: false } }) } catch (error: unknown) { const errorMessage = error instanceof Error ? error.message : `Error uploading ${ (fileToUpload.file as File).name}.`; const fileWithError: FileWithPreview = { ...fileToUpload, file: { // This is FileMetadata name: (fileToUpload.file as File).name, size: (fileToUpload.file as File).size, type: (fileToUpload.file as File).type, id: fileToUpload.id, url: fileToUpload.preview || '', uploaded: false, uploadError: errorMessage, } }; setState(prev => { const updatedFiles = prev.files.map(f => f.id === fileWithError.id ? fileWithError : f ) // Add to general errors in addition to specific file error const newErrors = prev.errors.filter(e => !e.includes(fileWithError.file.name)); // Avoid duplicate general messages for the same file newErrors.push(errorMessage); onUploadError?.(fileWithError, errorMessage) return { ...prev, files: updatedFiles, errors: newErrors, isUploadingGlobal: false } }) } } const addFilesAndUpload = useCallback( (newFilesInput: FileList | File[]) => { if (state.isUploadingGlobal) return; // Don't add if already uploading (for single mode primarily) if (!newFilesInput || newFilesInput.length === 0) return const newFilesArray = Array.from(newFilesInput) const currentValidationErrors: string[] = [] // Local to this call // For single file mode, if a file already exists (even if being uploaded or failed), replace it. if (!multiple && state.files.length > 0) { state.files.forEach((fwp) => { // Revoke old preview if (fwp.preview && fwp.file instanceof File && fwp.file.type.startsWith(""image/"")) { URL.revokeObjectURL(fwp.preview) } }) setState(prev => ({ ...prev, files: [], errors: [] })); // Clear existing files and their errors } else { setState(prev => ({ ...prev, errors: [] })); // Clear general errors for new batch } if (!multiple && newFilesArray.length > 1) { currentValidationErrors.push(""Please select only one file."") setState(prev => ({ ...prev, errors: currentValidationErrors })) if (inputRef.current) inputRef.current.value = """" return } if (multiple && maxFiles !== Infinity && state.files.length + newFilesArray.length > maxFiles) { currentValidationErrors.push(`You can only upload a maximum of ${maxFiles} files.`) setState((prev) => ({ ...prev, errors: [...prev.errors, ...currentValidationErrors] })) if (inputRef.current) inputRef.current.value = """" return } const filesToProcess: FileWithPreview[] = [] for (const file of newFilesArray) { if (!(file instanceof File)) continue; // Skip if not a File object // Duplicate check (more robust for multiple additions) const isDuplicate = (!multiple && state.files.length > 0) ? false : // In single mode, we already cleared state.files.some(existingFwp => existingFwp.file.name === file.name && existingFwp.file.size === file.size && (existingFwp.file instanceof File ? existingFwp.file.lastModified === file.lastModified : true) ); if (isDuplicate) continue; const validationError = validateFile(file) if (validationError) { currentValidationErrors.push(validationError) } else { filesToProcess.push({ file, // Actual File object id: generateUniqueId(file), preview: createPreview(file), }) } } if (currentValidationErrors.length > 0) { setState((prev) => ({ ...prev, errors: [...prev.errors, ...currentValidationErrors] })) if (inputRef.current) inputRef.current.value = """" return } if (filesToProcess.length > 0) { const filesToAddUpdate = !multiple ? filesToProcess.slice(0, 1) : filesToProcess; setState(prev => { const updatedFilesState = !multiple ? filesToAddUpdate : [...prev.files, ...filesToAddUpdate] onFilesChange?.(updatedFilesState) // Call with the full list onFilesAdded?.(filesToAddUpdate) // Call with only the newly added valid files return { ...prev, files: updatedFilesState, } }) if (uploadUrl) { filesToAddUpdate.forEach(fileToUpload => _uploadFileInternal(fileToUpload)) } else { console.warn(""uploadUrl not provided. Files added locally but not uploaded."") // If no uploadUrl, mark files as 'pending' or similar if needed, or convert to FileMetadata locally const filesAsMetadataLocally = filesToAddUpdate.map(fwp => ({ ...fwp, file: { // Convert to FileMetadata to indicate they are processed by the hook name: (fwp.file as File).name, size: (fwp.file as File).size, type: (fwp.file as File).type, id: fwp.id, url: fwp.preview || '', // Use preview as URL if no upload uploaded: false, // Not uploaded uploadError: ""Upload URL not configured"", } as FileMetadata })); setState(prev => { const updatedFiles = prev.files.map(existingFile => { const [MASK] = filesAsMetadataLocally.find(processedFile => processedFile.id === existingFile.id); return [MASK] || existingFile; }); return { ...prev, files: updatedFiles }; }); } } if (inputRef.current) { inputRef.current.value = """" } }, [ state.isUploadingGlobal, state.files, // Critical for logic within multiple, maxFiles, uploadUrl, validateFile, generateUniqueId, createPreview, // Other useCallback deps onFilesChange, onFilesAdded, // Callbacks // _uploadFileInternal is not directly a dep but its logic is tied to uploadUrl etc. // setState itself is stable. ] ) const removeFile = useCallback( (id: string) => { setState((prev) => { const fileToRemove = prev.files.find((file) => file.id === id) if (fileToRemove?.preview && fileToRemove.file instanceof File && fileToRemove.file.type.startsWith(""image/"")) { URL.revokeObjectURL(fileToRemove.preview) } const newFiles = prev.files.filter((file) => file.id !== id) onFilesChange?.(newFiles) let updatedErrors = prev.errors; if (fileToRemove?.file?.name) { // Remove errors specifically mentioning this file by name updatedErrors = prev.errors.filter(err => !err.includes(fileToRemove.file.name)); } // If all files are removed, clear all errors if (newFiles.length === 0) { updatedErrors = []; } if (inputRef.current && newFiles.length === 0) { inputRef.current.value = """"; } return { ...prev, files: newFiles, errors: updatedErrors, isUploadingGlobal: newFiles.length > 0 ? prev.isUploadingGlobal : false } }) }, [onFilesChange] // setState is stable ) const clearFiles = useCallback(() => { setState((prev) => { prev.files.forEach((fwp) => { if (fwp.preview && fwp.file instanceof File && fwp.file.type.startsWith(""image/"")) { URL.revokeObjectURL(fwp.preview) } }) if (inputRef.current) { inputRef.current.value = """" } const newState = { ...prev, files: [], errors: [], isUploadingGlobal: false } onFilesChange?.(newState.files) return newState }) }, [onFilesChange]) // setState is stable const clearErrors = useCallback(() => { setState((prev) => ({ ...prev, errors: [] })) }, []) // setState is stable const handleDragEnter = useCallback((e: DragEvent) => { e.preventDefault() e.stopPropagation() if (state.isUploadingGlobal && !multiple) return; if (!multiple && state.files.length > 0) return; // Don't allow drag if single file already present setState((prev) => ({ ...prev, isDragging: true })) }, [state.isUploadingGlobal, state.files.length, multiple]) const handleDragLeave = useCallback((e: DragEvent) => { e.preventDefault() e.stopPropagation() if (state.isUploadingGlobal && !multiple) return; if (e.currentTarget.contains(e.relatedTarget as Node)) { return; } setState((prev) => ({ ...prev, isDragging: false })) }, [state.isUploadingGlobal, multiple]) const handleDragOver = useCallback((e: DragEvent) => { e.preventDefault() e.stopPropagation() if (state.isUploadingGlobal && !multiple) { e.dataTransfer.dropEffect = ""none""; return; } if (!multiple && state.files.length > 0) { e.dataTransfer.dropEffect = ""none""; return; } e.dataTransfer.dropEffect = ""copy""; // Explicitly show copy cursor setState((prev) => ({ ...prev, isDragging: true })) }, [state.isUploadingGlobal, state.files.length, multiple]) const handleDrop = useCallback( (e: DragEvent) => { e.preventDefault() e.stopPropagation() setState((prev) => ({ ...prev, isDragging: false })) if (state.isUploadingGlobal && !multiple) return; if (!multiple && state.files.length > 0) return; if (e.dataTransfer.files && e.dataTransfer.files.length > 0) { addFilesAndUpload(e.dataTransfer.files) // This is addFilesAndUpload e.dataTransfer.clearData() } }, [addFilesAndUpload, state.isUploadingGlobal, state.files.length, multiple] // addFilesAndUpload is from useCallback ) const handleFileChange = useCallback( (e: ChangeEvent) => { // isUploadingGlobal check is handled within addFilesAndUpload for single mode if (e.target.files && e.target.files.length > 0) { addFilesAndUpload(e.target.files) // This is addFilesAndUpload } }, [addFilesAndUpload] // addFilesAndUpload is from useCallback ) const openFileDialog = useCallback(() => { if (state.isUploadingGlobal && !multiple) return; if (!multiple && state.files.length > 0) return; // Prevent opening if single file already selected if (inputRef.current) { inputRef.current.click() } }, [state.isUploadingGlobal, state.files.length, multiple]) const getInputProps = useCallback( (props?: InputHTMLAttributes) => ({ ...props, ref: inputRef, type: ""file"", onChange: handleFileChange, accept: accept, multiple: multiple, // Disable if global upload is happening (especially for single mode) // or if it's single mode and a file is already present. disabled: (state.isUploadingGlobal && !multiple) || (!multiple && state.files.length > 0), style: { display: ""none"", ...props?.style }, }), [handleFileChange, accept, multiple, state.isUploadingGlobal, state.files.length] ) return [ state, { addFiles: addFilesAndUpload, // Expose internal addFilesAndUpload as addFiles removeFile, clearFiles, clearErrors, handleDragEnter, handleDragLeave, handleDragOver, handleDrop, openFileDialog, getInputProps, }, ] }",found 249,"export class Vector2 { x: number y: number constructor (x: number, y: number) { this.x = x this.y = y } } export class Vector3 extends Vector2 { z: number constructor (x: number, y: number, z: number) { super(x, y) this.z = z } } export interface Color { r: number g: number b: number a: number } export interface GameObject { position: Vector3 radius: number color: Color extra?: any } export class Scene { objects: GameObject[] = [] constructor (objects: GameObject[]) { this.objects = objects } } export class Opts { FOV: number PROJECTION_CENTER_X: number PROJECTION_CENTER_Y: number constructor ( FOV: number, PROJECTION_CENTER_X: number, PROJECTION_CENTER_Y: number ) { this.FOV = FOV this.PROJECTION_CENTER_X = PROJECTION_CENTER_X this.PROJECTION_CENTER_Y = PROJECTION_CENTER_Y } } export class Renderer { Canvas: HTMLCanvasElement ctx: CanvasRenderingContext2D scene: Scene Opts: Opts constructor (Canvas: HTMLCanvasElement, Scene: Scene) { this.Canvas = Canvas this.scene = Scene this.ctx = Canvas.getContext('2d') as CanvasRenderingContext2D this.Opts = new Opts( this.Canvas.width * 1, this.Canvas.width / 2, this.Canvas.height / 2 ) } project (object: GameObject) { let [MASK] = this.Opts.FOV / (this.Opts.FOV + object.position.z) const xProject = object.position.x * [MASK] + this.Opts.PROJECTION_CENTER_X const yProject = object.position.y * [MASK] + this.Opts.PROJECTION_CENTER_Y return [xProject, yProject, [MASK] ] } draw (object: GameObject) { let [xProjected, yProjected, scaleProjected] = this.project(object) this.ctx.globalAlpha = Math.abs(1 - object.position.z / this.Opts.FOV) if (object.position.z < -this.Opts.FOV + object.radius) { return } this.ctx.fillStyle = `rgba(${object.color.r}, ${object.color.g}, ${object.color.b}, ${object.color.a})` this.ctx.fillRect( xProjected - object.radius, yProjected - object.radius, object.radius * 2 * scaleProjected, object.radius * 2 * scaleProjected ) } render () { this.scene.objects.forEach(object => { this.draw(object) }) } } export class Game { fps: number = 60 scene: Scene renderer: Renderer Canvas: HTMLCanvasElement context: CanvasRenderingContext2D constructor (fps: number, Canvas: HTMLCanvasElement) { this.fps = fps this.scene = new Scene([]) this.renderer = new Renderer(Canvas, this.scene) this.Canvas = Canvas this.context = Canvas.getContext('2d') as CanvasRenderingContext2D } draw () { this.context.clearRect( 0, 0, this.context.canvas.width, this.context.canvas.height ) this.scene.objects.sort((a, b) => a.position.z - b.position.z).forEach(object => { this.renderer.draw(object) }) } } export class KeyLogic { keys: { [key: string]: boolean } = {} constructor () { this.keys = {} document.addEventListener('keydown', e => { this.keys[e.keyCode] = true }) document.addEventListener('keyup' , e => { this.keys[e.keyCode] = false }) } } ",sizeProjection 250," import hre from ""hardhat""; async function Deployer( [MASK] :string){ try{ const ContractFactory = await hre.ethers.getContractFactory( [MASK] ); const risc0VerifierContractAddressSepolia = ""0x925d8331ddc0a1F0d96E68CF073DFE1d92b69187""; const risczeroVerifierContractAddressHole = ""0xf70aBAb028Eb6F4100A24B203E113D94E87DE93C"" ; const FibonachiContract = await ContractFactory.deploy(risc0VerifierContractAddressSepolia,825) await FibonachiContract.deploymentTransaction()?.wait(3) const FibonachiContractAddress = await FibonachiContract.getAddress(); try { await hre.run(""verify:verify"", { address : FibonachiContractAddress, constructorArguments : [risc0VerifierContractAddressSepolia,825] }) }catch(err){ console.error(""Error during verification:"",err); process.exit(1); } console.log(""Contract deployed to : "",await FibonachiContract.getAddress()); }catch(err){ console.error(""Error during deployment:"", err); process.exit(1); } } // After deploy // running script // npx hardhat run scripts/deploy.ts --network holesky // npx hardhat run scripts/deployFibonachiVerifier.ts --network holesky // contract address : 0xF9CB9306C7158978b18BbEfDFfa98852535bd5A4 // Contract address sepolia : 0x4bE39ec6c925954A5Bc95A830814821Ab0E6761D Deployer(""FibonachiVerifier"");",contractName 251,"import Clang from ""./clang.js""; import LLD from ""./lld.js""; export { Clang, LLD }; export type FileList = { [fileName: string]: string | ArrayBuffer }; export type CompilationJob = { source: string; fileName: string; flags: string[]; extraFiles?: FileList; }; export type CompilationResult = { compileOutput: string; module: WebAssembly.Module | null; }; export type Invocation = { compilerArgs: string[]; compilerArtifact: string; linkerArgs: string[]; linerArtifact: string; }; export function* tarContents( contents: ArrayBuffer ): Generator<{ name: string; content: Uint8Array }> { const data = new Uint8Array(contents); let offset = 0; const textDecoder = new TextDecoder(""utf-8""); while (offset + 512 <= data.length) { const header = data.slice(offset, offset + 512); const name = textDecoder.decode(header.slice(0, 100)).replace(/\0.*$/, """"); if (!name) break; // two empty blocks mean end of archive const sizeOctal = textDecoder .decode(header.slice(124, 136)) .replace(/\0.*$/, """") .trim(); const size = parseInt(sizeOctal, 8) || 0; const contentStart = offset + 512; const contentEnd = contentStart + size; const content = data.slice(contentStart, contentEnd); yield { name, content }; // advance to next file, rounding up to next 512 bytes const totalSize = 512 + Math.ceil(size / 512) * 512; offset += totalSize; } } export function setUpSysroot( module: any, tar: ArrayBuffer, extraFiles?: FileList ) { for (const { name, content } of tarContents(tar)) { if (name.endsWith(""/"")) continue; const dirName = name.split(""/"").slice(0, -1).join(""/""); if (!module.FS.analyzePath(dirName).exists) { module.FS.mkdirTree(dirName); } module.FS.writeFile(name, content); } if (extraFiles) { for (const [name, content] of Object.entries(extraFiles)) { const dirName = name.split(""/"").slice(0, -1).join(""/""); module.FS.mkdirTree(dirName); if (typeof content === ""string"") { module.FS.writeFile(name, content); } else { module.FS.writeFile(name, new Uint8Array(content)); } } } } // TODO: Executing the Clang driver just to get the flags is expensive (~80ms). // Reimplement the Clang driver's most common options in TS. export async function getCompilerInvocation( inputName: string, [MASK] : string, flags: string[] ): Promise { let stderr = """"; const clang = await Clang({ thisProgram: ""clang++"", printErr: (data: string) => { stderr += data + ""\n""; }, }); clang.FS.writeFile(inputName, [MASK] ); // Set up a dummy sysroot so the compiler driver finds the paths it needs. clang.FS.mkdirTree(""/lib/wasm32-wasi""); clang.FS.mkdirTree(""/include/c++/v1""); clang.FS.writeFile(""/lib/wasm32-wasi/crt1-command.o"", new Uint8Array(0)); clang.FS.writeFile(""/lib/wasm32-wasi/crt1-reactor.o"", new Uint8Array(0)); const ret = clang.callMain([inputName, ...flags, ""-###""]); if (ret !== 0) { console.error(stderr); throw new Error(`Clang driver failed with code ${ret}`); } const lines = stderr.split(""\n""); const getArgs = (key: string) => { const line = lines.find((line) => line.includes(key)) ?? """"; const args = line .match(/""([^""]*)""/g)! .map((s) => s.slice(1, -1)) .slice(1); const oIndex = args.findIndex((arg) => arg === ""-o""); return { args, outputFileName: args[oIndex + 1] }; }; const cc1line = getArgs(""-cc1""); const linkerLine = getArgs(""wasm-ld""); return { compilerArgs: cc1line.args, compilerArtifact: cc1line.outputFileName, linkerArgs: linkerLine.args, linerArtifact: linkerLine.outputFileName, }; } export async function compile({ source, fileName, flags, extraFiles, }: CompilationJob): Promise { let stderr = """"; const clangPromise = Clang({ thisProgram: ""clang++"", printErr: (data: string) => { stderr += data + ""\n""; }, }); const lldPromise = LLD({ thisProgram: ""wasm-ld"", printErr: (data: string) => { stderr += data + ""\n""; }, }); const sysroot = await ( await fetch(new URL(""sysroot.tar"", import.meta.url).href) ).arrayBuffer(); const invocation = await getCompilerInvocation(fileName, source, flags); const clang = await clangPromise; clang.FS.writeFile(fileName, source); setUpSysroot(clang, sysroot, extraFiles); let exitCode = clang.callMain(invocation.compilerArgs); if (exitCode !== 0) { return { compileOutput: stderr, module: null, }; } const binary = clang.FS.readFile(invocation.compilerArtifact, { encoding: ""binary"", }); const lld = await lldPromise; lld.FS.writeFile(invocation.compilerArtifact, binary); setUpSysroot(lld, sysroot, extraFiles); exitCode = lld.callMain(invocation.linkerArgs); if (exitCode !== 0) { return { compileOutput: stderr, module: null, }; } const output: Uint8Array = lld.FS.readFile(invocation.linerArtifact, { encoding: ""binary"", }); return { compileOutput: stderr, module: await WebAssembly.compile(output), }; } const compatibleWithPCH = (flags: string[]) => flags.includes(""-O2"") && flags.includes(""-std=c++20"") && flags.includes(""-fno-exceptions""); // FIXME: Make PCH flags configurable. export const getPrecompiledHeader = async (flags: string[]) => compatibleWithPCH(flags) ? (await fetch(new URL(""stdc++.h.pch"", import.meta.url).href)).arrayBuffer() : null; ",inputFile 252,"import {Service} from ""typedi""; import {LoggingService} from ""./logging-service""; import * as fs from 'fs'; import * as path from 'path'; @Service() export class FileSystemHelper { constructor(private readonly _loggingService: LoggingService) { } createFolderIfNotExist(fullPath: string): boolean { if (!fs.existsSync(fullPath)) { this._loggingService.trace(`- Creating folder '${fullPath}' ...`); fs.mkdirSync(fullPath); return true; } return false; } writeToFile(data: string, stringify: boolean, [MASK] : string, relativeOutFolderPath: string): void { const fullPath = path.join(__dirname, `${relativeOutFolderPath}/${ [MASK] }`); this._loggingService.trace(`Write to file '${fullPath}' ...`); fs.writeFileSync(fullPath, stringify ? JSON.stringify(data, null, 2) : data); } writeToFileA(data: string, stringify: false, absoluteFolderPathName: string): void; writeToFileA(data: object, stringify: true, absoluteFolderPathName: string): void; writeToFileA(data: string | object, stringify: boolean, absoluteFolderPathName: string): void { this._loggingService.trace(`Write to file '${absoluteFolderPathName}' ...`); fs.writeFileSync(absoluteFolderPathName, stringify ? JSON.stringify(data, null, 2) : data as string); } } ",fileName 253,"/* eslint-disable @typescript-eslint/no-unused-vars */ import { Address, isSome, IAccountMeta, IAccountSignerMeta, IInstruction, Option, TransactionSigner, } from ""@solana/kit"" /* eslint-enable @typescript-eslint/no-unused-vars */ import BN from ""bn.js"" // eslint-disable-line @typescript-eslint/no-unused-vars import * as borsh from ""@coral-xyz/borsh"" // eslint-disable-line @typescript-eslint/no-unused-vars import { borshAddress } from ""../utils"" // eslint-disable-line @typescript-eslint/no-unused-vars import * as types from ""../types"" // eslint-disable-line @typescript-eslint/no-unused-vars import { PROGRAM_ID } from ""../programId"" export interface SwapUnevenVaultsArgs { targetLimitBps: BN } export interface SwapUnevenVaultsAccounts { actionsAuthority: TransactionSigner strategy: Address globalConfig: Address tokenAVault: Address tokenBVault: Address tokenAMint: Address tokenBMint: Address baseVaultAuthority: Address pool: Address position: Address raydiumPoolConfigOrBaseVaultAuthority: Address poolTokenVaultA: Address poolTokenVaultB: Address /** Payer must send this correctly. */ tickArray0: Address /** Payer must send this correctly. */ tickArray1: Address /** Payer must send this correctly. */ tickArray2: Address oracle: Address poolProgram: Address scopePrices: Address tokenInfos: Address tickArrayLower: Address tickArrayUpper: Address tokenATokenProgram: Address tokenBTokenProgram: Address memoProgram: Address tokenProgram: Address tokenProgram2022: Address instructionSysvarAccount: Address consensusAccount: Address eventAuthority: Option
} export const layout = borsh.struct([borsh.u64(""targetLimitBps"")]) export function swapUnevenVaults( args: SwapUnevenVaultsArgs, accounts: SwapUnevenVaultsAccounts, programAddress: Address = PROGRAM_ID ) { const keys: Array = [ { address: accounts.actionsAuthority.address, role: 3, signer: accounts.actionsAuthority, }, { address: accounts.strategy, role: 1 }, { address: accounts.globalConfig, role: 0 }, { address: accounts.tokenAVault, role: 1 }, { address: accounts.tokenBVault, role: 1 }, { address: accounts.tokenAMint, role: 0 }, { address: accounts.tokenBMint, role: 0 }, { address: accounts.baseVaultAuthority, role: 1 }, { address: accounts.pool, role: 1 }, { address: accounts.position, role: 1 }, { address: accounts.raydiumPoolConfigOrBaseVaultAuthority, role: 0 }, { address: accounts.poolTokenVaultA, role: 1 }, { address: accounts.poolTokenVaultB, role: 1 }, { address: accounts.tickArray0, role: 1 }, { address: accounts.tickArray1, role: 1 }, { address: accounts.tickArray2, role: 1 }, { address: accounts.oracle, role: 1 }, { address: accounts.poolProgram, role: 0 }, { address: accounts.scopePrices, role: 0 }, { address: accounts.tokenInfos, role: 0 }, { address: accounts.tickArrayLower, role: 0 }, { address: accounts.tickArrayUpper, role: 0 }, { address: accounts.tokenATokenProgram, role: 0 }, { address: accounts.tokenBTokenProgram, role: 0 }, { address: accounts.memoProgram, role: 0 }, { address: accounts.tokenProgram, role: 0 }, { address: accounts.tokenProgram2022, role: 0 }, { address: accounts.instructionSysvarAccount, role: 0 }, { address: accounts.consensusAccount, role: 0 }, isSome(accounts.eventAuthority) ? { address: accounts.eventAuthority.value, role: 0 } : { address: programAddress, role: 0 }, ] const identifier = Buffer.from([143, 212, 101, 95, 105, 209, 184, 1]) const [MASK] = Buffer.alloc(1000) const len = layout.encode( { targetLimitBps: args.targetLimitBps, }, [MASK] ) const data = Buffer.concat([identifier, [MASK] ]).slice(0, 8 + len) const ix: IInstruction = { accounts: keys, programAddress, data } return ix } ",buffer 254,"import type { API, Characteristic, DynamicPlatformPlugin, Logging, PlatformAccessory, PlatformConfig, Service } from 'homebridge'; import { SwitchAccessory } from './switch-accessory.js'; import { PLATFORM_NAME, PLUGIN_NAME } from './const.js'; import type { PushoverNotificationConfig } from './types.js'; import { PushoverClient } from './pushover-client.js'; export class PushoverNotificationPlatform implements DynamicPlatformPlugin { readonly Service: typeof Service; readonly Characteristic: typeof Characteristic; private readonly accessories: Map = new Map(); private readonly discoveredCacheUUIDs: string[] = []; constructor( readonly log: Logging, readonly config: PlatformConfig, readonly api: API, ) { this.Service = api.hap.Service; this.Characteristic = api.hap.Characteristic; if (!config.token) { this.log.error('Pushover API token must be configured'); return; } if (!config.user) { this.log.error('Pushover user key must be configured'); return; } this.log.debug('Finished initializing platform:', config.name); this.api.on('didFinishLaunching', () => { log.debug('Registering accessories...'); this.registerAccessories(); }); } configureAccessory(accessory: PlatformAccessory) { this.log.debug('Loading accessory from cache:', accessory.displayName); this.accessories.set(accessory.UUID, accessory); } private registerAccessories() { const config = this.config as PushoverNotificationConfig; const [MASK] = new PushoverClient(config.token, config.user, this.log); for (const message of config.messages) { const uuid = this.api.hap.uuid.generate(message.name); const existingAccessory = this.accessories.get(uuid); if (existingAccessory) { this.log.debug('Restoring existing accessory from cache:', existingAccessory.displayName); new SwitchAccessory(this, existingAccessory, [MASK] , message); } else { this.log.debug('Adding new accessory:', message.name); const accessory = new this.api.platformAccessory(message.name, uuid); new SwitchAccessory(this, accessory, [MASK] , message); this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory]); } this.discoveredCacheUUIDs.push(uuid); } for (const [uuid, accessory] of this.accessories) { if (!this.discoveredCacheUUIDs.includes(uuid)) { this.log.debug('Removing existing accessory from cache:', accessory.displayName); this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory]); } } } } ",pushoverClient 255,"import { Injectable } from '@angular/core'; import { Plugins, CameraResultType, Capacitor, FilesystemDirectory, CameraPhoto, CameraSource } from '@capacitor/core'; const {Camera, Filesystem, Storage} = Plugins; @Injectable({ providedIn: 'root' }) export class PhotoService { public photos: Photo[] = []; private PHOTO_STORAGE = 'photos'; constructor() { } public async addNewToGallery() { const [MASK] = await Camera.getPhoto( { resultType: CameraResultType.Uri, source: CameraSource.Camera, quality: 100 }); const savedImage = await this.savePicture( [MASK] ); this.photos.unshift(savedImage); Storage.set({ key: this.PHOTO_STORAGE, value: JSON.stringify(this.photos) }); } public async loadSaved() { const photoList = await Storage.get({key: this.PHOTO_STORAGE}); this.photos = JSON.parse(photoList.value) || []; for (let photo of this.photos){ const readFile = await Filesystem.readFile( { path: photo.filepath, directory: FilesystemDirectory.Data } ); photo.webviewPath = `data:image/jpeg;base64,${readFile.data}`; } } private async savePicture(cameraPhoto: CameraPhoto){ const base64Data = await this.readAsBase64(cameraPhoto); const fileName = new Date().getTime() + '.jpeg'; const savedFile = await Filesystem.writeFile({ path: fileName, data: base64Data, directory: FilesystemDirectory.Data }); return{ filepath: fileName, webviewPath: cameraPhoto.webPath }; } private async readAsBase64(cameraPhoto: CameraPhoto) { const response = await fetch(cameraPhoto.webPath); const blob = await response.blob(); return await this.convertBlobToBase64(blob) as string; } convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => { const reader = new FileReader(); reader.onerror = reject; reader.onload = () => { resolve(reader.result); }; return reader.readAsDataURL(blob); }) } export interface Photo{ filepath: string; webviewPath: string; } ",capturedPhoto 256,"import { BrowserHeaders } from ""../src/BrowserHeaders""; import { getHeaderValues } from ""../src/util""; const { deepEqual, ok } = require(""assert""); declare function describe(name: string, test: () => void): void; declare function it(name: string, test: () => void): void; // Declare that there is a global property named ""Headers"" declare const Headers: any; interface Map { clear(): void; delete(key: K): boolean; forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; get(key: K): V | undefined; has(key: K): boolean; set(key: K, value?: V): this; readonly size: number; } interface MapConstructor { new (): Map; new (entries?: [K, V][]): Map; readonly prototype: Map; } declare const Map: MapConstructor; describe(""browser-headers"", () => { it(""should parse a CLRF-delimited header string"", () => { const browserHeaders = new BrowserHeaders(""keya: one\r\nkeyb: Two\r\nkeyC: three""); deepEqual(browserHeaders.get(""keyA""), [""one""]); deepEqual(browserHeaders.get(""keyB""), [""Two""]); deepEqual(browserHeaders.get(""keyC""), [""three""]); }); it(""should construct from an object"", () => { const browserHeaders = new BrowserHeaders({ ""keyA"": [""one"", ""Two""], ""keyb"": ""three"" }); deepEqual(browserHeaders.get(""keyA""), [""one"", ""Two""]); deepEqual(browserHeaders.get(""keyB""), [""three""]); }); it(""should construct from an instance of BrowserHeaders"", () => { const [MASK] = new BrowserHeaders({ ""keyA"": [""one"", ""Two""], ""keyb"": ""three"" }); const browserHeaders = new BrowserHeaders( [MASK] ); deepEqual(browserHeaders.get(""keyA""), [""one"", ""Two""]); deepEqual(browserHeaders.get(""keyB""), [""three""]); }); it(""should retain multiple values for a single key"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.append(""keyA"", ""one""); browserHeaders.append(""keyA"", ""Two""); deepEqual(browserHeaders.get(""keyA""), [""one"", ""Two""]); }); describe(""set"", () => { it(""should set an individual value"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.set(""keyA"", ""one""); deepEqual(browserHeaders.get(""keyA""), [""one""]); browserHeaders.set(""keyA"", ""Two""); deepEqual(browserHeaders.get(""keyA""), [""Two""]); }); it(""should set an array of values"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.set(""keyA"", [""one"", ""Two""]); deepEqual(browserHeaders.get(""keyA""), [""one"", ""Two""]); browserHeaders.set(""keyA"", [""three"", ""four""]); deepEqual(browserHeaders.get(""keyA""), [""three"", ""four""]); }); }); describe(""append"", () => { it(""should append an individual value"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.append(""keyA"", ""one""); browserHeaders.append(""keyA"", ""Two""); deepEqual(browserHeaders.get(""keyA""), [""one"", ""Two""]); }); it(""should append an array of values"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.append(""keyA"", [""one"", ""Two""]); browserHeaders.append(""keyA"", [""three"", ""four""]); deepEqual(browserHeaders.get(""keyA""), [""one"", ""Two"", ""three"", ""four""]); }); }); describe(""appendFromString"", () => { it(""should parse the headers string"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.appendFromString(""keya: one\r\nkeyb: Two\r\nkeyC: three""); deepEqual(browserHeaders.get(""keyA""), [""one""]); deepEqual(browserHeaders.get(""keyB""), [""Two""]); deepEqual(browserHeaders.get(""keyC""), [""three""]); }); it(""should append to existing values"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.append(""keyA"", [""one"", ""Two""]); browserHeaders.append(""keyB"", ""four""); browserHeaders.appendFromString(""keya: three\r\nkeyb: Five\r\nkeyC: six""); deepEqual(browserHeaders.get(""keyA""), [""one"", ""Two"", ""three""]); deepEqual(browserHeaders.get(""keyb""), [""four"", ""Five""]); deepEqual(browserHeaders.get(""keyC""), [""six""]); }); }); describe(""delete"", () => { it(""should remove a key"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.append(""keyA"", [""one"", ""Two""]); deepEqual(browserHeaders.get(""keyA""), [""one"", ""Two""]); browserHeaders.delete(""keyA""); deepEqual(browserHeaders.get(""keyA""), []); }); it(""should not throw an error when removing a key that is not present"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.delete(""keyA""); }); it(""should remove a value within a key"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.append(""keyA"", [""one"", ""Two"", ""three""]); deepEqual(browserHeaders.get(""keyA""), [""one"", ""Two"", ""three""]); browserHeaders.delete(""keyA"", ""Two""); deepEqual(browserHeaders.get(""keyA""), [""one"", ""three""]); }); it(""should not throw an error when removing a value of a key that is not present"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.delete(""keyA"", ""Two""); }); it(""should not throw an error when removing a non-existant value of a key that is present"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.append(""keyA"", [""one"", ""three""]); browserHeaders.delete(""keyA"", ""Two""); }); }); describe(""has"", () => { it(""should return true for an existing key"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.append(""keyA"", [""one"", ""Two""]); deepEqual(browserHeaders.get(""keyA""), [""one"", ""Two""]); deepEqual(browserHeaders.has(""keyA""), true); }); it(""should return false for a non-existing key"", () => { const browserHeaders = new BrowserHeaders(); deepEqual(browserHeaders.has(""keyA""), false); }); it(""should return true for an existing value"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.append(""keyA"", [""one"", ""Two""]); deepEqual(browserHeaders.has(""keyA"", ""Two""), true); }); it(""should return false for a non-existing value within a key"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.append(""keyA"", [""one"", ""Two""]); deepEqual(browserHeaders.has(""keyA"", ""three""), false); }); it(""should return false for a value within a non-existant key"", () => { const browserHeaders = new BrowserHeaders(); deepEqual(browserHeaders.has(""keyA"", ""three""), false); }); it(""should return false for a key that was deleted"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.append(""keyA"", [""one"", ""Two""]); browserHeaders.delete(""keya""); deepEqual(browserHeaders.has(""keyA""), false); }); it(""should return false for a key that was deleted by emptying it's keys"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.append(""keyA"", [""one"", ""Two""]); browserHeaders.delete(""keya"", ""one""); browserHeaders.delete(""keya"", ""Two""); deepEqual(browserHeaders.has(""keyA""), false); }); }); describe(""forEach"", () => { it(""should append an individual value"", () => { const browserHeaders = new BrowserHeaders(); browserHeaders.append(""keyA"", [""one"", ""Two""]); browserHeaders.append(""keyB"", [""three"", ""four""]); const visited: string[] = []; browserHeaders.forEach((key: string, values: string[]) => { visited.push(key + ""."" + values.join("","")); }); deepEqual(visited, [ ""keya.one,Two"", ""keyb.three,four"", ]); }); }); // Can only test the Headers compatibility if there is a Headers class in this browser if (typeof Headers !== ""undefined"") { describe(""Headers-compatibility"", () => { it(""should construct a BrowserHeaders from a Headers instance and not split the values by default"", () => { const headers = new Headers(); headers.append(""keyA"", ""one, Two""); headers.append(""keyB"", ""three""); const browserHeaders = new BrowserHeaders(headers); deepEqual(browserHeaders.get(""keyA""), [""one, Two""]); deepEqual(browserHeaders.get(""keyB""), [""three""]); }); it(""should construct a BrowserHeaders from a Headers instance and split the values if specified (comma)"", () => { const headers = new Headers(); headers.append(""keyA"", ""one,Two""); headers.append(""keyB"", ""three""); const browserHeaders = new BrowserHeaders(headers, {splitValues: true}); deepEqual(browserHeaders.get(""keyA""), [""one"", ""Two""]); deepEqual(browserHeaders.get(""keyB""), [""three""]); }); it(""should construct a BrowserHeaders from a Headers instance and split the values if specified (comma + space)"", () => { const headers = new Headers(); headers.append(""keyA"", ""one, Two""); headers.append(""keyB"", ""three""); const browserHeaders = new BrowserHeaders(headers, {splitValues: true}); deepEqual(browserHeaders.get(""keyA""), [""one"", ""Two""]); deepEqual(browserHeaders.get(""keyB""), [""three""]); }); /* This test uses separate append calls for `keyA`, which in some browsers joins the strings with a comma. By setting splitValues to true, this test checks that this browser-specific detail can be abstracted. */ it(""should construct a BrowserHeaders from a Headers instance and split the values if specified - separate appends"", () => { const headers = new Headers(); headers.append(""keyA"", ""one""); headers.append(""keya"", ""Two""); headers.append(""keyB"", ""three""); const browserHeaders = new BrowserHeaders(headers, {splitValues: true}); deepEqual(browserHeaders.get(""keyA""), [""one"", ""Two""]); deepEqual(browserHeaders.get(""keyB""), [""three""]); }); describe(""toHeaders"", () => { it(""should return a Headers instance that contains the same headers"", () => { const browserHeaders = new BrowserHeaders({ ""keyA"": [""one"", ""Two""], ""keyB"": ""three"" }); const headers = browserHeaders.toHeaders(); const keyA = getHeaderValues(headers, ""keyA""); // The value of keyA is one of [""one"", ""Two""], [""one,Two""] or [""one, Two""] depending on whether or not the // `.append` function of the current browser's Header class concatenates and what it joins by. // Join the array by "", "" so that the value(s) should now be either separated by "", "" or just "","" const keyAString = keyA.join("", ""); ok(keyAString === ""one, Two"" || keyAString === ""one,Two""); deepEqual(getHeaderValues(headers, ""keyB""), [""three""]); }); it(""should be compatible with fetch"", () => { const browserHeaders = new BrowserHeaders({ ""keyA"": [""one"", ""Two""], ""keyB"": ""three"" }); const headers = browserHeaders.toHeaders(); const promise = fetch(""http://127.0.0.1"", { headers: headers, }); ok(promise, ""promise is returned""); }); }); }); } // Can only test the Map compatibility if there is a Map class in this browser if (typeof Map !== ""undefined"") { describe(""Headers-compatibility"", () => { it(""should construct a BrowserHeaders from a Map"", () => { const map = new Map(); map.set(""keyA"", [""one"", ""Two""]); map.set(""keyB"", ""three""); const browserHeaders = new BrowserHeaders(map); deepEqual(browserHeaders.get(""keyA""), [""one"", ""Two""]); deepEqual(browserHeaders.get(""keyB""), [""three""]); }); }); } });",toInit 257,"import Fastify from ""fastify""; import alertRoutes from ""../feature/alert/routes/alert.routes""; import cors from ""@fastify/cors""; import helmet from ""@fastify/helmet""; jest.mock(""fastify""); jest.mock(""@fastify/cors""); jest.mock(""@fastify/helmet""); jest.mock(""../feature/alert/routes/alert.routes""); jest.mock(""../feature/alert/service/priceCheck.service""); jest.mock(""../core/config"", () => ({ config: { nodeEnv: ""test"", database: { host: ""localhost"", port: 5432, username: ""test"", password: """", database: ""test_db"", }, }, getLogLevel: jest.fn().mockReturnValue(""silent""), })); describe(""App Initialization"", () => { // would write mocked types but due to time constraints, using any // eslint-disable-next-line @typescript-eslint/no-explicit-any let mockApp: any; // eslint-disable-next-line @typescript-eslint/no-explicit-any let buildApp: any; beforeEach(() => { jest.clearAllMocks(); // Set up the mock Fastify instance mockApp = { register: jest.fn().mockReturnThis(), get: jest.fn().mockReturnThis(), setNotFoundHandler: jest.fn().mockReturnThis(), setErrorHandler: jest.fn().mockReturnThis(), addHook: jest.fn().mockReturnThis(), decorate: jest.fn().mockReturnThis(), }; (Fastify as unknown as jest.Mock).mockReturnValue(mockApp); // Dynamically import the app to ensure our mocks are set up first jest.isolateModules(async () => { buildApp = (await import(""../app"")).default; }); }); it(""should create a Fastify instance with logger configuration"", () => { // given / when buildApp(); // then expect(Fastify).toHaveBeenCalledWith( expect.objectContaining({ logger: expect.objectContaining({ level: ""silent"", }), }), ); }); it(""should register security plugins"", () => { // given / when buildApp(); // then expect(mockApp.register).toHaveBeenCalledWith(cors); expect(mockApp.register).toHaveBeenCalledWith(helmet); }); it(""should define a health check endpoint"", () => { // given / when buildApp(); // then expect(mockApp.get).toHaveBeenCalledWith( ""/prices-api/v1/health"", expect.any(Function), ); }); it(""should register alert routes with correct prefix"", () => { // given / when buildApp(); // then expect(mockApp.register).toHaveBeenCalledWith(alertRoutes, { prefix: ""/prices-api/v1/alerts"", }); }); it(""should set up error handlers"", () => { // given / when buildApp(); // then expect(mockApp.setNotFoundHandler).toHaveBeenCalledWith( expect.any(Function), ); expect(mockApp.setErrorHandler).toHaveBeenCalledWith(expect.any(Function)); }); it(""should set up onReady hook to initialize price check service"", () => { // When buildApp(); // Then expect(mockApp.addHook).toHaveBeenCalledWith( ""onReady"", expect.any(Function), ); }); it(""should set up onClose hook for cleanup"", () => { // When buildApp(); // Then expect(mockApp.addHook).toHaveBeenCalledWith( ""onClose"", expect.any(Function), ); }); // Test the health check endpoint handler it(""should return correct response from health check endpoint"", async () => { // given buildApp(); // Get the health check handler function const healthCheckHandlerCall = mockApp.get.mock.calls.find( // eslint-disable-next-line @typescript-eslint/no-explicit-any (call: any) => call[0] === ""/prices-api/v1/health"", ); const healthCheckHandler = healthCheckHandlerCall[1]; // when const response = await healthCheckHandler(); // then expect(response).toEqual({ status: ""OK"", message: ""API is up and running"", }); }); it(""should handle 404 errors correctly"", () => { // given buildApp(); const notFoundHandler = mockApp.setNotFoundHandler.mock.calls[0][0]; const request = {}; const [MASK] = { status: jest.fn().mockReturnThis(), send: jest.fn(), }; // when notFoundHandler(request, [MASK] ); // then expect( [MASK] .status).toHaveBeenCalledWith(404); expect( [MASK] .send).toHaveBeenCalledWith({ message: ""Resource not found"" }); }); }); ",reply 258,"import { CreateChatTokenResponse } from '@aws-sdk/client-ivschat'; import { chatSdk, ddbSdk } from '@Lambda/sdk'; import { APIException, CreateChatTokenBody } from '@Lambda/types'; import { createErrorResponse, createSuccessResponse, getUserData } from '@Lambda/utils'; import { APIGatewayProxyResultV2, APIGatewayProxyWithCognitoAuthorizerEvent } from 'aws-lambda'; async function handler( event: APIGatewayProxyWithCognitoAuthorizerEvent ): Promise { const { meetingId }: CreateChatTokenBody = JSON.parse(event.body || '{}'); const [MASK] = getUserData(event); let response: CreateChatTokenResponse; console.info('[EVENT]', JSON.stringify(event)); // Check required input if (!meetingId) { return createErrorResponse({ code: 400, name: APIException.BAD_INPUT, message: 'Missing meetingId' }); } try { const meetingRecord = await ddbSdk.getMeetingRecord(meetingId); if (!meetingRecord) { return createErrorResponse({ code: 404, name: APIException.MEETING_NOT_FOUND, message: `No meeting exists with the meeting ID or alias ""${meetingId}""` }); } console.info('Found meeting record', meetingRecord); response = await chatSdk.createToken(meetingRecord.chatRoomArn, [MASK] ); } catch (error) { console.error(error); return createErrorResponse({ message: 'Failed to create chat token.' }); } console.info('[RESPONSE]', response); return createSuccessResponse({ body: response }); } export { handler }; ",userData 259,"import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms'; import { MatSnackBar } from '@angular/material/snack-bar'; import { environment } from '../environment'; import { FileService } from '../file.service'; import { Targets } from '../models/Target'; import { TargetService } from '../target.service'; @Component({ selector: 'app-targets', templateUrl: './targets.component.html', styleUrls: ['./targets.component.css'] }) export class TargetsComponent implements OnInit { targetForm: FormGroup; selectedTarget: any; targetList: Targets; constructor(private http: HttpClient, private targetService: TargetService, private formBuilder: FormBuilder, private fileService: FileService, private snackbar: MatSnackBar) { } ngOnInit(): void { this.targetForm = this.formBuilder.group({ targetName: ['', Validators.required], address: ['', Validators.required], ca: ['', Validators.required], cakey: ['', Validators.required], }); this.selectedTarget = {}; this.getTargets(); } getTargets(): void { this.targetService.getTargets().subscribe(targets => { if (targets != null) { this.targetList = targets; } else { this.targetList = {}; } }); } setTarget(targetForm): void { this.http.post(`${environment.apiUrl}/target/${targetForm.targetName}`, targetForm).subscribe( (res) => { this.targetList[targetForm.targetName] = { address: targetForm.address, ca: targetForm.ca, cakey: targetForm.cakey, }; this.selectedTarget = this.targetList[targetForm.targetName]; this.snackbar.open(""Saved"", """", {duration: 2000}); }, (error) => console.error(error), ); } deleteTarget(): void { let name = this.targetForm.get(""targetName"").value; this.fileService.deleteFile(this.selectedTarget.ca).subscribe((res) => { console.log(res); }, error => console.error(error)); this.fileService.deleteFile(this.selectedTarget.cakey).subscribe((res) => { console.log(res); }, error => console.error(error)); this.targetService.delete(name).subscribe(res => { this.selectedTarget = {}; this.targetForm.reset(); delete this.targetList[name]; this.snackbar.open(""Deleted"", """", {duration: 2000}); }, error => console.error(error)) } setSelectedTarget(targetName: string): void { this.selectedTarget = this.targetList[targetName]; if (this.selectedTarget === undefined) { this.selectedTarget = {}; this.targetForm.reset(); return; } this.targetForm.setValue({ targetName, address: this.selectedTarget.address, ca: this.selectedTarget.ca, cakey: this.selectedTarget.cakey, }); } addCa( [MASK] : string): void { this.targetForm.patchValue({ ca: [MASK] , }); } addCaKey(keyFileName: string): void { this.targetForm.patchValue({ cakey: keyFileName, }); } get targetName(): AbstractControl { return this.targetForm.get('targetName'); } get targetAddress(): AbstractControl { return this.targetForm.get('address'); } } ",caFileName 260,"import { use, expect, assert } from 'chai' import { ethers } from ""ethers"" import { deployContract, solidity } from 'ethereum-waffle' import { waffle } from ""@nomiclabs/buidler""; // The actual contract import DKG from ""../build/DKG.json"" use(solidity); describe('DKG', () => { const provider = waffle.provider; const [deployer, ...participants] = provider.getWallets(); const timeTravel = async (blocks: number) => { for (let i = 0; i < blocks; i++) { await provider.send('evm_mine', []) } } // Each phase's data is just an opaque blob of data from the smart contract's // perspective, so we'll just use a dummy data object const data = ""0x2222222222222222222222222222222222222222222222222222222222222222"" // Each phase lasts 30 blocks const PHASE_DURATION = 30; const THRESHOLD = 3; let dkg: ethers.Contract; beforeEach(async () => { dkg = await deployContract(deployer, DKG, [THRESHOLD, PHASE_DURATION]); await dkg.allowlist(participants[0].address) await dkg.allowlist(participants[1].address) }) describe('Whitelist', async () => { it('only owner can allowlist', async () => { // non-owner user tries to allowlist a sybil copy of them dkg = dkg.connect(participants[0]); await expect(dkg.allowlist(participants[2].address)).revertedWith(""only owner may allowlist users"") }) it('owner cannot allowlist twice', async () => { await expect(dkg.allowlist(participants[0].address)).revertedWith(""user is already allowlisted"") }) it('cannot allowlist once started', async () => { await dkg.start() await expect(dkg.allowlist(participants[2].address)).revertedWith(""DKG has already started"") }); }) describe('Registration', async () => { it('participants can register', async () => { dkg = dkg.connect(participants[0]); await dkg.register(data) }) it('participants cannot register if not allowlisted', async () => { dkg = dkg.connect(participants[2]); await expect(dkg.register(data)).revertedWith(""user is not allowlisted or has already registered"") }) it('participants cannot register twice', async () => { dkg = dkg.connect(participants[0]); await dkg.register(data) await expect(dkg.register(data)).revertedWith(""user is not allowlisted or has already registered"") // user cannot try to inflate the registrations array with 0-length registrations await expect(dkg.register(""0x"")).revertedWith(""user is not allowlisted or has already registered"") }) it('cannot register once started', async () => { // user is allowlisted but they dont' register in time await dkg.allowlist(participants[2].address) await dkg.start() dkg = dkg.connect(participants[2]); await expect(dkg.register(data)).revertedWith(""DKG has already started"") }); it('only owner can start the DKG', async () => { await expect(dkg.connect(participants[0]).start()).revertedWith(""only owner may start the DKG"") }); it('cannot publish if not registered', async () => { expect(dkg.connect(participants[1]).publish(data)).revertedWith(""you are not registered!""); }) }) it('e2e', async() => { const [MASK] = ""0x123""; await dkg.connect(participants[0]).register( [MASK] ) const pubkey2 = ""0x456""; await dkg.connect(participants[1]).register(pubkey2) expect(await dkg.inPhase()).to.equal(0); await dkg.start() expect(await dkg.inPhase()).to.equal(1); // only the second participant publishes their shares const my_shares = ""0x123456""; await dkg.connect(participants[1]).publish(my_shares) const shares = await dkg.getShares() expect(shares[0]).to.equal(""0x"") expect(shares[1]).to.equal(my_shares) await timeTravel(PHASE_DURATION) expect(await dkg.inPhase()).to.equal(2); // only the second participant publishes their responses const my_responses = ""0x234567""; await dkg.connect(participants[1]).publish(my_responses) const responses = await dkg.getResponses() expect(responses[0]).to.equal(""0x"") expect(responses[1]).to.equal(my_responses) await timeTravel(PHASE_DURATION) expect(await dkg.inPhase()).to.equal(3); // only the second participant publishes their justifications const my_justifications = ""0x345678""; await dkg.connect(participants[1]).publish(my_justifications) const justifications = await dkg.getJustifications() expect(justifications[0]).to.equal(""0x"") expect(justifications[1]).to.equal(my_justifications) await timeTravel(PHASE_DURATION) await expect(dkg.inPhase()).revertedWith(""VM Exception while processing transaction: revert DKG Ended"") }) describe('Shares', async () => { beforeEach(async () => { dkg = dkg.connect(participants[0]) await dkg.register(data) await dkg.connect(deployer).start() }) it('publishes to shares', async () => { await dkg.publish(data) const shares = await dkg.getShares() expect(shares[0]).to.equal(data) const responses = await dkg.getResponses() expect(responses[0]).to.equal(""0x""); const justifications = await dkg.getJustifications() expect(justifications[0]).to.equal(""0x""); }) it('cannot publish to shares twice', async () => { await dkg.publish(data) await expect(dkg.publish(data)).revertedWith(""you have already published your shares"") }) }) describe('Responses', async () => { beforeEach(async () => { dkg = dkg.connect(participants[0]) await dkg.register(data) await dkg.connect(deployer).start() await timeTravel(PHASE_DURATION) }) it('publishes to responses', async () => { await dkg.publish(data) const responses = await dkg.getResponses() expect(responses[0]).to.equal(data) const shares = await dkg.getShares() expect(shares[0]).to.equal(""0x""); const justifications = await dkg.getJustifications() expect(justifications[0]).to.equal(""0x""); }) it('cannot publish twice', async () => { await dkg.publish(data) await expect(dkg.publish(data)).revertedWith(""you have already published your responses"") }) }) describe('Responses', async () => { beforeEach(async () => { dkg = dkg.connect(participants[0]) await dkg.register(data) await dkg.connect(deployer).start() await timeTravel(2 * PHASE_DURATION) }) it('publishes to justifications', async () => { await dkg.publish(data) const justifications = await dkg.getJustifications() expect(justifications[0]).to.equal(data) const shares = await dkg.getShares() expect(shares[0]).to.equal(""0x""); const responses = await dkg.getResponses() expect(responses[0]).to.equal(""0x""); }) it('cannot publish twice', async () => { await dkg.publish(data) await expect(dkg.publish(data)).revertedWith(""you have already published your justifications"") }) }) it('Phases are correct', async () => { expect(await dkg.inPhase()).to.equal(0); await dkg.start() expect(await dkg.inPhase()).to.equal(1); // we need to mine 1 extra block here for the phase to change await timeTravel(PHASE_DURATION+ 1) expect(await dkg.inPhase()).to.equal(2); await timeTravel(PHASE_DURATION + 1) expect(await dkg.inPhase()).to.equal(3); await timeTravel(PHASE_DURATION + 1) await expect(dkg.inPhase()).revertedWith(""VM Exception while processing transaction: revert DKG Ended"") }) it('Ended', async () => { dkg = dkg.connect(participants[0]) await dkg.register(data) await dkg.connect(deployer).start() await timeTravel(3 * PHASE_DURATION) await expect(dkg.publish(data)).revertedWith(""DKG has ended"") }) }) ",pubkey1 261,"import { Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { MatAutocompleteActivatedEvent } from '@angular/material/autocomplete'; import { MatIconRegistry } from '@angular/material/icon'; import { DomSanitizer } from '@angular/platform-browser'; import { Subject } from 'rxjs'; import { debounceTime, map, startWith } from 'rxjs/operators'; import { ShieldService } from './shield.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { loaded = false; filteredOptions: string[] = []; lookUpIcon = new Subject(); myControl = new FormControl(''); Math = Math; mode: 'material' | 'custom' = 'material'; customSvgFile: File | null = null; constructor( private _iconRegistry: MatIconRegistry, private domSanitizer: DomSanitizer, public shieldService: ShieldService ) { } ngOnInit(): void { this.lookUpIcon.pipe(debounceTime(250)).subscribe((iconLabel) => { this.customSvgFile = null; this.shieldService.svgAsString.next(''); this._lookUpIcon(iconLabel) }); this.shieldService.style.subscribe(() => this.lookUpIcon.next(this.shieldService.icon.value)); this.shieldService.version.subscribe(() => this.lookUpIcon.next(this.shieldService.icon.value)); this.myControl = new FormControl(this.shieldService.icon.value); this.myControl.valueChanges.pipe( startWith(''), debounceTime(200), map(value => this._filter(value)) ).subscribe((res) => { this.filteredOptions = res; }); this.myControl.valueChanges.subscribe((option) => { this.shieldService.version.next(this.shieldService.iconNameToVersion[option]?.toString?.()) this.lookUpIcon.next(option); }); this.shieldService.svgAsString.subscribe((svgString) => { this.mode = svgString === '' ? 'material' : 'custom'; }); this.lookUpIcon.next(this.shieldService.icon.value); } onAutoCompleteOptionActivation(event: MatAutocompleteActivatedEvent): void { const option = event.option?.value; this.shieldService.version.next(this.shieldService.iconNameToVersion[option]?.toString?.()) this.lookUpIcon.next(option); } private _filter(value: string) { const filterValue = value.toLowerCase(); return this.shieldService.materialIconNames.filter(option => option.toLowerCase().startsWith(filterValue)); } getMaterialUrl(): string { return `https://fonts.gstatic.com/s/i/${this.shieldService.namespace()}` } onUpload(event: Event): void { const files = (event.target as any).files; const file = files[0]; const reader = new FileReader(); reader.onload = ((e: any) => { const [MASK] = e.target.result.split('data:image/svg+xml;base64,')[1]; const svg = atob( [MASK] ); this.shieldService.svgAsString.next(svg); }); reader.readAsDataURL(file); } doesNotExist = new Set(); private _lookUpIcon(iconLabel: string): void { const url = `https://fonts.gstatic.com/s/i/${this.shieldService.style.value}/${iconLabel}/v${this.shieldService.version.value}/${this.shieldService.size.value}px.svg`; if (this.doesNotExist.has(url)) { return; } fetch(url).then((res) => { if (!res.ok) { this.doesNotExist.add(url) return; } this.shieldService.icon.next(iconLabel); this._iconRegistry.addSvgIconInNamespace( this.shieldService.namespace(), this.shieldService.icon.value, this.domSanitizer.bypassSecurityTrustResourceUrl(this.getMaterialUrl()) ); this.shieldService.iconRotation.next(this.shieldService.iconRotation.value); this.loaded = true; }); } randomInputs(): void { this.shieldService.primary.next(this.generateRandomColor()); this.shieldService.iconColor.next(this.generateRandomColor()); this.shieldService.secondary.next(this.generateRandomColor()); } generateRandomColor(): string { // https://css-tricks.com/snippets/javascript/random-hex-color/ return '#' + Math.floor(Math.random()*16777215).toString(16); } } ",encodedSVG 262,"import { HardhatRuntimeEnvironment } from ""hardhat/types""; import { DeployFunction } from ""hardhat-deploy/types""; interface ConstructorArgs { root: string; totalUsesPerConsumer: number; tokenAddress: string; voucherValue: number; } const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) { const { deployments, getNamedAccounts } = hre; const { deploy } = deployments; const { deployer } = await getNamedAccounts(); /* 1. Recover USDT from deployments */ const usdtDeployment = await deployments.get(""USDT""); const usdtAddress = usdtDeployment.address; console.log(""Using USDT deployed at: "", usdtAddress); console.log(""Vault deployer: "", deployer); /* 2. Deploy Vault */ const constructorArgs: ConstructorArgs = { root: ""0x7c051167362941338293b69a56e14425db2dd23de7cee321c504981379214fe0"", totalUsesPerConsumer: 1, tokenAddress: usdtAddress, voucherValue: 100, }; await deploy(""Vault"", { from: deployer, log: true, // bytes32 _merkleRoot, uint256 _totalUsesPerConsumer, address _tokenAddress, uint256 _voucherValue args: [constructorArgs.root, constructorArgs.totalUsesPerConsumer, constructorArgs.tokenAddress, constructorArgs.voucherValue], }); const [MASK] = await deployments.get(""Vault""); const vaultAddress = [MASK] .address; console.log(""Vault deployed at: "", vaultAddress, ""\n""); }; export default func; func.tags = [""all"", ""vault""]; func.dependencies = [""usdt""]; ",vaultDeployment 263,"import type { DynamicData, SyncData } from '../common'; // 优先发布图文 export async function DynamicDouban(data: SyncData) { const dynamicData = data.data as DynamicData; console.debug('DynamicDouban', data); // 辅助函数:等待元素出现 function waitForElement(selector: string, timeout = 10000): Promise { return new Promise((resolve, reject) => { const element = document.querySelector(selector); if (element) { resolve(element); return; } const observer = new MutationObserver(() => { const element = document.querySelector(selector); if (element) { resolve(element); observer.disconnect(); } }); observer.observe(document.body, { childList: true, subtree: true, }); setTimeout(() => { observer.disconnect(); reject(new Error(`Element with selector ""${selector}"" not found within ${timeout}ms`)); }, timeout); }); } // 填写内容 async function fillContent() { await waitForElement('textarea[id=""isay-cont""]'); await new Promise((resolve) => setTimeout(resolve, 1000)); const textarea = document.querySelector('#isay-cont') as HTMLTextAreaElement; if (textarea) { // 如果有标题,将标题和内容拼接 const fullContent = dynamicData.title ? `${dynamicData.title}\n\n${dynamicData.content}` : dynamicData.content; textarea.value = fullContent; textarea.dispatchEvent(new Event('input', { bubbles: true })); textarea.dispatchEvent(new Event('click', { bubbles: true })); } } // 上传图片 async function uploadFiles() { if (!dynamicData.images?.length) return; const [MASK] = document.querySelector('input[type=""file""]') as HTMLInputElement; if (! [MASK] ) { console.debug('未找到文件输入元素'); return; } const dataTransfer = new DataTransfer(); const files = dynamicData.images || []; for (let i = 0; i < files.length; i++) { if (i >= 8) { console.debug('最多上传8张图片'); break; } const fileInfo = files[i]; if (!fileInfo.type.startsWith('image/')) { console.debug('skip non-image file', fileInfo); continue; } try { console.debug('try upload file', fileInfo); const response = await fetch(fileInfo.url); const arrayBuffer = await response.arrayBuffer(); const file = new File([arrayBuffer], fileInfo.name, { type: fileInfo.type }); dataTransfer.items.add(file); } catch (error) { console.error('上传文件失败:', error); } } if (dataTransfer.files.length > 0) { [MASK] .files = dataTransfer.files; [MASK] .dispatchEvent(new Event('change', { bubbles: true })); [MASK] .dispatchEvent(new Event('input', { bubbles: true })); console.debug('文件上传操作完成'); await new Promise((resolve) => setTimeout(resolve, 5000)); } } // 发布动态 async function publishDynamic() { const sendButton = document.querySelector('#isay-submit') as HTMLButtonElement; if (sendButton) { if (data.isAutoPublish) { console.debug('sendButton clicked'); sendButton.click(); } } else { console.debug('未找到""发送""按钮'); } } // 主流程 try { await fillContent(); await uploadFiles(); await publishDynamic(); } catch (error) { console.error('发布动态失败:', error); } } ",fileInput 264,"import { get, post } from '$lib/api'; export type ModelLabel = { default: string | number; type: string; comment: string; required: boolean; }; export interface ModelOption { model: Record; trainer: Record; } export const getModelOptions = async () => { const res = await get('/lm/models/options'); return res.json() as Promise>; }; type ExternalConfig = { fork?: string; series: any }; export interface TrainedModel { name: string; checkpoints: string[]; config: ExternalConfig; } /** 获取以及训练完成的模型 */ export const getTrainedNetworks = async () => { const res = await get('/lm/models'); return res.json() as Promise; }; export interface ModelDetail { model_name: string; model_config: Record; external_config: ExternalConfig; } export const getModelDetail = async (model: string) => { const res = await get(`/lm/models/${model}`); return res.json() as Promise; }; export const getModelsOptions = async () => { const res = await get('/lm/models/options'); return res.json() as Promise<{ [key: string]: { model: any; trainer: any } }>; }; export const getTrainResources = async () => { const res = await get('/lm/train/resources'); return res.json() as Promise; }; export const getTrainCommand = async ( type: string, fork: string | null, resume: string | null, dataset: string, tokenizer: string, modelOption: any, trainerOption: any ) => { const res = await post(`/lm/model/train/command`, { type: type, fork: fork, resume: resume, dataset: dataset, tokenizer: tokenizer, m_conf: modelOption, t_conf: trainerOption }); return res.text() as Promise; }; export const startTrainModel = async ( type: string, fork: string | null, resume: string | null, dataset: string, tokenizer: string, modelOption: any, trainerOption: any ) => { const res = await post('/lm/v2/model/train/', { type: type, fork: fork, resume: resume, dataset: dataset, tokenizer: tokenizer, m_conf: modelOption, t_conf: trainerOption }); return res.json() as Promise; }; export const createForkNetwork = async ( name: string, [MASK] : string, modelOption: any, trainerOption: any ) => { const res = await post(`/lm/edit/init/${name}`, { model: [MASK] , m_conf: modelOption, t_conf: trainerOption }); return res.json() as Promise; }; ",modelType 265,"import NextAuth, {AuthOptions} from ""next-auth""; import Credentials from ""next-auth/providers/credentials""; import prismadb from ""@/lib/prismadb""; import { compare } from ""bcrypt""; import GithubProvider from ""next-auth/providers/github""; import GoogleProvider from ""next-auth/providers/google""; import { PrismaAdapter } from ""@next-auth/prisma-adapter""; export const authOptions: AuthOptions = { providers: [ GithubProvider({ clientId: process.env.GITHUB_ID || '', clientSecret: process.env.GITHUB_SECRET || '' }), GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID || '', clientSecret: process.env.GOOGLE_CLIENT_SECRET || '' }), Credentials({ id: ""credentials"", name: ""Credentials"", credentials: { email: { label: ""Email"", type: ""text"", }, pwd: { label: ""Password"", type: ""password"", } }, async authorize(credentials) { if (!credentials?.email || !credentials?.pwd) { console.log(""Credentials: "", credentials); throw new Error(""Emails and passwords are required, email: "" + credentials?.email + "" password: "" + credentials?.pwd ); } const user = await prismadb.user.findUnique({ where:{ email: credentials.email } }); if (!user || !user.hashedPassword) { throw new Error(""User not found""); } const [MASK] = await compare( credentials.pwd, user.hashedPassword ); if (! [MASK] ) { throw new Error(""Invalid email or password: "" + user.hashedPassword + "" "" + credentials.pwd); } return user; } }) ], pages:{ signIn: ""/auth"", }, debug: process.env.NODE_ENV === ""development"", adapter: PrismaAdapter(prismadb), session: { strategy: ""jwt"", }, jwt: { secret: process.env.NEXTAUTH_JWT_SECRET, }, secret: process.env.NEXTAUTH_SECRET, } export default NextAuth(authOptions);",isCorrectPassword 266,"import * as fs from 'fs'; import * as path from 'path'; import { Organization, getClient, getOrderer } from './client'; import config from './config'; const CHANNEL_1_PATH = './../ksachdeva-exp-channel-1.tx'; async function main() { const [MASK] = await getClient(Organization.ORG1); const orderer = await getOrderer( [MASK] ); // read in the envelope for the channel config raw bytes console.log('Reading the envelope from manually created channel transaction ..'); const envelope = fs.readFileSync(path.join(__dirname, CHANNEL_1_PATH)); // extract the configuration console.log('Extracting the channel configuration ..'); const channelConfig = [MASK] .extractChannelConfig(envelope); console.log('Signing the extracted channel configuration ..'); const signature = [MASK] .signChannelConfig(channelConfig); // prepare the request const channelRequest: ChannelRequest = { name: config.CHANNEL_NAME, config: channelConfig, signatures: [signature], orderer: orderer, txId: [MASK] .newTransactionID() }; console.log('Sending the request to create the channel ..'); const response = await [MASK] .createChannel(channelRequest); console.log(response); } main(); ",org1Client 267,"function escapeBrackets(text: string): string { const pattern = /(```[\S\s]*?```|`.*?`)|\\\[([\S\s]*?[^\\])\\]|\\\((.*?)\\\)/g; return text.replace( pattern, ( match: string, codeBlock: string | undefined, [MASK] : string | undefined, roundBracket: string | undefined, ): string => { if (codeBlock != null) { return codeBlock; } else if ( [MASK] != null) { return `$$${ [MASK] }$$`; } else if (roundBracket != null) { return `$${roundBracket}$`; } return match; }, ); } function escapeMhchem(text: string) { return text.replaceAll('$\\ce{', '$\\\\ce{').replaceAll('$\\pu{', '$\\\\pu{'); } export function preprocessLaTeX(content: string): string { const codeBlocks: string[] = []; content = content.replace(/(```[\s\S]*?```|`[^`\n]+`)/g, (match, code) => { codeBlocks.push(code); return `<>`; }); const latexExpressions: string[] = []; content = content.replace(/(\$\$[\s\S]*?\$\$|\\\[[\s\S]*?\\\]|\\.*\(?\\\))/g, (match) => { latexExpressions.push(match); return `<>`; }); content = content.replace(/\$(?=\d)/g, '\\$'); content = content.replace(/<>/g, (_, index) => latexExpressions[parseInt(index)]); content = content.replace(/<>/g, (_, index) => codeBlocks[parseInt(index)]); content = content.replace(/\u00B7/g, '\u22C5'); content = escapeBrackets(content); content = escapeMhchem(content); return content; } ",squareBracket 268,"import axios, { AxiosResponse } from ""axios""; import baseURL from ""./index""; //const baseURL: string | undefined = ""http://localhost/api""; const api = axios.create({ baseURL, }); export interface Stuff { id: number; name: string; price: number; img: string; type: string; rating: number; } export interface StuffInfo { id: number; stuff_id: number; title: string; description: string; } export interface StuffFilters { id: number; name: string; price: number; img: string; type_id: number; rating: number; stuffInfo: StuffInfo[]; } export const getAllStuff = async (): Promise => { try { const response: AxiosResponse = await api.get('/stuff'); return response.data; } catch (error) { console.error('Error fetching stuff:', error); throw error; } }; export const getBasketStuff = async (): Promise => { try { const response: AxiosResponse = await api.get('/stuff/basket',{ headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` } }); const basketStuffs = response.data; const stuffs = basketStuffs.map((basketStuff: any) => basketStuff.stuff); return stuffs; } catch (error) { console.error('Error fetching stuff:', error); throw error; } }; export const addToBusket = async (stuffId: number) => { try { await axios.post(`${baseURL}/add-to-busket`, { stuff_id: stuffId }, { headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` } }); alert('Товар добавлен в корзину'); } catch (error) { console.error('Ошибка при добавлении товара в корзину', error); alert('Не удалось добавить товар в корзину'); } }; export const removeFromBasket = async (stuffId: number) => { try { await axios.delete(`${baseURL}/remove-from-basket/${stuffId}`, { headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` } }); alert('Товар удален из корзины'); } catch (error) { console.error('Ошибка при удалении товара из корзины', error); alert('Не удалось удалить товар из корзины'); } window.location.reload(); }; export const getFilteredStuff = async ( [MASK] : any): Promise => { try { const response: AxiosResponse = await api.get('/stuff/filter', { params: [MASK] }); return response.data; } catch (error) { console.error('Error fetching filtered stuff:', error); throw error; } }; ",filters 269,"import type { RayHandler } from ""./RayHandler""; import { ShadowShader, WithoutShadowShader, GaussianShader, DiffuseShader, createShadowShader, createDiffuseShader, createWithoutShadowShader, createGaussianShader, } from ""./shaders""; import { VertexBufferObject } from ""./utils/VertexBufferObject""; import { FrameBuffer } from ""./utils/FrameBuffer""; import { lightSettings } from ""./settings""; export class LightMap { private shadowShader: ShadowShader; public frameBuffer: FrameBuffer; private vertBuffer: VertexBufferObject; private uvBuffer: VertexBufferObject; private pingPongBuffer: FrameBuffer; private rayHandler: RayHandler; private withoutShadowShader: WithoutShadowShader; private blurShader: GaussianShader; private diffuseShader: DiffuseShader; private gl: WebGLRenderingContext; public lightMapDrawingDisabled = false; public constructor(rayHandler: RayHandler, fboWidth: number, [MASK] : number) { this.rayHandler = rayHandler; this.gl = rayHandler.gl; this.vertBuffer = new VertexBufferObject(this.gl, this.gl.STATIC_DRAW, this.createVertices()); this.uvBuffer = new VertexBufferObject(this.gl, this.gl.STATIC_DRAW, this.createUvCoords()); if (fboWidth <= 0) fboWidth = 1; if ( [MASK] <= 0) [MASK] = 1; this.frameBuffer = new FrameBuffer(this.gl, fboWidth, [MASK] ); this.pingPongBuffer = new FrameBuffer(this.gl, fboWidth, [MASK] ); this.shadowShader = createShadowShader(this.gl); this.diffuseShader = createDiffuseShader(this.gl); this.withoutShadowShader = createWithoutShadowShader(this.gl); this.blurShader = createGaussianShader(this.gl, fboWidth, [MASK] , lightSettings.isDiffuse); } public render() { const needed = this.rayHandler.lightRenderedLastFrame > 0; if (this.lightMapDrawingDisabled) return; this.frameBuffer.bindTexture(); // at last lights are rendered over scene if (this.rayHandler.shadows) { const c = this.rayHandler.ambientLight; let shader = this.shadowShader; if (lightSettings.isDiffuse) { shader = this.diffuseShader; shader.use(); this.rayHandler.diffuseBlendFunc.apply(); shader.ambient.set(c.r, c.g, c.b, c.a); } else { shader.use(); this.rayHandler.shadowBlendFunc.apply(); shader.ambient.set(c.r * c.a, c.g * c.a, c.b * c.a, 1 - c.a); } // shader.setUniformi(""u_texture"", 0); this.renderTriangleFan(shader); } else if (needed) { this.rayHandler.simpleBlendFunc.apply(); this.withoutShadowShader.use(); // withoutShadowShader.setUniformi(""u_texture"", 0); this.renderTriangleFan(this.withoutShadowShader); } this.gl.disable(this.gl.BLEND); } public renderTriangleFan(shader: WithoutShadowShader | DiffuseShader | ShadowShader | GaussianShader) { this.vertBuffer.bind(); shader.a_position.enable(); shader.a_position.set(2, this.gl.FLOAT, false, 0, 0); this.vertBuffer.unbind(); this.uvBuffer.bind(); shader.a_texCoord.enable(); shader.a_texCoord.set(2, this.gl.FLOAT, false, 0, 0); this.uvBuffer.unbind(); this.gl.drawArrays(this.gl.TRIANGLE_FAN, 0, 4); shader.a_position.disable(); shader.a_texCoord.disable(); } public gaussianBlur() { this.gl.disable(this.gl.BLEND); for (let i = 0; i < this.rayHandler.blurNum; i++) { this.frameBuffer.bindTexture(); // horizontal this.pingPongBuffer.begin(); this.blurShader.use(); // blurShader.setUniformi(""u_texture"", 0); this.blurShader.dir.set(1, 0); this.renderTriangleFan(this.blurShader); this.pingPongBuffer.endSimple(); this.pingPongBuffer.bindTexture(); // vertical this.frameBuffer.begin(); this.blurShader.use(); // blurShader.setUniformi(""u_texture"", 0); this.blurShader.dir.set(0, 1); this.renderTriangleFan(this.blurShader); if (this.rayHandler.customViewport) { this.frameBuffer.end( this.rayHandler.viewportX, this.rayHandler.viewportY, this.rayHandler.viewportWidth, this.rayHandler.viewportHeight, ); } else { this.frameBuffer.endSimple(); } } this.gl.enable(this.gl.BLEND); } public dispose() { this.shadowShader.dispose(); this.blurShader.dispose(); this.vertBuffer.dispose(); this.uvBuffer.dispose(); this.frameBuffer.dispose(); this.pingPongBuffer.dispose(); } private createVertices() { // prettier-ignore return new Float32Array([ -1, -1, 1, -1, 1, 1, -1, 1, ]); } private createUvCoords() { // prettier-ignore return new Float32Array([ 0, 0, 1, 0, 1, 1, 0, 1 ]); } } ",fboHeight 270,"import { Component, OnInit } from '@angular/core'; import { fabric } from 'fabric'; import { SocketWebService } from '../services/socket-web.service'; import * as uuid from 'uuid'; import { THIS_EXPR } from '@angular/compiler/src/output/output_ast'; @Component({ selector: 'app-canvas', templateUrl: './canvas.component.html', styleUrls: ['./canvas.component.css'] }) export class CanvasComponent implements OnInit { selectedColor: string = '##c61717'; sak = """"; public canvas = new fabric.Canvas('canvas'); private emite: boolean = true; isColorShown = false; isImageShown = false; public isDrawButtonActive?= false; group: fabric.Group; private arrow1 = [{ x: 20, y: 40 }, { x: 110, y: 40 }, { x: 110, y: 20 }, { x: 140, y: 50 }, { x: 110, y: 80 }, { x: 110, y: 60 }, { x: 20, y: 60 }, { x: 20, y: 40 }]; private arrow2 = [{ x: 20, y: 50 }, { x: 139, y: 50 }, { x: 110, y: 30 }, { x: 111, y: 30 }, { x: 141, y: 50 }, { x: 141, y: 51 }, { x: 111, y: 70 }, { x: 110, y: 70 }, { x: 139, y: 50 }, { x: 20, y: 51 }]; private arrow3 = [{ x: 20, y: 50 }, { x: 110, y: 50 }, { x: 110, y: 30 }, { x: 140, y: 50 }, { x: 110, y: 70 }, { x: 110, y: 50 }]; constructor(private socketService: SocketWebService) { this.socketService.callDraw.subscribe((res: any) => { console.log('Recibiendo evento DIBUJAR objeto genérico: callDraw', res.name, ' - ', res.type); this.emite = false; this.drawFromEvent(res) }); this.socketService.callRemove.subscribe((res: any) => { console.log('Recibiendo evento BORRAR objeto genérico: callRemove'); this.emite = false; this.deleteFromEvent(res) }); this.socketService.callModify.subscribe((res: any) => { this.emite = false; console.log('Recibiendo Modificar flecha: ', res.res); if (res.res.target.type == ""ArrowEnd"" || res.res.target.type === ""ArrowStart"") { console.log('Recibiendo evento MODIFICAR FLECHA: callModify', res.res.target.name, ' - ', res.res.target.type); this.modifyArrow(res); } else { console.log('Recibiendo evento MODIFICAR objeto genérico: callModify', res.res.target.name, ' - ', res.res.target.type); this.modifyObjectFromEvent(res) } }); this.socketService.callChangeColor.subscribe((res: any) => { console.log('Recibiendo evento CAMBIO COLOR objeto genérico: callChangeColor'); this.emite = false; this.changeColorFromEvent(res); }) this.socketService.callTextChanged.subscribe((res: any) => { console.log('Recibiendo evento CAMBIAR TEXTO objeto genérico: callTextChanged'); this.emite = false; this.changeTextFromEvent(res) }); this.socketService.callDrawArrow.subscribe((res: any) => { this.emite = false; console.log('Recibiendo evento DIBUJAR FLECHA: callDrawArrow'); this.addArrowToCanvas(res.startWithName, res.lineWithName, res.endWithName); }); } showCanvasComponent() { this.isColorShown = !this.isColorShown; } showImageURL() { this.isImageShown = !this.isImageShown; } ngOnInit(): void { this.isColorShown = false; this.isImageShown = false; this.canvas = new fabric.Canvas('canvas'); this.isDrawButtonActive = this.canvas.isDrawingMode; this.canvas.on('object:added', (e) => { if (this.emite) { console.log(e) if(e.target?.type == ""path""){ e.target.name = this.generateObjectId(); e.target.type = ""path""; } var shapeName = e.target?.name; if (shapeName != null) { if (shapeName.startsWith(""arrowS"")) { var idArrow = shapeName.substring(6, shapeName.length); var line = this.getObjectById('arrowL' + idArrow) as fabric.Line; var lineName = line.name; var end = this.getObjectById('arrowE' + idArrow) as fabric.Triangle; var endName = end.name; var start = e.target as fabric.Circle; var startName = e.target.name; console.log('Emitiendo evento DIBUJAR FLECHA: drawFullArrow: ', e); this.socketService.drawFullArrow({ start, startName }, { line, lineName }, { end, endName }); } else if (shapeName.startsWith(""arrowE"") || shapeName.startsWith(""arrowL"")) { } else { this.socketService.drawEvent(e, shapeName?.toString()); } } } }); this.canvas.on('object:removed', (e) => { if (this.emite) { let nameShape = (e.target?.name) console.log('Emitiendo evento BORRAR objeto genérico: removeEvent'); this.socketService.removeEvent((nameShape)); } }); this.canvas.on('object:modified', (e) => { var objects: any[] = []; this.canvas.getActiveObjects().forEach((object: any) => { objects.push({ name: object.name, shape: object }); }); console.log('Emitiendo evento MODIFICAR objeto genérico: modifyEvent ', objects[0].name, ' - ', objects[0].type); this.socketService.modifyEvent(e, objects); }); this.canvas.on('text:changed', (e) => { var name = e.target?.name; console.log('Emitiendo evento MODIFICAR TEXTO: changeTextEvent'); this.socketService.changeTextEvent(({ e, name })); }); } /************************ ACTIONS FROM EVENTS *************************/ changeTextFromEvent(res: any) { var object = this.getObjectById(res.name) as fabric.Text object.text = res.e.target.text; this.canvas.renderAll() } modifyObjectFromEvent(event: any) { var target = event.res.target; if (target.objects != null) { console.log('Multiple objects not available.') } else { var from = event.objects[0]; var object = this.getObjectById(from.name); if (object != null) { object.left = from.shape.left; object.top = from.shape.top; object.angle = from.shape.angle; object.scaleX = from.shape.scaleX; object.scaleY = from.shape.scaleY; object.width = from.shape.width; object.height = from.shape.height; this.canvas.renderAll(); } } } deleteFromEvent(nameToRemove: string): void { if (nameToRemove != null) { var object = this.getObjectById(nameToRemove); if (object != null) this.removeShape(object) } } changeColorFromEvent(payload: any) { if (payload != null) { var object = this.getObjectById(payload.obj); if (object != null) { if (object.type == 'path') { object.set('stroke', payload.color); } else { object.set('fill', payload.color); } } this.canvas.renderAll(); } } drawFromEvent(e: any): void { if (e != null) { var target = e.res.target; var newTarget = this.addObjectIdToTargetOptions(target, e.name); switch (target.type) { case ""rect"": this.canvas.add(new fabric.Rect(newTarget)) break; case ""circle"": this.canvas.add(new fabric.Circle(newTarget)); break; case ""textbox"": this.canvas.add(new fabric.Textbox('', newTarget)); break; case ""path"": var pathValue = this.mapPathFromEvent(e); this.canvas.add(new fabric.Path(pathValue, newTarget)); break; case ""polyline"": this.canvas.add(new fabric.Polyline(target.points, newTarget)) break; case ""line"": this.canvas.add(new fabric.Line([350, 100, 350, 400], newTarget)); break; case ""image"": this.insertImageToCanvas(target.src, e.name, newTarget.scaleX != null ? newTarget.scaleX : 0.5); break; default: console.log('Target type not valid: ', target.type); } } } addObjectIdToTargetOptions(target: any, objectId: string): fabric.IObjectOptions { var ret = target as fabric.IObjectOptions; ret.name = objectId; return ret; } mapPathFromEvent(e: any): string { console.log(e); const path = e.res.target.path as Array>; let pathValue = """"; path.forEach((elements) => { elements.forEach((elementPath) => { pathValue += ' ' + elementPath }); }); return pathValue; } /************************ END ACTIONS FROM EVENTS *************************/ /************************ ARROW *************************/ addArrowToCanvas(startWithName?: any, lineWithName?: any, endWithName?: any) { var arrowId = this.generateObjectId(); var start: fabric.Circle; var line1: fabric.Line; var end: fabric.Triangle; if (startWithName != null) { start = startWithName?.start; line1 = lineWithName?.line; end = endWithName?.end; } var arrow = new fabric.Triangle({ left: end ? end.left : 100, top: end ? end.top : 50, originX: end ? end.originX : 'center', originY: end ? end.originY : 'center', type: end ? end.type : 'ArrowEnd', angle: end ? end.angle : 90, width: end ? end.width : 30, height: end ? end.height : 30, fill: end ? end.fill : '#000', name: endWithName ? endWithName.endName : 'arrowE' + arrowId, }); var line = new fabric.Line([50, 50, arrow.left, arrow.top], { stroke: line1 ? line1.stroke : '#000', selectable: line1 ? line1.selectable : false, strokeWidth: line1 ? line1.strokeWidth : 5, padding: line1 ? line1.padding : 5, originX: line1 ? line1.originX : 'center', originY: line1 ? line1.originY : 'center', name: lineWithName ? lineWithName.lineName : 'arrowL' + arrowId, type: line1 ? line1.type : 'ArrowLine', }); var circle = new fabric.Circle({ left: line.get('x1'), top: line.get('y1'), radius: start ? start.radius : 3, stroke: start ? start.stroke : '#000', strokeWidth: start ? start.strokeWidth : 14, originX: start ? start.originX : 'center', originY: start ? start.originY : 'center', hasBorders: start ? start.hasBorders : false, hasControls: start ? start.hasControls : false, lockScalingX: start ? start.lockScalingX : true, lockScalingY: start ? start.lockScalingY : true, lockRotation: start ? start.lockRotation : true, name: startWithName ? startWithName.startName : 'arrowS' + arrowId, type: start ? start.type : 'ArrowStart', fill: start ? start.fill : '#000' }); arrow.on('moving', (e) => { var line = this.getObjectById('arrowL' + arrowId) as fabric.Line; this.canvas.remove(line); var newLine = new fabric.Line([circle.left, circle.top, arrow.left, arrow.top], { stroke: '#000', selectable: false, strokeWidth: 8, padding: 5, originX: 'center', originY: 'center', name: 'arrowL' + arrowId, type: 'ArrowLine', }).on('mousedblclick', () => { this.canvas.remove(newLine); }); arrow.angle = this.calcArrowAngle(line?.get('x1'), line?.get('y1'), line?.get('x2'), line?.get('y2')); this.canvas.add(newLine); this.canvas.renderAll(); }); circle.on('moving', (e) => { var line = this.getObjectById('arrowL' + arrowId) as fabric.Line; this.canvas.remove(line); var newLine = new fabric.Line([circle.left, circle.top, arrow.left, arrow.top], { stroke: '#000', selectable: false, strokeWidth: 8, padding: 5, originX: 'center', originY: 'center', name: 'arrowL' + arrowId, type: 'ArrowLine', }).on('mousedblclick', () => { this.canvas.remove(newLine); }) arrow.angle = this.calcArrowAngle(line?.get('x1'), line?.get('y1'), line?.get('x2'), line?.get('y2')); this.canvas.add(newLine); this.canvas.renderAll(); }) this.canvas.add(line); this.canvas.add(arrow); this.canvas.add(circle); } modifyArrow(event: any) { this.modifyObjectFromEvent(event) var from = event.objects[0]; var [MASK] = this.getObjectById(from.name); if ( [MASK] != null) { var arrowId = from.name.substring(6); var line = this.getObjectById('arrowL' + arrowId) as fabric.Line; var circle = this.getObjectById('arrowS' + arrowId) as fabric.Circle; var arrow = this.getObjectById('arrowE' + arrowId) as fabric.Triangle; this.canvas.remove(line); var newLine = new fabric.Line([circle.left, circle.top, arrow.left, arrow.top], { stroke: '#000', selectable: false, strokeWidth: 8, padding: 5, originX: 'center', originY: 'center', name: 'arrowL' + arrowId, type: 'ArrowLine', }).on('mousedblclick', () => { this.canvas.remove(newLine); }); this.canvas.add(newLine); if ( [MASK] .type === ""ArrowStart"") { var line = this.getObjectById('arrowL' + arrowId) as fabric.Line; arrow.angle = this.calcArrowAngle(line?.get('x1'), line?.get('y1'), line?.get('x2'), line?.get('y2')); } this.canvas.renderAll(); } } calcArrowAngle(x1: any, y1: any, x2: any, y2: any) { var angle = 0, x, y; x = (x2 - x1); y = (y2 - y1); if (x === 0) { angle = (y === 0) ? 0 : (y > 0) ? Math.PI / 2 : Math.PI * 3 / 2; } else if (y === 0) { angle = (x > 0) ? 0 : Math.PI; } else { angle = (x < 0) ? Math.atan(y / x) + Math.PI : (y < 0) ? Math.atan(y / x) + (2 * Math.PI) : Math.atan(y / x); } return (angle * 180 / Math.PI) + 90; } drawDefaultArrow(arrow: { x: number; y: number }[]) { var pline = new fabric.Polyline(arrow, { fill: 'white', stroke: this.selectedColor, opacity: 1, strokeWidth: 2, originX: 'left', originY: 'top', selectable: false, name: this.generateObjectId() }); this.canvas.add(pline); this.canvas.renderAll(); } /************************ ARROW *************************/ /************************ GENERIC EVENTS *************************/ insertImageToCanvas(url: string, id: string, scale: number): void { fabric.Image.fromURL(url, img => { img.scale(scale); img.name = id; this.canvas.add(img); this.canvas.renderAll(); }); } removeShape(s: fabric.Object) { if (s == null) return; this.canvas.remove(s); } generateObjectId(): string { return uuid.v4(); } getObjectById(n: string): fabric.Object { return this.canvas.getObjects().find((object: any) => object.name === n); } /************************ GENERIC EVENTS *************************/ /************************ ON CLICK EVENTS *************************/ onClick_drawTextButton(): void { this.emite = true; this.canvas.isDrawingMode = false; this.canvas.add(new fabric.Textbox('Insert text', { name: this.generateObjectId() })); } checkFreeDrawValue() { this.emite = true; this.canvas.isDrawingMode = !this.canvas.isDrawingMode; this.isDrawButtonActive = this.canvas.isDrawingMode; this.canvas.freeDrawingBrush.color = this.selectedColor; } onClick_drawCircleButton(): void { this.emite = true; this.canvas.add(new fabric.Circle({ width: 100, height: 100, left: 100, top: 100, fill: this.selectedColor, angle: 45, radius: 50, name: this.generateObjectId() })) } onClick_drawLineButton(): void { this.emite = true; this.canvas.add(new fabric.Line([350, 100, 350, 400], { height: 100, left: 100, top: 100, stroke: this.selectedColor, name: this.generateObjectId() })) } onClick_drawRectButton(): void { this.emite = true; this.canvas.add(new fabric.Rect({ width: 100, height: 100, left: 0, top: 0, fill: this.selectedColor, name: this.generateObjectId() })) } onClick_deleteButton(): void { this.emite = true; var selectedObjects = this.canvas.getActiveObjects(); selectedObjects.forEach(shape => { this.removeShape(shape); }); } onClick_drawArrow1Button(): void { this.emite = true; this.addArrowToCanvas(); } onClick_drawArrow2Button(): void { this.emite = true; this.drawDefaultArrow(this.arrow2); } onClick_drawArrow3Button(): void { this.emite = true; this.drawDefaultArrow(this.arrow3); } onClick_AddImage(): void { this.emite = true; var url = document.getElementById('imageInput') as HTMLInputElement; var id = this.generateObjectId(); this.insertImageToCanvas(url.value, id, 0.5); } onClick_changeColor(): void { var activeObjects = this.canvas.getActiveObjects(); activeObjects.forEach(o => { if (o.type == 'path' || o.type == 'line') { o.set('stroke', this.selectedColor); } else { o.set('fill', this.selectedColor); } if (o.name != null) { this.socketService.changeColorEvent(o.name, this.selectedColor); } }); this.canvas.renderAll(); } onClickChangeColor(color: string): void { this.selectedColor = color; if (this.canvas.isDrawingMode) this.canvas.freeDrawingBrush.color = color; } /************************ END ON CLICK EVENTS *************************/ } ",arrowEvent 271,"// (C) Copyright 2015 Moodle Pty 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. import { Injectable } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { CoreAppProvider } from './app'; import { CoreConfigProvider } from './config'; import { CoreFileProvider, CoreFileProgressFunction } from './file'; import { CoreFilepoolProvider } from './filepool'; import { CoreSitesProvider } from './sites'; import { CoreWSProvider } from './ws'; import { CoreDomUtilsProvider } from './utils/dom'; import { CoreUtilsProvider } from './utils/utils'; import { CoreConstants } from '@core/constants'; import { FileEntry } from '@ionic-native/file'; import { makeSingleton } from '@singletons/core.singletons'; /** * Provider to provide some helper functions regarding files and packages. */ @Injectable() export class CoreFileHelperProvider { // Variables for reading files in chunks. protected MAX_CHUNK_SIZE_NAME = 'file_max_chunk_size'; protected READ_CHUNK_ATTEMPT_NAME = 'file_read_chunk_attempt'; protected maxChunkSize = -1; constructor(protected fileProvider: CoreFileProvider, protected filepoolProvider: CoreFilepoolProvider, protected sitesProvider: CoreSitesProvider, protected appProvider: CoreAppProvider, protected translate: TranslateService, protected utils: CoreUtilsProvider, protected wsProvider: CoreWSProvider, protected configProvider: CoreConfigProvider, protected domUtils: CoreDomUtilsProvider) { this.initMaxChunkSize(); } /** * Convenience function to open a file, downloading it if needed. * * @param file The file to download. * @param component The component to link the file to. * @param componentId An ID to use in conjunction with the component. * @param state The file's state. If not provided, it will be calculated. * @param onProgress Function to call on progress. * @param siteId The site ID. If not defined, current site. * @return Resolved on success. */ downloadAndOpenFile(file: any, component: string, componentId: string | number, state?: string, onProgress?: (event: any) => any, siteId?: string): Promise { siteId = siteId || this.sitesProvider.getCurrentSiteId(); const fileUrl = this.getFileUrl(file), timemodified = this.getFileTimemodified(file); return this.downloadFileIfNeeded(file, fileUrl, component, componentId, timemodified, state, onProgress, siteId) .then((url) => { if (!url) { return; } if (url.indexOf('http') === 0) { /* In iOS, if we use the same URL in embedded browser and background download then the download only downloads a few bytes (cached ones). Add a hash to the URL so both URLs are different. */ url = url + '#moodlemobile-embedded'; return this.utils.openOnlineFile(url).catch((error) => { // Error opening the file, some apps don't allow opening online files. if (!this.fileProvider.isAvailable()) { return Promise.reject(error); } let promise; // Get the state. if (state) { promise = Promise.resolve(state); } else { promise = this.filepoolProvider.getFileStateByUrl(siteId, fileUrl, timemodified); } return promise.then((state) => { if (state == CoreConstants.DOWNLOADING) { return Promise.reject(this.translate.instant('core.erroropenfiledownloading')); } let promise; if (state === CoreConstants.NOT_DOWNLOADED) { // File is not downloaded, download and then return the local URL. promise = this.downloadFile(fileUrl, component, componentId, timemodified, onProgress, file, siteId); } else { // File is outdated and can't be opened in online, return the local URL. promise = this.filepoolProvider.getInternalUrlByUrl(siteId, fileUrl); } return promise.then((url) => { return this.utils.openFile(url); }); }); }); } else { return this.utils.openFile(url); } }); } /** * Download a file if it needs to be downloaded. * * @param file The file to download. * @param fileUrl The file URL. * @param component The component to link the file to. * @param componentId An ID to use in conjunction with the component. * @param timemodified The time this file was modified. * @param state The file's state. If not provided, it will be calculated. * @param onProgress Function to call on progress. * @param siteId The site ID. If not defined, current site. * @return Resolved with the URL to use on success. */ protected downloadFileIfNeeded(file: any, fileUrl: string, component?: string, componentId?: string | number, timemodified?: number, state?: string, onProgress?: (event: any) => any, siteId?: string): Promise { siteId = siteId || this.sitesProvider.getCurrentSiteId(); return this.sitesProvider.getSite(siteId).then((site) => { return site.checkAndFixPluginfileURL(fileUrl); }).then((fixedUrl) => { if (this.fileProvider.isAvailable()) { let promise; if (state) { promise = Promise.resolve(state); } else { // Calculate the state. promise = this.filepoolProvider.getFileStateByUrl(siteId, fileUrl, timemodified); } return promise.then((state) => { // The file system is available. const isWifi = this.appProvider.isWifi(), isOnline = this.appProvider.isOnline(); if (state == CoreConstants.DOWNLOADED) { // File is downloaded, get the local file URL. return this.filepoolProvider.getUrlByUrl( siteId, fileUrl, component, componentId, timemodified, false, false, file); } else { if (!isOnline && !this.isStateDownloaded(state)) { // Not downloaded and user is offline, reject. return Promise.reject(this.translate.instant('core.networkerrormsg')); } if (onProgress) { // This call can take a while. Send a fake event to notify that we're doing some calculations. onProgress({calculating: true}); } return this.filepoolProvider.shouldDownloadBeforeOpen(fixedUrl, file.filesize).then(() => { if (state == CoreConstants.DOWNLOADING) { // It's already downloading, stop. return; } // Download and then return the local URL. return this.downloadFile(fileUrl, component, componentId, timemodified, onProgress, file, siteId); }, () => { // Start the download if in wifi, but return the URL right away so the file is opened. if (isWifi) { this.downloadFile(fileUrl, component, componentId, timemodified, onProgress, file, siteId); } if (!this.isStateDownloaded(state) || isOnline) { // Not downloaded or online, return the online URL. return fixedUrl; } else { // Outdated but offline, so we return the local URL. return this.filepoolProvider.getUrlByUrl( siteId, fileUrl, component, componentId, timemodified, false, false, file); } }); } }); } else { // Use the online URL. return fixedUrl; } }); } /** * Download the file. * * @param fileUrl The file URL. * @param component The component to link the file to. * @param componentId An ID to use in conjunction with the component. * @param timemodified The time this file was modified. * @param onProgress Function to call on progress. * @param file The file to download. * @param siteId The site ID. If not defined, current site. * @return Resolved with internal URL on success, rejected otherwise. */ downloadFile(fileUrl: string, component?: string, componentId?: string | number, timemodified?: number, onProgress?: (event: any) => any, file?: any, siteId?: string): Promise { siteId = siteId || this.sitesProvider.getCurrentSiteId(); // Get the site and check if it can download files. return this.sitesProvider.getSite(siteId).then((site) => { if (!site.canDownloadFiles()) { return Promise.reject(this.translate.instant('core.cannotdownloadfiles')); } return this.filepoolProvider.downloadUrl(siteId, fileUrl, false, component, componentId, timemodified, onProgress, undefined, file).catch((error) => { // Download failed, check the state again to see if the file was downloaded before. return this.filepoolProvider.getFileStateByUrl(siteId, fileUrl, timemodified).then((state) => { if (this.isStateDownloaded(state)) { return this.filepoolProvider.getInternalUrlByUrl(siteId, fileUrl); } else { return Promise.reject(error); } }); }); }); } /** * Get the file's URL. * * @param file The file. */ getFileUrl(file: any): string { return file.fileurl || file.url; } /** * Get the file's timemodified. * * @param file The file. */ getFileTimemodified(file: any): number { return file.timemodified || 0; } /** * Initialize the max chunk size. * * @return Promise resolved when done. */ protected async initMaxChunkSize(): Promise { const sizes = await Promise.all([ await this.configProvider.get(this.READ_CHUNK_ATTEMPT_NAME, -1), // Check if there is any attempt pending. await this.configProvider.get(this.MAX_CHUNK_SIZE_NAME, -1), // Retrieve current max chunk size from DB. ]); const attemptSize = sizes[0]; const maxChunkSize = sizes[1]; if (attemptSize != -1 && (maxChunkSize == -1 || attemptSize < maxChunkSize)) { // Store the attempt's size as the max size. this.storeMaxChunkSize(attemptSize); } else { // No attempt or the max size is already lower. Keep current max size. this.maxChunkSize = maxChunkSize; } if (attemptSize != -1) { // Clean pending attempt. await this.configProvider.delete(this.READ_CHUNK_ATTEMPT_NAME); } } /** * Check if a state is downloaded or outdated. * * @param state The state to check. */ isStateDownloaded(state: string): boolean { return state === CoreConstants.DOWNLOADED || state === CoreConstants.OUTDATED; } /** * Whether the file has to be opened in browser (external repository). * The file must have a mimetype attribute. * * @param file The file to check. * @return Whether the file should be opened in browser. */ shouldOpenInBrowser(file: any): boolean { if (!file || !file.isexternalfile || !file.mimetype) { return false; } const mimetype = file.mimetype; if (mimetype.indexOf('application/vnd.google-apps.') != -1) { // Google Docs file, always open in browser. return true; } if (file.repositorytype == 'onedrive') { // In OneDrive, open in browser the office docs return mimetype.indexOf('application/vnd.openxmlformats-officedocument') != -1 || mimetype == 'text/plain' || mimetype == 'document/unknown'; } return false; } /** * Calculate the total size of the given files. * * @param files The files to check. * @return Total files size. */ async getTotalFilesSize(files: any[]): Promise { let [MASK] = 0; for (const file of files) { [MASK] += await this.getFileSize(file); } return [MASK] ; } /** * Calculate the file size. * * @param file The file to check. * @return File size. */ async getFileSize(file: any): Promise { if (file.filesize) { return file.filesize; } // If it's a remote file. First check if we have the file downloaded since it's more reliable. if (file.filename && !file.name) { try { const siteId = this.sitesProvider.getCurrentSiteId(); const path = await this.filepoolProvider.getFilePathByUrl(siteId, file.fileurl); const fileEntry = await this.fileProvider.getFile(path); const fileObject = await this.fileProvider.getFileObjectFromFileEntry(fileEntry); return fileObject.size; } catch (error) { // Error getting the file, maybe it's not downloaded. Get remote size. const size = await this.wsProvider.getRemoteFileSize(file.fileurl); if (size === -1) { throw new Error('Couldn\'t determine file size: ' + file.fileurl); } return size; } } // If it's a local file, get its size. if (file.name) { const fileObject = await this.fileProvider.getFileObjectFromFileEntry(file); return fileObject.size; } throw new Error('Couldn\'t determine file size: ' + file.fileurl); } /** * Save max chunk size. * * @param size Size to store. * @return Promise resolved when done. */ protected async storeMaxChunkSize(size: number): Promise { this.maxChunkSize = size; await this.configProvider.set(this.MAX_CHUNK_SIZE_NAME, size); } /** * Write some file data into a filesystem file. * It's done in chunks to prevent crashing the app for big files. * * @param file The data to write. * @param path Path where to store the data. * @param onProgress Function to call on progress. * @param offset Offset where to start reading from. * @param append Whether to append the data to the end of the file. * @return Promise resolved when done. */ async writeFileDataInFile(file: Blob, path: string, onProgress?: CoreFileProgressFunction, offset: number = 0, append?: boolean): Promise { offset = offset || 0; // Get the chunk to read and write. const readWholeFile = offset === 0 && CoreFileProvider.CHUNK_SIZE >= file.size; const chunk = readWholeFile ? file : file.slice(offset, Math.min(offset + CoreFileProvider.CHUNK_SIZE, file.size)); try { const fileEntry = await this.fileProvider.writeFileDataInFileChunk(chunk, path, append); offset += CoreFileProvider.CHUNK_SIZE; onProgress && onProgress({ lengthComputable: true, loaded: offset, total: file.size }); if (offset >= file.size) { // Done, stop. return fileEntry; } // Read the next chunk. return this.writeFileDataInFile(file, path, onProgress, offset, true); } catch (error) { if (readWholeFile || !error || error.name != 'NotReadableError') { return Promise.reject(error); } // Permission error when reading file in chunks. This usually happens with Google Drive files. // Try to read the whole file at once. return this.writeBigFileDataInFile(file, path, onProgress); } } /** * Writes a big file data into a filesystem file without using chunks. * The app can crash when doing this with big files, so this function will try to control the max size that works * and warn the user if he's trying to upload a file that is too big. * * @param file The data to write. * @param path Path where to store the data. * @param onProgress Function to call on progress. * @return Promise resolved with the file. */ protected async writeBigFileDataInFile(file: Blob, path: string, onProgress?: CoreFileProgressFunction): Promise { if (this.maxChunkSize != -1 && file.size >= this.maxChunkSize) { // The file size is bigger than the max allowed size. Ask the user to confirm. await this.domUtils.showConfirm(this.translate.instant('core.confirmreadfiletoobig')); } // Store the ""attempt"". await this.configProvider.set(this.READ_CHUNK_ATTEMPT_NAME, file.size); // Write the whole file. const fileEntry = await this.fileProvider.writeFileDataInFileChunk(file, path, false); // Success, remove the attempt and increase the max chunk size if needed. await this.configProvider.delete(this.READ_CHUNK_ATTEMPT_NAME); if (file.size > this.maxChunkSize) { await this.storeMaxChunkSize(file.size + 1); } return fileEntry; } } export class CoreFileHelper extends makeSingleton(CoreFileHelperProvider) {} ",totalSize 272,"import { CreateNoteRequest } from ""./types/createNoteRequest.js""; import { NoteResponse } from ""./types/noteResponse.js""; import { PaginatedResponse } from ""./types/paginatedResponse.js""; import { UpdateNoteRequest } from ""./types/updateNoteRequest.js""; export interface ApiInterface { getNotes( pageNumber: number, pageSize: number, ): Promise>; getNote(noteId: string): Promise; updateNote(noteId: string, request: UpdateNoteRequest): Promise; createNote(request: CreateNoteRequest): Promise; deleteNote(noteId: string): Promise; } export class Api implements ApiInterface { private readonly API_BASE_URL: string; constructor( [MASK] : string) { this.API_BASE_URL = `${ [MASK] }/notes`; } async getNotes( pageNumber: number, pageSize: number, ): Promise> { const response = await fetch( `${this.API_BASE_URL}?pageNumber=${pageNumber}&pageSize=${pageSize}`, ); const data = await response.json(); return data as PaginatedResponse; } async getNote(noteId: string): Promise { const response = await fetch(`${this.API_BASE_URL}/${noteId}`); const data = await response.json(); return data as NoteResponse; } async updateNote(noteId: string, request: UpdateNoteRequest): Promise { await fetch(`${this.API_BASE_URL}/${noteId}`, { method: ""PUT"", body: JSON.stringify(request), headers: { ""Content-Type"": ""application/json"", }, }); } async createNote(request: CreateNoteRequest): Promise { const response = await fetch(this.API_BASE_URL, { method: ""POST"", body: JSON.stringify(request), headers: { ""Content-Type"": ""application/json"", }, }); const data = await response.json(); return data as NoteResponse; } async deleteNote(noteId: string): Promise { await fetch(`${this.API_BASE_URL}/${noteId}`, { method: ""DELETE"", }); } } ",baseUrl 273,"import ax, { AxiosError } from ""axios""; import { getSession, signOut } from ""next-auth/react""; const axios = ax.create({ baseURL: process.env.NEXT_PUBLIC_BASE_URL, headers: { post: { ""Content-Type"": ""application/json"", }, }, }); axios.interceptors.request.use(async (request) => { const [MASK] = axios.defaults.headers.token; // if token header not set if (!Boolean( [MASK] )) { const session = await getSession({ req: request, }); if (session) { const bearerToken = `Bearer ${session.user.userToken}`; request.headers.Authorization = bearerToken; axios.defaults.headers.Authorization = bearerToken; } } return request; }); axios.interceptors.response.use(undefined, async (error: unknown) => { if (error instanceof AxiosError && error.response?.status === 403) { await signOut({ callbackUrl: ""/signin"", redirect: true, }); } throw error; }); export { axios }; ",tokenDefault 274,"import { endpoint,account,namespace,expiration,xAuthEmail,xAuthKey } from ""../env"" const headers = { ""X-Auth-Email"": xAuthEmail, ""X-Auth-Key"": xAuthKey, 'Access-Control-Allow-Origin': '*', ""Content-Type"": ""application/json"" } const keyURL = endpoint + account + namespace + ""_noKeys"" + expiration /** * This function deletes a specific post off Cloudflare KV * It uses the runtime API since concurrent deletion will still lead to deletion of that key * @param request * @returns */ const delPost = async (request: any) => { const postId = request.params.id // retrieve id parameter from URL using itty router const [MASK] = JSON.stringify(await POSTS_KV.get(postId)) if ( [MASK] != JSON.stringify(null)) { // delete kv await POSTS_KV.delete(postId) // update no of keys using HTTPS to prevent concurrent access const keyOptions = { method: 'PUT', body: JSON.stringify(Number(await POSTS_KV.get(""_noKeys""))-1), headers: headers } await fetch(keyURL, keyOptions) return new Response('Successfully removed key-value:\n' + postId + "" : ""+ [MASK] ) } return new Response('No such key.') } export default delPost",existing 275,"// Arquivo: router.ts import { Router } from ""express""; import { isValidateObjectRequest } from './helpers/validate'; import { loadContatos, saveContato } from './helpers/load-data'; const router = Router(); router.get('/', function (req, res) { res.send({ api_name: 'api-contatos', descricao: 'API para gestão de contatos', status: 'OK', }); }); router.get('/sobre', function (req, res) { res.send({ name: '', email: '', github: 'github.com/joaoteixeira' }); }); router.post('/contato', function (req, res) { let ok = true; let [MASK] = ""Contato salvo com sucesso!""; const inputs = [ { name: ""nome"", message: ""A propriedade [nome] não deve estar em indefinida/vazio!"" }, { name: ""email"", message: ""A propriedade [email] não deve estar em indefinida/vazio!"" } ]; const checkValidate = isValidateObjectRequest(req, inputs); if (Array.isArray(checkValidate)) { ok = false; [MASK] = checkValidate.join(', '); } if (ok) { saveContato(req.body); } res.send({ success: ok, message: [MASK] }) }); router.get('/contato', function (req, res) { const contatos = loadContatos(); res.send(contatos); }); export default router;",mensagem 276,"import { CanActivate, ExecutionContext, HttpStatus, Injectable } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import { JwtService } from '@nestjs/jwt'; import { Request } from 'express'; import appConfig from '../../config/auth.config'; import { IS_PUBLIC_KEY } from '../helpers/skipAuth'; import * as SYS_MSG from '../constant/SystemMessages'; import { CustomHttpException } from '../helpers/custom-http-filter'; import { AuthGuard } from './auth.guard'; @Injectable() export class AdminGuard implements CanActivate { constructor( private jwtService: JwtService, private reflector: Reflector, private authGuard: AuthGuard ) {} async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); const token = this.authGuard.extractTokenFromRequest(request); if (!token) { throw new CustomHttpException(SYS_MSG.UNAUTHENTICATED_MESSAGE, HttpStatus.UNAUTHORIZED); } const [MASK] = request.user; if (! [MASK] || [MASK] .role !== 'admin') { throw new CustomHttpException(SYS_MSG.UNAUTHORIZED_MESSAGE, HttpStatus.FORBIDDEN); } return true; return true; } }",payload 277,"import type { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh' import { PhysicsAggregate } from '@babylonjs/core/Physics/v2/physicsAggregate' import { moveTowards } from '../utils/utils.ts' import type { Scene } from '@babylonjs/core/scene' import type { AnimationGroup } from '@babylonjs/core/Animations/animationGroup' import type { ArcRotateCamera } from '@babylonjs/core/Cameras/arcRotateCamera' import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder' import { Quaternion, Vector3 } from '@babylonjs/core/Maths/math.vector' import { PhysicsShapeType } from '@babylonjs/core/Physics/v2/IPhysicsEnginePlugin' import { Ingredient } from '@shared/types/enums.ts' import type { IngredientLoader } from '@client/game/IngredientLoader.ts' import { Mesh } from '@babylonjs/core/Meshes' import { CharacterState } from './CharacterState' import type { AudioManager } from '@client/game/managers/AudioManager.ts' import { TransformNode } from '@babylonjs/core/Meshes/transformNode' import { INGREDIENT_VISUAL_CONFIG, type IngredientVisualContextConfig } from '@shared/visualConfigs.ts' import { getItemDefinition } from '@shared/items.ts' import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture' import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial' import { Color3 } from '@babylonjs/core/Maths/math.color' import { Texture } from '@babylonjs/core/Materials/Textures/texture' export class CharacterController { protected readonly audioManager: AudioManager protected readonly ingredientLoader: IngredientLoader private currentIngredientMesh?: Mesh | null = undefined private plateMesh?: Mesh | null = undefined readonly scene: Scene readonly model: AbstractMesh readonly physicsAggregate: PhysicsAggregate readonly moveSpeed = 1.8 readonly rotationSpeed = 6 readonly animationBlendSpeed = 4.0 readonly jumpForce = 5.0 readonly walkAnim: AnimationGroup readonly idleAnim: AnimationGroup readonly jumpAnim: AnimationGroup readonly landingAnim: AnimationGroup readonly fallingAnim: AnimationGroup readonly sambaDanceAnim: AnimationGroup readonly nonIdleAnimations: AnimationGroup[] readonly thirdPersonCamera?: ArcRotateCamera protected targetAnim: AnimationGroup protected readonly impostorMesh: AbstractMesh protected currentState: CharacterState = CharacterState.IDLE protected ingredient: Ingredient = Ingredient.None protected holdingPlate: boolean = false protected readonly holdAttachmentPoint: TransformNode protected readonly nameTagAttachmentPoint: TransformNode private usernamePlane: Mesh | null = null private usernameTexture: DynamicTexture | null = null private usernameMaterial: StandardMaterial | null = null private currentDisplayedUsername: string = '' protected constructor( characterMesh: AbstractMesh, scene: Scene, ingredientLoader: IngredientLoader, animationGroups: AnimationGroup[], audioManager: AudioManager, ) { this.scene = scene this.ingredientLoader = ingredientLoader this.audioManager = audioManager this.impostorMesh = MeshBuilder.CreateCapsule('CharacterTransform', { height: 1.5, radius: 0.3 }, scene) this.impostorMesh.visibility = 0 this.impostorMesh.rotationQuaternion = Quaternion.Identity() this.impostorMesh.position.y = 1 this.impostorMesh.position.x = 0 this.impostorMesh.position.z = 3.5 this.impostorMesh.isPickable = false this.holdAttachmentPoint = new TransformNode('holdAttachmentPoint', scene) this.holdAttachmentPoint.parent = this.impostorMesh this.holdAttachmentPoint.position = new Vector3(0, -0.2, -0.4) // Adjust as needed this.holdAttachmentPoint.rotationQuaternion = Quaternion.Identity() this.holdAttachmentPoint.scaling = Vector3.One() // Ensure it doesn't scale this.nameTagAttachmentPoint = new TransformNode('nameTagAttachmentPoint', scene) this.nameTagAttachmentPoint.parent = this.impostorMesh this.nameTagAttachmentPoint.position = new Vector3(0, 1.0, 0) this.model = characterMesh this.model.parent = this.impostorMesh this.model.rotate(Vector3.Up(), Math.PI) this.model.position.y = -0.75 characterMesh.isPickable = false // Make all submeshes unselectable this.model.getChildMeshes().forEach((mesh) => { mesh.isPickable = false mesh.receiveShadows = true }) const walkAnimGroup = animationGroups.find((ag) => ag.name === 'Walking') if (walkAnimGroup === undefined) throw new Error(""'Walking' animation not found"") this.walkAnim = walkAnimGroup this.walkAnim.weight = 0 const sambaDanceAnimGroup = animationGroups.find((ag) => ag.name === 'SambaDancing') if (sambaDanceAnimGroup === undefined) throw new Error(""'SambaDancing' animation not found"") this.sambaDanceAnim = sambaDanceAnimGroup this.sambaDanceAnim.weight = 0 const jumpAnimGroup = animationGroups.find((ag) => ag.name === 'Jump') if (jumpAnimGroup === undefined) throw new Error(""'Jumping' animation not found"") this.jumpAnim = jumpAnimGroup this.jumpAnim.weight = 0 const fallingAnimGroup = animationGroups.find((ag) => ag.name === 'Fall') if (fallingAnimGroup === undefined) throw new Error(""'Falling' animation not found"") this.fallingAnim = fallingAnimGroup this.fallingAnim.weight = 0 const landingAnimGroup = animationGroups.find((ag) => ag.name === 'Land') if (landingAnimGroup === undefined) throw new Error(""'Landing' animation not found"") this.landingAnim = landingAnimGroup this.landingAnim.weight = 0 this.landingAnim.loopAnimation = false const idleAnimGroup = animationGroups.find((ag) => ag.name === 'Idle') if (idleAnimGroup === undefined) throw new Error(""'Idle' animation not found"") this.idleAnim = idleAnimGroup this.idleAnim.weight = 1 this.idleAnim.play(true) this.targetAnim = this.idleAnim this.nonIdleAnimations = [this.walkAnim, this.sambaDanceAnim, this.jumpAnim, this.fallingAnim, this.landingAnim] this.physicsAggregate = new PhysicsAggregate(this.getTransform(), PhysicsShapeType.CAPSULE, { mass: 1, friction: 0.5, }) this.physicsAggregate.body.setMassProperties({ inertia: Vector3.ZeroReadOnly }) this.physicsAggregate.body.setAngularDamping(100) this.physicsAggregate.body.setLinearDamping(10) } private clearHeldItemVisuals(): void { if (this.currentIngredientMesh) { this.currentIngredientMesh.dispose() this.currentIngredientMesh = undefined } if (this.plateMesh) { this.plateMesh.dispose() this.plateMesh = undefined } } private updateHeldItemVisuals(): void { this.clearHeldItemVisuals() // Clear previous visuals const plateHoldingConfig = INGREDIENT_VISUAL_CONFIG[Ingredient.Plate] const heldIngredientConfig = INGREDIENT_VISUAL_CONFIG[this.ingredient] const heldIngredientDef = getItemDefinition(this.ingredient) const defaultScale = new Vector3(0.5, 0.5, 0.5) // --- 1. Handle Plate --- if (this.holdingPlate) { this.plateMesh = this.ingredientLoader.getIngredientMesh(Ingredient.Plate) if (this.plateMesh) { // Parent plate to the attachment point this.plateMesh.parent = this.holdAttachmentPoint // Apply config or defaults to the plate const plateScale = plateHoldingConfig?.scale ? new Vector3(plateHoldingConfig.scale.x, plateHoldingConfig.scale.y, plateHoldingConfig.scale.z) : defaultScale this.plateMesh.scaling = plateScale const contextConfig = plateHoldingConfig?.hand const defaultPlatePos = Vector3.Zero() this.plateMesh.position = contextConfig?.positionOffset ? new Vector3(contextConfig.positionOffset.x, contextConfig.positionOffset.y, contextConfig.positionOffset.z) : defaultPlatePos this.plateMesh.rotationQuaternion = contextConfig?.rotationOffset ? new Quaternion( contextConfig.rotationOffset.x, contextConfig.rotationOffset.y, contextConfig.rotationOffset.z, contextConfig.rotationOffset.w, ) : Quaternion.Identity() this.plateMesh.isPickable = false this.plateMesh.getChildMeshes().forEach((m) => (m.isPickable = false)) } } // --- 2. Handle Ingredient --- if (this.ingredient !== Ingredient.None && heldIngredientDef) { this.currentIngredientMesh = this.ingredientLoader.getIngredientMesh(this.ingredient) if (this.currentIngredientMesh) { let targetParent: TransformNode | Mesh = this.holdAttachmentPoint let contextConfig: IngredientVisualContextConfig | undefined let basePosition: Vector3 if (this.holdingPlate && this.plateMesh) { targetParent = this.plateMesh contextConfig = heldIngredientConfig?.onPlate basePosition = new Vector3(0, 0.1, 0) } else { targetParent = this.holdAttachmentPoint contextConfig = heldIngredientConfig?.hand basePosition = new Vector3(0, -0.1, 0.1) } this.currentIngredientMesh.parent = targetParent let ingredientScale = heldIngredientConfig?.scale ? new Vector3(heldIngredientConfig.scale.x, heldIngredientConfig.scale.y, heldIngredientConfig.scale.z) : defaultScale if (this.holdingPlate && this.plateMesh) { ingredientScale = new Vector3(ingredientScale.x / 0.5, ingredientScale.y / 0.5, ingredientScale.z / 0.5) } this.currentIngredientMesh.scaling = ingredientScale const positionOffset = contextConfig?.positionOffset ? new Vector3(contextConfig.positionOffset.x, contextConfig.positionOffset.y, contextConfig.positionOffset.z) : Vector3.Zero() this.currentIngredientMesh.position = basePosition.add(positionOffset) this.currentIngredientMesh.rotationQuaternion = contextConfig?.rotationOffset ? new Quaternion( contextConfig.rotationOffset.x, contextConfig.rotationOffset.y, contextConfig.rotationOffset.z, contextConfig.rotationOffset.w, ) : Quaternion.Identity() this.currentIngredientMesh.isPickable = false this.currentIngredientMesh.getChildMeshes().forEach((m) => (m.isPickable = false)) } } } dropIngredient() { this.ingredient = Ingredient.None this.updateHeldItemVisuals() } dropPlate() { if (!this.holdingPlate) return this.holdingPlate = false // If dropping plate also drops ingredient on it if (this.ingredient !== Ingredient.None) { const itemDef = getItemDefinition(this.ingredient) if (itemDef?.isFinal) { // Only results sit on plates typically this.ingredient = Ingredient.None } } this.updateHeldItemVisuals() // Update visuals after dropping } pickupIngredient(ingredient: Ingredient) { if (this.ingredient) { return } const ingredient_def = getItemDefinition(ingredient) if (this.holdingPlate && !ingredient_def?.isFinal) { return } this.forceSetIngredient(ingredient) } forceSetIngredient(ingredient: Ingredient) { if (this.ingredient === ingredient) return this.ingredient = ingredient this.updateHeldItemVisuals() } pickupPlate() { const currentIngredient = this.ingredient const currentIngredientIsFinal = currentIngredient !== Ingredient.None && !!getItemDefinition(currentIngredient)?.isFinal if (currentIngredient !== Ingredient.None && !currentIngredientIsFinal) { console.warn('Client: Cannot pick up plate while holding non-final.') return } this.forcePickupPlate() } forcePickupPlate() { if (this.holdingPlate) return this.holdingPlate = true this.updateHeldItemVisuals() } get holdedIngredient() { return this.ingredient } get isHoldingPlate() { return this.holdingPlate } set isHoldingPlate(value: boolean) { if (value && !this.holdingPlate) { this.pickupPlate() } else if (!value && this.holdingPlate) { this.dropPlate() } } get position() { return this.impostorMesh.position } get rotation() { return this.impostorMesh.rotationQuaternion } get getTargetAnim() { return this.targetAnim } public getTransform() { return this.impostorMesh } public setPosition(position: Vector3) { this.impostorMesh.position = position } public setRotation(rotation: Quaternion) { this.impostorMesh.rotationQuaternion = rotation } public setRotationY(y: number) { this.impostorMesh.rotationQuaternion = Quaternion.RotationAxis(Vector3.Up(), y) } public update(_deltaSeconds: number): void { return } private _createOrUpdateUsernameDisplay(username: string): void { const textureWidth = 512 const [MASK] = 128 // Rectangular for names const planeWidth = 1 // Adjust size as needed const planeHeight = ( [MASK] / textureWidth) * planeWidth const cornerRadius = [MASK] * 0.2 // --- Dispose existing resources if they exist --- this._removeUsernameDisplay() // --- Create Dynamic Texture --- this.usernameTexture = new DynamicTexture( `usernameTexture_${this.impostorMesh.name}`, { width: textureWidth, height: [MASK] }, this.scene, false, // No mipmaps Texture.BILINEAR_SAMPLINGMODE, ) this.usernameTexture.hasAlpha = true // --- Draw on Texture --- const ctx = this.usernameTexture.getContext() as CanvasRenderingContext2D ctx.clearRect(0, 0, textureWidth, [MASK] ) // Background (optional, for readability) ctx.fillStyle = 'rgba(0, 0, 0, 0.5)' // Semi-transparent black ctx.beginPath() ctx.roundRect(0, 0, textureWidth, [MASK] , cornerRadius) ctx.fill() // Text Style ctx.font = `bold ${ [MASK] * 0.6}px Arial` // Adjust font size based on texture height ctx.fillStyle = '#ffe4e6' ctx.textAlign = 'center' ctx.textBaseline = 'middle' // Draw Text ctx.fillText(username, textureWidth / 2, [MASK] / 2) // Update Texture this.usernameTexture.update() // --- Create Material --- this.usernameMaterial = new StandardMaterial(`usernameMat_${this.impostorMesh.name}`, this.scene) this.usernameMaterial.diffuseTexture = this.usernameTexture this.usernameMaterial.opacityTexture = this.usernameTexture // Use alpha from diffuse this.usernameMaterial.useAlphaFromDiffuseTexture = true this.usernameMaterial.emissiveColor = Color3.White() // Make it glow slightly / ignore lighting this.usernameMaterial.disableLighting = true this.usernameMaterial.backFaceCulling = false // Visible from behind // --- Create Plane --- this.usernamePlane = MeshBuilder.CreatePlane(`usernamePlane_${this.impostorMesh.name}`, { width: planeWidth, height: planeHeight }, this.scene) this.usernamePlane.material = this.usernameMaterial this.usernamePlane.billboardMode = Mesh.BILLBOARDMODE_ALL // Always face camera this.usernamePlane.parent = this.nameTagAttachmentPoint // Attach to the point above head this.usernamePlane.position = Vector3.Zero() // Positioned relative to attachment point this.usernamePlane.isPickable = false this.usernamePlane.renderingGroupId = 1 // Render on top this.usernamePlane.setEnabled(true) this.currentDisplayedUsername = username } // Method to remove the username display protected _removeUsernameDisplay(): void { if (this.usernamePlane) { this.usernamePlane.dispose() this.usernamePlane = null } if (this.usernameMaterial) { this.usernameMaterial.dispose() this.usernameMaterial = null } if (this.usernameTexture) { this.usernameTexture.dispose() this.usernameTexture = null } this.currentDisplayedUsername = '' } // Public method to set the displayed username public setUsernameDisplay(username: string | undefined | null): void { const nameToShow = username?.trim() ?? 'Player' // Default to 'Player' if empty/null if (nameToShow && nameToShow !== this.currentDisplayedUsername) { this._createOrUpdateUsernameDisplay(nameToShow) } else if (!nameToShow && this.usernamePlane) { this._removeUsernameDisplay() } } public dispose() { console.log(`Disposing CharacterController ${this.impostorMesh?.name ?? 'Unknown'}`) this._removeUsernameDisplay() this.clearHeldItemVisuals() this.holdAttachmentPoint.dispose() this.nameTagAttachmentPoint.dispose() this.impostorMesh.dispose() this.model.dispose() if (this.physicsAggregate) { this.physicsAggregate.dispose() } this.nonIdleAnimations.forEach((anim) => anim.stop()) this.idleAnim.stop() console.log(`CharacterController ${this.impostorMesh?.name ?? 'Unknown'} disposed.`) } /** * Performs animation blending based on the current state. * @param deltaTime Time elapsed since the last frame. */ protected updateAnimations(deltaTime: number): void { let targetAnim: AnimationGroup = this.idleAnim switch (this.currentState) { case CharacterState.IDLE: targetAnim = this.idleAnim break case CharacterState.WALKING: targetAnim = this.walkAnim break case CharacterState.JUMPING: targetAnim = this.jumpAnim break case CharacterState.FALLING: targetAnim = this.fallingAnim break case CharacterState.LANDING: targetAnim = this.landingAnim break case CharacterState.DANCING: targetAnim = this.sambaDanceAnim break } this.targetAnim = targetAnim let weightSum = 0 for (const anim of this.nonIdleAnimations) { const targetWeight = anim === targetAnim ? 1.0 : 0.0 anim.weight = moveTowards(anim.weight, targetWeight, this.animationBlendSpeed * deltaTime) if (anim === targetAnim && anim.weight > 0.01 && !anim.isPlaying) { const shouldLoop = anim === this.fallingAnim || anim === this.walkAnim || anim === this.sambaDanceAnim if (!shouldLoop) { anim.goToFrame(0) // Ensure non-looping starts at frame 0 } anim.play(shouldLoop) } else if (anim !== targetAnim && anim.weight < 0.01) { if (anim.isPlaying) { anim.pause() // Ensure non-looping animations are reset when they fully fade out or are paused if (!anim.loopAnimation) { anim.goToFrame(0) } } } weightSum += anim.weight } this.idleAnim.weight = moveTowards(this.idleAnim.weight, Math.max(0.0, 1.0 - weightSum), this.animationBlendSpeed * deltaTime) if (this.idleAnim.weight > 0.01 && !this.idleAnim.isPlaying) { this.idleAnim.play(true) } else if (this.idleAnim.weight < 0.01 && this.idleAnim.isPlaying) { this.idleAnim.pause() } } /** Helper to check if an animation is visually blended out */ protected isAnimationFinished(anim: AnimationGroup): boolean { // Considered finished if not playing OR weight is very low // For non-looping animations, check isPlaying specifically. if (!anim.loopAnimation) { return !anim.isPlaying && anim.weight < 0.1 } // For looping animations, weight is a better indicator of blend-out return anim.weight < 0.1 } } ",textureHeight 278,"import { Game } from ""crystal-maze""; import { memory } from ""crystal-maze/crystal_maze_bg""; const ACTIONS = [ ""All off"", ""All but self toggle"", ""Toggle self"", ""On evens"", ""Off evens"", ""On odds"", ""Off odds"", ""Toggle ±1"", ""Toggle ±2"", ""Toggle ±3"" ]; const game = Game.new(BigInt(new Date().getTime())); const SIZE = game.size(); const buttonElements = document .getElementById(""leds"") .getElementsByTagName(""button""); const ledsPtr = game.leds(); const leds = new Uint8Array(memory.buffer, ledsPtr, SIZE); const mappingPtr = game.mapping(); const mapping = new Uint8Array(memory.buffer, mappingPtr, SIZE); const setLeds = () => leds.forEach((on, i) => { buttonElements[i].classList.toggle(""on"", on !== 0); }); const displayMapping = () => { let [MASK] = """"; const a = ""a"".codePointAt(0); for (let i = 0; i < SIZE; i++) { const mapped = mapping[i]; [MASK] += `${i + 1}: ${String.fromCodePoint(a + mapped)} (${ ACTIONS[mapped] })\n`; } document.getElementById(""mapping"").textContent = [MASK] ; }; for (let i = 0; i < SIZE; i++) { const buttonElement = buttonElements[i]; buttonElement.addEventListener(""click"", () => { game.button_down(i); setLeds(); }); } document.getElementById(""reset"").addEventListener(""click"", () => { game.reset(); setLeds(); displayMapping(); }); setLeds(); displayMapping(); ",displayedMapping 279,"import { FieldType, LoadingState, dateTime } from '@grafana/data'; import { RelativeRangeCache } from 'RelativeRangeRequestCache/RelativeRangeCache'; import { QueryType, SiteWiseTimeOrder } from 'types'; import { generateSiteWiseRequestCacheId } from './cacheIdUtils'; describe('RelativeRangeCache', () => { const requestId = 'mock-request-id'; const range = { from: dateTime('2024-05-28T00:00:00Z'), to: dateTime('2024-05-28T01:00:00Z'), raw: { from: 'now-1h', to: 'now' , } }; const request = { requestId, interval: '5s', intervalMs: 5000, range, scopedVars: {}, targets: [ { refId: 'A', queryType: QueryType.PropertyValueHistory, }, { refId: 'B', queryType: QueryType.DescribeAsset, }, ], timezone: 'browser', app: 'dashboard', startTime: 1716858000000, }; const requestDisabledCache = { ...request, targets: [ { ...request.targets[0], clientCache: false, }, ], }; describe('get()', () => { it('returns undefined when any query with client cache disabled', () => { const cachedQueryInfo = [ { query: { queryType: QueryType.PropertyValueHistory, refId: 'A', }, dataFrame: { name: 'Demo Turbine Asset 1', refId: 'A', fields: [ { name: 'time', type: FieldType.time, config: {}, values: [], }, ], length: 0 }, }, ]; const cacheData = { [generateSiteWiseRequestCacheId(requestDisabledCache)]: { queries: cachedQueryInfo, range, }, }; const cache = new RelativeRangeCache(new Map(Object.entries(cacheData))); expect(cache.get(requestDisabledCache)).toBeUndefined(); }); it('returns undefined when there is no cached response', () => { const cache = new RelativeRangeCache(); expect(cache.get(request)).toBeUndefined(); }); it('returns starting cached data and time series query to fetch', () => { const cachedQueryInfo = [ { query: { queryType: QueryType.PropertyValueHistory, refId: 'A', }, dataFrame: { name: 'Demo Turbine Asset 1', refId: 'A', fields: [ { name: 'time', type: FieldType.time, config: {}, values: [ 1716854400000, // 2024-05-28T00:00:00Z 1716854400001, // 2024-05-28T00:15:00Z + 1ms 1716855300000, // 2024-05-28T00:15:00Z 1716855300001, // 2024-05-28T00:15:00Z + 1ms 1716857100000, // 2024-05-28T00:45:00Z 1716857100001, // 2024-05-28T00:45:00Z + 1ms ], }, { name: 'RotationsPerSecond', type: FieldType.number, config: { unit: 'RPS' }, values: [0,1,2,3,4,5], }, ], length: 6 }, }, { query: { queryType: QueryType.ListAssociatedAssets, refId: 'B', }, dataFrame: { name: 'child', refId: 'B', fields: [ { name: 'name', type: FieldType.string, config: {}, values: [ 'child' ], }, ], length: 1 }, } ]; const expectedDataFrames = [ { name: 'Demo Turbine Asset 1', refId: 'A', fields: [ { name: 'time', type: FieldType.time, config: {}, values: [ 1716854400001, // 2024-05-28T00:15:00Z + 1ms 1716855300000, // 2024-05-28T00:15:00Z 1716855300001, // 2024-05-28T00:15:00Z + 1ms 1716857100000, // 2024-05-28T00:45:00Z ], }, { name: 'RotationsPerSecond', type: FieldType.number, config: { unit: 'RPS' }, values: [1,2,3,4], }, ], length: 4 }, { name: 'child', refId: 'B', fields: [ { name: 'name', type: FieldType.string, config: {}, values: [ 'child' ], }, ], length: 1 }, ]; const cacheData = { [generateSiteWiseRequestCacheId(request)]: { queries: cachedQueryInfo, range, }, }; const cache = new RelativeRangeCache(new Map(Object.entries(cacheData))); const cacheResult = cache.get(request); expect(cacheResult).toBeDefined() expect(cacheResult?.cachedResponse).toEqual({ start: { data: expectedDataFrames, key: requestId, state: LoadingState.Streaming, }, end: { data: [], key: requestId, state: LoadingState.Streaming, }, }); expect(cacheResult?.refreshingRequest).toEqual({ ...request, targets: [ { ...request.targets[0], // only time series query }, ], range: { from: dateTime(1716857100000), // '2024-05-28T01:45:00Z' to: dateTime('2024-05-28T01:00:00Z'), raw: { from: 'now-1h', to: 'now' , } } }) }); it('returns ending cached data and time series query to fetch', () => { const [MASK] = { requestId, interval: '5s', intervalMs: 5000, range, scopedVars: {}, targets: [ { refId: 'A', queryType: QueryType.PropertyValueHistory, timeOrdering: SiteWiseTimeOrder.DESCENDING, }, { refId: 'B', queryType: QueryType.DescribeAsset, }, ], timezone: 'browser', app: 'dashboard', startTime: 1716858000000, }; const cachedQueryInfoDescending = [ { query: { queryType: QueryType.PropertyValueHistory, refId: 'A', timeOrdering: SiteWiseTimeOrder.DESCENDING, }, dataFrame: { name: 'Demo Turbine Asset 1', refId: 'A', fields: [ { name: 'time', type: FieldType.time, config: {}, values: [ 1716857100001, // 2024-05-28T00:45:00Z + 1ms 1716857100000, // 2024-05-28T00:45:00Z 1716855300001, // 2024-05-28T00:15:00Z + 1ms 1716855300000, // 2024-05-28T00:15:00Z 1716854400001, // 2024-05-28T00:15:00Z + 1ms 1716854400000, // 2024-05-28T00:00:00Z ], }, { name: 'RotationsPerSecond', type: FieldType.number, config: { unit: 'RPS' }, values: [5,4,3,2,1,0], }, ], length: 6 }, }, { query: { queryType: QueryType.ListAssociatedAssets, refId: 'B', }, dataFrame: { name: 'child', refId: 'B', fields: [ { name: 'name', type: FieldType.string, config: {}, values: [ 'child' ], }, ], length: 1 }, } ]; const expectedStartDataFrames = [ { name: 'Demo Turbine Asset 1', refId: 'A', fields: [], length: 0, }, { name: 'child', refId: 'B', fields: [ { name: 'name', type: FieldType.string, config: {}, values: [ 'child' ], }, ], length: 1 } ]; const expectedEndingDataFrames = [ { name: 'Demo Turbine Asset 1', refId: 'A', fields: [ { name: 'time', type: FieldType.time, config: {}, values: [ 1716857100000, // 2024-05-28T00:45:00Z 1716855300001, // 2024-05-28T00:15:00Z + 1ms 1716855300000, // 2024-05-28T00:15:00Z 1716854400001, // 2024-05-28T00:15:00Z + 1ms ], }, { name: 'RotationsPerSecond', type: FieldType.number, config: { unit: 'RPS' }, values: [4,3,2,1], }, ], length: 4 } ]; const cacheData = { [generateSiteWiseRequestCacheId( [MASK] )]: { queries: cachedQueryInfoDescending, range, }, }; const cache = new RelativeRangeCache(new Map(Object.entries(cacheData))); const cacheResult = cache.get( [MASK] ); expect(cacheResult).toBeDefined() expect(cacheResult?.cachedResponse).toEqual({ start: { data: expectedStartDataFrames, key: requestId, state: LoadingState.Streaming, }, end: { data: expectedEndingDataFrames, key: requestId, state: LoadingState.Streaming, }, }); expect(cacheResult?.refreshingRequest).toEqual({ ... [MASK] , targets: [ { ... [MASK] .targets[0], // only time series query }, ], range: { from: dateTime(1716857100000), // '2024-05-28T01:45:00Z' to: dateTime('2024-05-28T01:00:00Z'), raw: { from: 'now-1h', to: 'now' , } } }) }); }); describe('set()', () => { const cachedQueryInfo = [ { query: { queryType: QueryType.PropertyValueHistory, refId: 'A', }, dataFrame: { name: 'Demo Turbine Asset 1', refId: 'A', fields: [ { name: 'time', type: FieldType.time, config: {}, values: [ 1716854400001, // 2024-05-28T00:15:00Z + 1ms 1716855300000, // 2024-05-28T00:15:00Z 1716855300001, // 2024-05-28T00:15:00Z + 1ms 1716857100000, // 2024-05-28T00:45:00Z ], }, { name: 'RotationsPerSecond', type: FieldType.number, config: { unit: 'RPS' }, values: [1,2,3,4], }, ], length: 4 }, }, { query: { queryType: QueryType.DescribeAsset, refId: 'B', }, dataFrame: { name: 'child', refId: 'B', fields: [ { name: 'name', type: FieldType.string, config: {}, values: [ 'child' ], }, ], length: 1 }, } ]; const expectedDataFrames = [ { name: 'Demo Turbine Asset 1', refId: 'A', fields: [ { name: 'time', type: FieldType.time, config: {}, values: [ 1716854400001, // 2024-05-28T00:15:00Z + 1ms 1716855300000, // 2024-05-28T00:15:00Z 1716855300001, // 2024-05-28T00:15:00Z + 1ms 1716857100000, // 2024-05-28T00:45:00Z ], }, { name: 'RotationsPerSecond', type: FieldType.number, config: { unit: 'RPS' }, values: [1,2,3,4], }, ], length: 4 }, { name: 'child', refId: 'B', fields: [ { name: 'name', type: FieldType.string, config: {}, values: [ 'child' ], }, ], length: 1 }, ]; it('does nothing when any query with client cache disabled', () => { const cacheMap = new Map(); const cache = new RelativeRangeCache(cacheMap); cache.set(requestDisabledCache, { data: expectedDataFrames, }); expect(cacheMap.size).toBe(0); }); it('set request/response pair', () => { const cacheData = { [generateSiteWiseRequestCacheId(request)]: { queries: cachedQueryInfo, range, }, }; const expectedCacheMap = new Map(Object.entries(cacheData)); const cacheMap = new Map(); const cache = new RelativeRangeCache(cacheMap); cache.set(request, { data: expectedDataFrames, }); expect(cacheMap).toEqual(expectedCacheMap); }); }); }); ",requestDescending 280,"import {v4 as uuid} from 'uuid'; import axios from ""axios""; import * as log4js from 'log4js'; const logger = log4js.getLogger('azure-sentinel-dispatcher'); logger.level = process.env.LOG_LEVEL || 'info'; const express = require(""express""); const { HTTP } = require(""cloudevents""); const app = express(); const msal = require('@azure/msal-node'); const AZURE_SUBSCRIPTION_ID = process.env.AZURE_SUBSCRIPTION_ID; const AZURE_RESOURCE_GROUP = process.env.AZURE_RESOURCE_GROUP; const AZURE_WORKSPACE = process.env.AZURE_WORKSPACE; const AZURE_CLIENT_SECRET = process.env.AZURE_CLIENT_SECRET; const AZURE_CLIENT_ID = process.env.AZURE_CLIENT_ID; const AZURE_TENANT_ID = process.env.AZURE_TENANT_ID; const AZURE_API_VERSION = '2020-01-01'; const incidentId = uuid(); const requestUrl = `https://management.azure.com/subscriptions/${AZURE_SUBSCRIPTION_ID}/` + `resourceGroups/${AZURE_RESOURCE_GROUP}/` + `providers/Microsoft.OperationalInsights/workspaces/${AZURE_WORKSPACE}/` + `providers/Microsoft.SecurityInsights/incidents/${incidentId}?api-version=${AZURE_API_VERSION}`; app.use((req, res, next) => { let data = """"; req.setEncoding(""utf8""); req.on(""data"", function ( [MASK] ) { data += [MASK] ; }); req.on(""end"", function () { req.body = data; next(); }); }); app.post(""/"", async (req, res) => { const msalConfig = { auth: { clientId: AZURE_CLIENT_ID, authority: ""https://login.microsoftonline.com/"" + AZURE_TENANT_ID, clientSecret: AZURE_CLIENT_SECRET, } }; const cca = new msal.ConfidentialClientApplication(msalConfig); const tokenRequest = { scopes: [ 'https://management.azure.com/.default' ], }; const getTokenResponse = await cca.acquireTokenByClientCredential(tokenRequest); var event try { event = HTTP.toEvent({ headers: req.headers, body: req.body }); } catch (err) { console.error(err); res.status(415).header(""Content-Type"", ""application/json"").send(JSON.stringify(err)); } const incident = { ""properties"": { ""severity"": ""High"", ""status"": ""Active"", ""title"": event.data.event.event.metadata.name, ""description"": event.data.event.event.metadata.shortDescription, ""additionalData"": { ""alertProductNames"": [ event.data.event.event.resources[0].platform, event.data.event.event.resources[0].accountId, event.data.event.event.resources[0].region, event.data.event.event.resources[0].service, event.data.event.event.resources[0].type + ':' + event.data.event.event.resources[0].name + ':' + event.data.event.event.resources[0].guid ] }, ""labels"": [ { ""labelName"": event.data.event.event.reporter.name, ""labelType"": ""User"" } ] } }; try { const result = await axios.put(requestUrl, incident,{ headers: { 'Authorization': `Bearer ${getTokenResponse.accessToken}` } }); console.log(result); if (result.status === 200 || result.status === 201) { logger.debug('incident successfully dispatched'); console.log('incident successfully dispatched'); } else { logger.error('failed to dispatch incident', result); res.status(500).send(result); } } catch (e) { logger.error('failed to dispatch incident', e); res.status(500).send(e); } res.status(200).header(""Content-Type"", ""application/json"").send(""ok""); }); app.listen(8080, () => { console.log(""Example app listening on port 8080!""); }); ",chunk 281,"window.addEventListener(""load"", () => { // Handle disabling all relevant inputs if one patient selection method has been interacted with const patientInputs = Array.from( document.querySelectorAll("".patient-option input, .patient-option select"") || [], ); patientInputs.forEach((input) => { input.addEventListener(""change"", () => { const siblings = Array.from( input.closest("".patient-option"")?.querySelectorAll(""input, select"") || [], ); patientInputs.forEach(( [MASK] ) => { if (!siblings.includes( [MASK] )) { /* eslint-disable-next-line no-param-reassign */ [MASK] .disabled = true; } }); const reset = input.closest("".patient-option"")?.querySelector("".form-reset"") as HTMLElement; reset.classList.remove(""hidden""); }); }); // Handle resetting all patient selection input fields const resets = document.querySelectorAll("".form-reset""); resets.forEach((reset) => { reset.addEventListener(""click"", () => { patientInputs.forEach((input) => { /* eslint-disable-next-line no-param-reassign */ input.value = input.defaultValue; /* eslint-disable-next-line no-param-reassign */ input.disabled = false; }); resets.forEach((reset) => { reset.classList.add(""hidden""); }); }); }); // Handle displaying and updating the selected approximate age of emergency patients const ageSlider = document.querySelector(""#id_unknown-approximate_age"") as HTMLInputElement; const ageDisplay = document.querySelector(""#approximate-age-display"") as HTMLElement; if (!ageSlider || !ageDisplay) { return; } ageSlider.addEventListener(""input"", () => { ageDisplay.innerHTML = ageSlider.value; }); // If a patient was passed to the intake form, use it const patientSearch = document.querySelector(""#id_patient""); const urlParams = new URLSearchParams(window.location.href); if (urlParams.get(""patient"") && patientSearch) { patientSearch.dispatchEvent(new Event(""change"")); } }); ",otherInput 282,"import { createAgent } from ""@connectifi/agent-web""; let selectedChannel : string | null = null; document.addEventListener('DOMContentLoaded',async () => { const fdc3 = await createAgent('https://platform.connectifi.app', 'example@sandbox', { headless:true, onChannelJoined: joinHandler, onChannelLeft: leaveHandler, }); const picker = document.getElementById('picker'); const [MASK] = await fdc3?.getUserChannels(); [MASK] ?.forEach((channel) => { const item = document.createElement('div'); item.classList.add('channel'); item.id = channel.id; item.style.backgroundColor = channel.displayMetadata?.color || ''; item.addEventListener('click', () => { //if the channel selected is the current channel, then unjoin it if (selectedChannel === channel.id){ fdc3?.leaveCurrentChannel(); } else { fdc3?.joinUserChannel(channel.id); } }) picker?.appendChild(item); }); }); const joinHandler = (channelId: string) => { //reset the selected element if (selectedChannel) { const oldChannel = document.getElementById(selectedChannel); if (oldChannel){ oldChannel.textContent = ''; } } selectedChannel = channelId; //mark the selected one const channelElement = document.getElementById(channelId); if (channelElement){ channelElement.textContent = 'X'; } } const leaveHandler = () => { if (selectedChannel) { const oldChannel = document.getElementById(selectedChannel); if (oldChannel){ oldChannel.textContent = ''; } selectedChannel = null; } }",userChannels 283,"import { MultiplicationTable } from ""./MultiplicationTable"" import { range } from ""./utils"" export class FiniteGroup { private _identity: T get identity() { return this._identity } readonly order = this.table.size readonly elements = this.table.elements constructor (public readonly table: Readonly>) { if (!table.isRearangable()) throw new TypeError('Group can only be constructed from a rearangable multiplication table.') if (!table.isAssociative()) throw new TypeError('Group can only be constructed from an associative multiplication table.') const identity = table.findIdentity(); if (identity === null) throw new TypeError('Group must have a unique both-sided identity element.') this._identity = identity } hasElement(g: T): boolean { return this.table.indexMap.has(g) } multiply(...args: T[]): T { return args.reduce((a, b) => this.table.multiply(a, b)); } mul = this.multiply.bind(this) /** Quick inverse without type checks */ _inv = (g: number) => this.table.elements[this.table.data[g].indexOf(this._identity)]; inverse(g: T): T { const { table } = this if (!table.indexMap.has(g)) throw new TypeError('Cannot invert an unknown element.') const row = this.table.data[table.indexMap.get(g)!] const [MASK] = row.indexOf(this._identity) return this.table.elements[ [MASK] ] } inv = this.inverse.bind(this) private _classes: Set[] | null = null private _allClassesFound = false classOf(g: T): Set { const { elements, mul, inv } = this if (this._classes === null) this._classes = [] let c: Set | undefined if (c = this._classes.find(c => c.has(g))) return c c = new Set() for (let h of elements) { c.add(mul(h, g, inv(h))) } this._classes.push(c) return c } get classes(): readonly Set[] { if (this._classes === null) this._classes = [] if (this._allClassesFound) return this._classes for (let g of this.elements) { if (this._classes.some(c => c.has(g))) continue this._classes.push(this.classOf(g)) } this._allClassesFound = true return this._classes } } ",indexOfInverse 284,"import { Address } from ""@graphprotocol/graph-ts""; import { Creator } from ""../../generated/schema""; import * as constant from ""../constant""; import { getOrCreatePlatform } from ""./platform""; export function getOrCreateCreator(id: Address): Creator { let [MASK] = Creator.load(id.toHex()); if ( [MASK] ) { return [MASK] ; } [MASK] = new Creator(id.toHex()); [MASK] .address = id; [MASK] .nftTokenAddress = constant.NULL_ADDRESS; [MASK] .metadataURI = """"; [MASK] .twitterHandle = """"; [MASK] .lensHandle = """"; [MASK] .bio = """"; [MASK] .deliveryTime = constant.BIGINT_ZERO; [MASK] .demos = []; [MASK] .profilePicture = """"; [MASK] .userName = """"; [MASK] .price = constant.DEFAULT_PRICE; [MASK] .businessPrice = constant.DEFAULT_BUSINESS_PRICE; [MASK] .customServices = []; [MASK] .txHash = constant.NULL_ADDRESS; [MASK] .block = constant.BIGINT_ZERO; [MASK] .timestamp = constant.BIGINT_ZERO; [MASK] .updated = constant.BIGINT_ZERO; [MASK] .save(); let platform = getOrCreatePlatform(constant.Version.v1); platform.totalCreators = platform.totalCreators + 1; platform.save(); return [MASK] ; } export class CreatorStruct { nft: Address; metadataURI: string; constructor(nft: Address, metadataURI: string) { (this.nft = nft), (this.metadataURI = metadataURI); } } ",creator 285,"import {logger} from ""@atomist/automation-client""; import fs = require(""fs""); import _ = require(""lodash""); import stripJsonComments = require(""strip-json-comments""); import {Cluster} from ""./Cluster""; import {HttpAuth} from ""./HttpAuth""; import {SubatomicConfig} from ""./SubatomicConfig""; export class QMConfig { public static subatomic: SubatomicConfig; public static teamId: string; public static token: string; public static http: HttpAuth; public static cluster: Cluster; public static publicConfig() { return new PublicQMConfig(); } public static initialize() { const [MASK] = stripJsonComments(fs.readFileSync(this.getConfigFile()).toString()); const config = JSON.parse( [MASK] ); QMConfig.subatomic = config.subatomic; QMConfig.teamId = config.teamId; QMConfig.token = config.token; QMConfig.http = config.http; QMConfig.cluster = config.cluster || { enabled: process.env.NODE_ENV === ""production"", workers: 10, }; } private static getConfigFile() { let configFile = """"; logger.info(`Searching folder: config/`); fs.readdirSync(`config/`).forEach(file => { logger.info(`Found file: ${file}`); if (file.endsWith(""local.json"")) { configFile = file; } else if (file.endsWith(""config.json"") && configFile !== ""local.json"") { configFile = file; } else if (file.endsWith("".json"") && configFile === """") { configFile = file; } }); if (configFile === """") { logger.error(""Failed to read config file in config/ directory. Exiting.""); process.exit(1); } logger.info(`Using config file: ${configFile}`); return `config/${configFile}`; } } export class PublicQMConfig { public subatomic: SubatomicConfig = _.cloneDeep(QMConfig.subatomic); public teamId: string = _.cloneDeep(QMConfig.teamId); constructor() { this.subatomic.bitbucket.auth.email = """"; this.subatomic.bitbucket.auth.password = """"; this.subatomic.bitbucket.auth.username = """"; this.subatomic.bitbucket.cicdKey = """"; this.subatomic.bitbucket.cicdPrivateKeyPath = """"; this.subatomic.bitbucket.caPath = """"; this.subatomic.openshiftNonProd.auth.token = """"; } } QMConfig.initialize(); ",configRaw 286,"import { Component, OnInit, ViewChild, AfterViewInit, OnDestroy, ViewContainerRef } from '@angular/core'; import { Subscription } from 'rxjs'; import { ModalService } from './modal.service'; declare var $; @Component({ selector: 'app-modal', template: `
`, styleUrls: ['./modal.component.css'] }) export class ModalComponent implements OnInit , AfterViewInit, OnDestroy { @ViewChild('inner', { read: ViewContainerRef }) vcr; private subscription: Subscription; public display = 'none'; constructor(private modal: ModalService) { } ngAfterViewInit() { this.modal.vcr = this.vcr; } ngOnInit() { this.subscription = this.modal.content$.subscribe( value => { if (value) { console.log('dialog open'); this.display = ''; // this.open(); } else { this.display = 'none'; console.log('dialog none'); } }); } containerClick( [MASK] ) { [MASK] .stopPropagation(); } close() { $('iceword').modal('hide'); this.modal.close(); } ngOnDestroy() { this.subscription.unsubscribe(); } open() { $('icesword').modal(); } } ",$event 287,"import type { INetwork } from '@onekeyhq/engine/src/types'; import { CHAINS_DISPLAYED_IN_DEV } from '@onekeyhq/shared/src/engine/engineConsts'; import platformEnv from '@onekeyhq/shared/src/platformEnv'; import logoUrl from '@onekeyhq/kit/src/utils/data/logoUrl'; import { makeSelector } from './redux'; export type IManageNetworks = { allNetworks: INetwork[]; enabledNetworks: INetwork[]; }; const emptyArray = Object.freeze([]); const DEToken = { ""id"": ""e"", ""name"": ""DE"", ""impl"": ""evm"", ""symbol"": ""DE"", ""logoURI"": logoUrl.DE, ""enabled"": true, ""feeSymbol"": ""Gwei"", ""decimals"": 18, ""feeDecimals"": 9, ""balance2FeeDecimals"": 9, ""rpcURL"": ""http://dechain13.depaas.net:8545"", ""explorerURL"": ""127.0.0.1/"", ""shortName"": ""DE"", ""shortCode"": """", ""preset"": false, ""isTestnet"": false, ""nativeDisplayDecimals"": 6, ""tokenDisplayDecimals"": 4, ""extraInfo"": { ""chainId"": ""0x2328"", ""networkVersion"": ""9000"" }, ""accountNameInfo"": { ""default"": { ""prefix"": ""EVM"", ""category"": ""44'/60'"", ""template"": ""m/44'/60'/0'/0/$$INDEX$$"", ""coinType"": ""60"", ""label"": { ""id"": ""form__bip44_standard"" }, ""desc"": { ""id"": ""form__bip44_standard_desc"" }, ""recommended"": true }, ""etcNative"": { ""prefix"": ""ETC-Native"", ""category"": ""44'/61'"", ""template"": ""m/44'/61'/0'/0/$$INDEX$$"", ""coinType"": ""61"", ""label"": { ""id"": ""form__bip44_standard_cointype_61"" } }, ""ledgerLive"": { ""prefix"": ""Ledger Live"", ""category"": ""44'/60'"", ""template"": ""m/44'/60'/$$INDEX$$'/0/0"", ""coinType"": ""60"", ""label"": ""Ledger Live"" } }, ""blockExplorerURL"": { ""name"": ""127.0.0.1/"", ""address"": ""127.0.0.1/#/address?addressId={address}"", ""block"": ""127.0.0.1/block/{block}"", ""transaction"": ""127.0.0.1/transaction/{transaction}"" }, ""settings"": { ""feeInfoEditable"": true, ""privateKeyExportEnabled"": true, ""tokenEnabled"": true, ""txCanBeReplaced"": true, ""importedAccountEnabled"": true, ""hardwareAccountEnabled"": true, ""externalAccountEnabled"": true, ""watchingAccountEnabled"": true, ""isUTXOModel"": false, ""subNetworkSettings"": { ""evm--86"": { ""isIntegerGasPrice"": true } }, ""supportDeflationary"": true, ""supportFilterScam"": true, ""supportBatchTransfer"": true, ""batchTokenTransferApprovalRequired"": true, ""accountNameInfo"": { ""default"": { ""prefix"": ""EVM"", ""category"": ""44'/60'"", ""template"": ""m/44'/60'/0'/0/$$INDEX$$"", ""coinType"": ""60"", ""label"": { ""id"": ""form__bip44_standard"" }, ""desc"": { ""id"": ""form__bip44_standard_desc"" }, ""recommended"": true }, ""etcNative"": { ""prefix"": ""ETC-Native"", ""category"": ""44'/61'"", ""template"": ""m/44'/61'/0'/0/$$INDEX$$"", ""coinType"": ""61"", ""label"": { ""id"": ""form__bip44_standard_cointype_61"" } }, ""ledgerLive"": { ""prefix"": ""Ledger Live"", ""category"": ""44'/60'"", ""template"": ""m/44'/60'/$$INDEX$$'/0/0"", ""coinType"": ""60"", ""label"": ""Ledger Live"" } } } } export const { use: useManageNetworks, get: getManageNetworks } = makeSelector((selector, { useMemo }) => { const devModeEnable = selector((s) => s.settings.devMode)?.enable; const networks = selector((s) => s.runtime.networks) ?? emptyArray; const [allNetworks, enabledNetworks] = useMemo(() => { const chainsToHide = devModeEnable ? [] : CHAINS_DISPLAYED_IN_DEV; const all = networks.filter( (network) => !chainsToHide.includes(network.impl) && (platformEnv.isExtension ? !network.settings.disabledInExtension : true), ); let enabled = all.filter((network) => network.enabled); enabled = enabled.filter((e) => e.id !== 'evm--undefined') const [MASK] = enabled.findIndex((e) => e.id === 'evm--9000') if ( [MASK] !== -1) { enabled.splice( [MASK] , 1); enabled.splice(2, 0, DEToken); } return [all, enabled]; }, [devModeEnable, networks]); return { allNetworks, enabledNetworks, }; }); ",subscript 288,"import { HAQuerySelector, HAQuerySelectorEvent, OnListenDetail } from 'home-assistant-query-selector'; import HomeAssistantJavaScriptTemplates, { HomeAssistantJavaScriptTemplatesRenderer, HomeAssistant as HomeAssistantExtended } from 'home-assistant-javascript-templates'; import { HomeAssistant, Config, Secret, ServiceSecret, MoreInfoSecret, NavigateSecret } from 'types'; import { NAMESPACE, DEFAULT_THRESHOLD, GESTURES, EVENT, TYPEOF, DOMAIN_ENTITY_REGEXP } from '@constants'; import { logVersionToConsole, fetchConfig, getSecrets, isServiceSecret, isMoreInfoSecret, isNavigateSecret, isToggleMenuSecret, isJavaScriptSecret, compareArrays } from '@utilities'; import 'hammerjs'; class HomeAssistantSecretTaps { constructor() { const selector = new HAQuerySelector(); selector.addEventListener( HAQuerySelectorEvent.ON_LISTEN, (event: CustomEvent) => { Promise.all([ fetchConfig(), event.detail.HOME_ASSISTANT.element, event.detail.HOME_ASSISTANT_MAIN.element ]).then(([config, homeAssistant, homeAssistantMain]) => { if (config.enabled) { this._config = config; this._threshold = config.threshold || DEFAULT_THRESHOLD; this._ha = homeAssistant as HomeAssistant; this._main = homeAssistantMain as HTMLElement; this._log('configuration loaded, printing configuration...'); this._log(this._config); this._secrets = getSecrets(this._config, this._ha.hass.user); this._log(`secrets queried for ${this._ha.hass.user.name}, printing secrets...`); this._log(this._secrets); const haJsTemplates = new HomeAssistantJavaScriptTemplates( homeAssistant as HomeAssistantExtended, { autoReturn: false } ); haJsTemplates.getRenderer() .then((renderer: HomeAssistantJavaScriptTemplatesRenderer): void => { this._renderer = renderer; this._log('JavaScript renderer initialised, starting the plugin'); this._start(); }); } }); }, { once: true } ); selector.listen(); } private _config: Config; private _threshold: number; private _ha: HomeAssistant; private _main: HTMLElement; private _renderer: HomeAssistantJavaScriptTemplatesRenderer; private _secrets: Secret[]; private _taps: HammerManager; private _stack: string[] | null; private _eventTimeoutId: number; private _log(message: string | object): void { if (this._config.debug) { const logMessage = typeof message === TYPEOF.OBJECT ? JSON.stringify(message, null, 4) : message; console.log(`${NAMESPACE}: ${logMessage}`); } } private _callService(secret: ServiceSecret): void { const { service, data = {} } = secret; const [MASK] = service.match(DOMAIN_ENTITY_REGEXP); this._ha.hass.callService( [MASK] [1], [MASK] [2], data ); } private _openMoreInfo(secret: MoreInfoSecret): void { this._ha.dispatchEvent( new CustomEvent( EVENT.HASS_MORE_INFO, { detail: { entityId: secret.entity_id } } ) ); } private _navigate(secret: NavigateSecret): void { const { navigation_path, navigation_replace = false } = secret; const params: Parameters = [ null, '', navigation_path ]; if (navigation_replace) { window.history.replaceState(...params); } else { window.history.pushState(...params); } window.dispatchEvent( new CustomEvent( EVENT.LOCATION_CHANGED, { detail: { replace: navigation_replace } } ) ); } private _toggleMenu() { this._main.dispatchEvent( new Event( EVENT.HASS_TOGGLE_MENU ) ); } private _executeJavaScript(code: string): void { this._renderer.renderTemplate(code); } private _showNotification(message: string): void { this._ha.dispatchEvent( new CustomEvent( EVENT.HASS_NOTIFICATION, { detail: { message, dismissable: true } } ) ); } private _execute(secret: Secret): void { let executed = false; if (isServiceSecret(secret)) { this._callService(secret); executed = true; } else if (isMoreInfoSecret(secret)) { this._openMoreInfo(secret); executed = true; } else if (isNavigateSecret(secret)) { this._navigate(secret); executed = true; } else if (isToggleMenuSecret(secret)) { this._toggleMenu(); executed = true; } else if (isJavaScriptSecret(secret)) { this._executeJavaScript(secret.code.trim()); executed = true; } this._log( executed ? 'secret executed!' : 'secret NOT executed! secret with errors' ); this._log(secret); if (this._config.notification) { this._showNotification( executed ? 'secret taps successfully executed!' : 'secret taps failed! Review your secret config!' ); } } private _processTaps(): void { this._log('checking if there is a scret with the previous event stack'); const secret = this._secrets.find((secret: Secret): boolean => { return compareArrays(this._stack, secret.taps); }); if (secret) { this._log('secret found, executing secret'); this._execute(secret); } } private _trackTap(event: HammerInput): void { this._log(`event ${event.type} fired`); window.clearTimeout(this._eventTimeoutId); this._stack = this._stack || []; this._stack.push(event.type); this._log('printig event stack...'); this._log(this._stack.join(' » ')); this._eventTimeoutId = window.setTimeout(() => { this._processTaps(); this._stack = null; }, this._threshold); } private _start(): void { delete Hammer.defaults.cssProps; this._taps = new Hammer.Manager(this._ha); const commonProps = { threshold: 10, posThreshold: 15 }; const tripleTap = new Hammer.Tap({ event: GESTURES.TRIPLE_TAP, taps: 3, ...commonProps }); const doubleTap = new Hammer.Tap({ event: GESTURES.DOUBLE_TAP, taps: 2, ...commonProps }); const singleTap = new Hammer.Tap({ event: GESTURES.TAP, ...commonProps }); this._taps.add([ tripleTap, doubleTap, singleTap ]); tripleTap.recognizeWith([doubleTap, singleTap]); doubleTap.recognizeWith(singleTap); doubleTap.requireFailure(tripleTap); singleTap.requireFailure([doubleTap, tripleTap]); this._taps.on(Object.values(GESTURES).join(' '), (event: HammerInput): void => { this._trackTap(event); }); } } if (!window.HomeAssistantSecretTaps) { logVersionToConsole(); window.HomeAssistantSecretTaps = new HomeAssistantSecretTaps(); }",matches 289,"import { web3 } from ""@coral-xyz/anchor""; import * as anchor from ""@coral-xyz/anchor""; import idl from ""@/utils/smart-contract/event_protocol.json""; import { EventProtocol } from ""@/utils/smart-contract/event_protocol""; import { useAnchorWallet } from ""@solana/wallet-adapter-react""; import { useUserStore } from ""@/stores/userStore""; import { useMemo } from ""react""; export const useAnchor = () => { const wallet = useAnchorWallet(); const { network } = useUserStore(); const [MASK] = useMemo(() => { switch (network) { case ""solana"": return web3.clusterApiUrl(""devnet""); case ""sonic"": return ""https://devnet.sonic.game""; default: return web3.clusterApiUrl(""devnet""); } }, [network]); const provider = new anchor.AnchorProvider( new web3.Connection( [MASK] ), wallet!, ); anchor.setProvider(provider); const program = new anchor.Program(idl as EventProtocol, provider); const [master] = web3.PublicKey.findProgramAddressSync( [Buffer.from(""master"")], program.programId, ); return { program, provider, wallet, masterProgramAddress: master }; }; ",endpoint 290,"/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * 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. */ import {Aws, CfnOutput, Duration, RemovalPolicy, Stack, StackProps} from 'aws-cdk-lib'; import {Construct} from 'constructs'; import {LogGroup} from ""aws-cdk-lib/aws-logs""; import {HttpApi, HttpConnectionType} from ""@aws-cdk/aws-apigatewayv2-alpha""; import {CfnIntegration, CfnRoute, CfnStage} from ""aws-cdk-lib/aws-apigatewayv2""; import {Stream, StreamEncryption} from ""aws-cdk-lib/aws-kinesis""; import {Role, ServicePrincipal} from ""aws-cdk-lib/aws-iam""; import {NodejsFunction} from ""aws-cdk-lib/aws-lambda-nodejs""; import {CfnEventSourceMapping, EventSourceMapping, Runtime, StartingPosition, Tracing} from ""aws-cdk-lib/aws-lambda""; import {KinesisEventSource} from ""aws-cdk-lib/aws-lambda-event-sources""; import * as path from ""path""; import {AttributeType, BillingMode, Table, TableEncryption} from ""aws-cdk-lib/aws-dynamodb""; import { Dashboard, LogQueryVisualizationType, LogQueryWidget, PeriodOverride, SingleValueWidget } from ""aws-cdk-lib/aws-cloudwatch""; import {NagSuppressions} from ""cdk-nag""; ; // import * as sqs from 'aws-cdk-lib/aws-sqs'; export class Stacks extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props); const dashboard = new Dashboard(this, ""dashboard"", { dashboardName: ""AwsLambdaFanout"", periodOverride: PeriodOverride.AUTO }) const api = new HttpApi(this, ""aws-lambda-fanout-api"", { apiName: `aws-lambda-fanout-api`, createDefaultStage: true, }) const apiLogGroup = new LogGroup(this, ""aws-lambda-fanout-api-log-group"", { logGroupName: `/poc/aws-lambda-fanout/api`, removalPolicy: RemovalPolicy.DESTROY }) const defaultStage = api.defaultStage?.node.defaultChild as CfnStage defaultStage.accessLogSettings = { destinationArn: apiLogGroup.logGroupArn, format: JSON.stringify({ ""requestId"": ""$context.requestId"", ""ip"": ""$context.identity.sourceIp"", ""caller"": ""$context.identity.caller"", ""user"": ""$context.identity.user"", ""requestTime"": ""$context.requestTime"", ""httpMethod"": ""$context.httpMethod"", ""resourcePath"": ""$context.resourcePath"", ""status"": ""$context.status"", ""protocol"": ""$context.protocol"", ""responseLength"": ""$context.responseLength"" }) } const apiGatewayRole = new Role(this, 'api-gateway-role', { assumedBy: new ServicePrincipal('apigateway.amazonaws.com') }); const inStream = new Stream(this, 'InStream', { encryption: StreamEncryption.MANAGED }); const integration = new CfnIntegration(this, ""kinesis-integration"", { apiId: api.apiId, connectionType: HttpConnectionType.INTERNET.toString(), integrationSubtype: ""Kinesis-PutRecord"", integrationType: ""AWS_PROXY"", payloadFormatVersion: ""1.0"", requestParameters: { StreamName: inStream.streamName, Data: ""$request.body"", PartitionKey: ""$request.path.partitionKey"" }, credentialsArn: apiGatewayRole.roleArn, }) const route = new CfnRoute(this, ""kinesis-route"", { apiId: api.apiId, routeKey: ""POST /record/{partitionKey}"", target: `integrations/${integration.ref}` }) route.addDependsOn(integration) const outStream = new Stream(this, 'OutStream', { encryption: StreamEncryption.MANAGED }); const fanOutLambda = new NodejsFunction(this, ""fanout-function"", { memorySize: 256, timeout: Duration.seconds(5), runtime: Runtime.NODEJS_14_X, handler: ""lambdaHandler"", entry: path.join(__dirname, `/../runtime/fanout.ts`), environment: { ""STREAM_NAME"": outStream.streamName }, tracing: Tracing.ACTIVE }); const table = new Table(this, ""downstream-table"", { billingMode: BillingMode.PAY_PER_REQUEST, encryption: TableEncryption.AWS_MANAGED, partitionKey: { name: ""id"", type: AttributeType.STRING }, sortKey: { name: ""partition"", type: AttributeType.STRING }, pointInTimeRecovery: true }) const downstreamLambda = new NodejsFunction(this, ""downstream-function"", { memorySize: 256, timeout: Duration.seconds(5), runtime: Runtime.NODEJS_14_X, handler: ""lambdaHandler"", entry: path.join(__dirname, `/../runtime/downstream.ts`), environment: { ""TABLE_NAME"": table.tableName }, tracing: Tracing.ACTIVE }); fanOutLambda.addEventSource(new KinesisEventSource(inStream, { batchSize: 10, retryAttempts: 3, startingPosition: StartingPosition.LATEST })) const downstreamEventSource=new EventSourceMapping(this,""outstreamMapping"",{ eventSourceArn: outStream.streamArn, target: downstreamLambda, bisectBatchOnError: false, enabled: true, batchSize: 10, retryAttempts: 3, startingPosition: StartingPosition.LATEST, }) const cfnDownstreamEventSource=downstreamEventSource.node.defaultChild as CfnEventSourceMapping cfnDownstreamEventSource.addPropertyOverride('FilterCriteria', { ""Filters"": [ { ""Pattern"": ""{ \""partitionKey\"": [ {\""prefix\"": \""1_\""},\""CHAT\"",\""RAISE_HAND\""] }"" } ] }) inStream.grantRead(fanOutLambda) inStream.grantWrite(apiGatewayRole) outStream.grantWrite(fanOutLambda) outStream.grantRead(downstreamLambda) table.grantWriteData(downstreamLambda) const kinesisWidget = new SingleValueWidget({ height: 13, width: 12, title: ""Kinesis"", region: Aws.REGION, metrics: [ inStream.metricIncomingRecords({ label: ""InStream - IncomingRecords"", period: Duration.seconds(900), region: Aws.REGION, statistic: ""Sum"", }), outStream.metricIncomingRecords({ label: ""OutStream - IncomingRecords"", period: Duration.seconds(900), region: Aws.REGION, statistic: ""Sum"", }) ] }) const fanoutLambdaWidget = new SingleValueWidget({ height: 13, width: 12, title: ""Fanout Lambda"", region: Aws.REGION, metrics: [ fanOutLambda.metricInvocations({ label: ""Invocations"", period: Duration.seconds(900), region: Aws.REGION, statistic: ""Sum"", }), fanOutLambda.metricErrors({ label: ""Errors"", period: Duration.seconds(900), region: Aws.REGION, statistic: ""Sum"", }), fanOutLambda.metricThrottles({ label: ""Throttles"", period: Duration.seconds(900), region: Aws.REGION, statistic: ""Sum"", }), ] }) const [MASK] = new SingleValueWidget({ height: 13, width: 12, title: ""Downstream Lambda"", region: Aws.REGION, metrics: [ downstreamLambda.metricInvocations({ label: ""Invocations"", period: Duration.seconds(900), region: Aws.REGION, statistic: ""Sum"", }), downstreamLambda.metricErrors({ label: ""Errors"", period: Duration.seconds(900), region: Aws.REGION, statistic: ""Sum"", }), downstreamLambda.metricThrottles({ label: ""Throttles"", period: Duration.seconds(900), region: Aws.REGION, statistic: ""Sum"", }), ] }) const fanoutLogsQuery = new LogQueryWidget({ logGroupNames: [fanOutLambda.logGroup.logGroupName], height: 3, width: 12, region: Aws.REGION, queryString: ""filter @message like /Fanout success/ | stats count(*) as Count"", title: ""Fanout Lambda Success Count"", view: LogQueryVisualizationType.TABLE }) const downstreamLogsQuery = new LogQueryWidget({ logGroupNames: [downstreamLambda.logGroup.logGroupName], height: 3, width: 12, region: Aws.REGION, queryString: ""filter @message like /Downstream response/ | stats count(*) as Count"", title: ""Downstream Lambda Success Count"", view: LogQueryVisualizationType.TABLE }) dashboard.addWidgets(kinesisWidget, fanoutLambdaWidget, [MASK] , fanoutLogsQuery, downstreamLogsQuery) new CfnOutput(this, ""record-url"", { value: `${api.apiEndpoint}/record`, description: ""The api endpoint to send records to"", }) new CfnOutput(this, ""outstream-name"", { value: outStream.streamName, description: ""The name of the kinesis output stream. Point the KPL sample client at this stream"", }) //CDK Nag Suppressions NagSuppressions.addResourceSuppressionsByPath(this,""/AwsLambdaFanoutStack/api-gateway-role/DefaultPolicy/Resource"",[{ id: ""AwsSolutions-IAM5"", reason: ""Following directions here https://docs.aws.amazon.com/apigateway/latest/developerguide/integrating-api-with-aws-services-kinesis.html"" }]) NagSuppressions.addResourceSuppressionsByPath(this,""/AwsLambdaFanoutStack/fanout-function/ServiceRole/Resource"",[{ id: ""AwsSolutions-IAM4"", reason: ""I'm ok using managed policies for this example"" }]) NagSuppressions.addResourceSuppressionsByPath(this,""/AwsLambdaFanoutStack/fanout-function/ServiceRole/DefaultPolicy/Resource"",[{ id: ""AwsSolutions-IAM5"", reason: ""Wildcard is for xray support"" }]) NagSuppressions.addResourceSuppressionsByPath(this,""/AwsLambdaFanoutStack/downstream-function/ServiceRole/Resource"",[{ id: ""AwsSolutions-IAM4"", reason: ""I'm ok using managed policies for this example"" }]) NagSuppressions.addResourceSuppressionsByPath(this,""AwsLambdaFanoutStack/downstream-function/ServiceRole/DefaultPolicy/Resource"",[{ id: ""AwsSolutions-IAM5"", reason: ""Wildcard is for xray support"" }]) NagSuppressions.addResourceSuppressionsByPath(this,""/AwsLambdaFanoutStack/LogRetentionaae0aa3c5b4d4f87b02d85b201efdd8a/ServiceRole/Resource"",[{ id: ""AwsSolutions-IAM4"", reason: ""I'm ok using managed policies for this example"" }]) NagSuppressions.addResourceSuppressionsByPath(this,""/AwsLambdaFanoutStack/LogRetentionaae0aa3c5b4d4f87b02d85b201efdd8a/ServiceRole/DefaultPolicy/Resource"",[{ id: ""AwsSolutions-IAM5"", reason: ""Wildcard is for log rentetion support"" }]) NagSuppressions.addResourceSuppressionsByPath(this,""/AwsLambdaFanoutStack/kinesis-route"",[{ id: ""AwsSolutions-APIG4"", reason: ""I'm ok with no api authorization for this example"" }]) } } ",downstreamLambdaWidget 291,"/** * SPDX-License-Identifier: Apache-2.0 */ import * as WalletMigration from ""fabric-wallet-migration""; import { Wallet, Wallets, X509Identity } from ""fabric-network""; import { promises as fs } from ""node:fs""; import * as os from ""node:os""; import * as path from ""node:path""; const oldWalletPath = path.resolve(__dirname, "".."", "".."", ""fixtures"", ""wallet-v1""); describe(""Wallet migration"", () => { let newWalletPath: string; let oldWallet: Wallet; let newWallet: Wallet; async function createTempDir(): Promise { const prefix = path.join(os.tmpdir(), path.sep); return await fs.mkdtemp(prefix); } async function migrate(oldWallet: Wallet, newWallet: Wallet): Promise { const migratedLabels: string[] = []; const identityLabels = await oldWallet.list(); for (const label of identityLabels) { const identity = await oldWallet.get(label); if (identity) { await newWallet.put(label, identity); migratedLabels.push(label); } } return migratedLabels; } async function getAll(wallet: Wallet): Promise> { const identities = new Map(); const labels = await wallet.list(); for (const label of labels) { const identity = await wallet.get(label); if (identity) { identities.set(label, identity as X509Identity); } } return identities; } beforeAll(async () => { const walletStore = await WalletMigration.newFileSystemWalletStoreV1(oldWalletPath); oldWallet = new Wallet(walletStore); newWalletPath = await createTempDir(); newWallet = await Wallets.newFileSystemWallet(newWalletPath); await migrate(oldWallet, newWallet); }); afterAll(async () => { await fs.rm(newWalletPath, { recursive: true, force: true }); }); it(""has expected labels"", async () => { const labels = await newWallet.list(); expect(labels).toEqual([""user1"", ""user2""]); }); it(""contains X.509 identities"", async () => { const identities = await getAll(newWallet); identities.forEach((identity) => { expect(identity.type).toEqual(""X.509""); }); }); it(""identities have matching certificates"", async () => { const identities = await getAll(newWallet); identities.forEach((identity) => { expect(identity.credentials.certificate).toMatch(/.+/); }); }); it(""identities have non-empty private keys"", async () => { const identities = await getAll(newWallet); identities.forEach((identity) => { expect(identity.credentials.privateKey).toMatch(/.+/); }); }); it(""identities match"", async () => { const oldIdentities = await getAll(oldWallet); const newIdentities = await getAll(newWallet); oldIdentities.forEach(( [MASK] , label) => { const newIdentity = newIdentities.get(label); expect(newIdentity).toEqual( [MASK] ); }); }); }); ",oldIdentity 292,"import { ModuleObserver } from './bus'; import { ModuleAction } from './models'; import { ModuleEvents, appKey } from './events'; import { Container } from './container-abstract'; export class Orchestrator extends ModuleObserver { private bindTypeContainer = new Map(); private shippedContainersLabel = new Map(); private shippedContainers = new Set(); private logger = console; constructor(id: string = 'Orchestrator') { super(id); } public async notification(event: string, emitter: string, action: ModuleAction) { this.logger.info({ msg: `${emitter}: ${action.message}` }); switch (event) { case `${appKey}.${ModuleEvents.closeAll}`: await this.closeShipping(); break; default: this.logger.debug({ message: `the event ${event} by the ${emitter} is emitted and there is no action to handle it`, }); break; } } public labelContainer(map: T) { for (const [label, container] of Object.entries(map)) { this.bindTypeContainer.set(label, container); } } public async shipContainers() { for (const [type, container] of this.bindTypeContainer) { if (!this.shippedContainersLabel.get(type)) { try { await this.prepareContainer(type, container); this.logger.info({ msg: `shipped container: ${container.id || container.name}`, }); } catch (error) { this.logger.error({ error: `can't ship container: ${container.id || container.name}`, stck: error, }); } } } } private async prepareContainer(type: string, container: any) { const iContainer = new container(); if (iContainer.dependencyTypes) { const start = iContainer.start(await this.constructDep(iContainer.dependencyTypes)); if (start instanceof Promise) { await start; } } else { if (iContainer.start) { const start = iContainer.start(); if (start instanceof Promise) { await start; } } } this.shippedContainers.add(iContainer); this.shippedContainersLabel.set(type, iContainer); } private async constructDep( [MASK] : string[]) { const injectedDependencies: { [key: string]: Container; } = {}; for (const dependency of [MASK] ) { if (!this.shippedContainersLabel.get(dependency)) { await this.prepareContainer(dependency, this.bindTypeContainer.get(dependency)); } injectedDependencies[dependency] = this.shippedContainersLabel.get(dependency); } return injectedDependencies; } public async closeShipping() { for (const container of this.shippedContainers) { if (container.close) { try { const close = container.close(); if (close instanceof Promise) { await close; } this.logger.info({ msg: `closed container: ${container.id || container.name}`, }); } catch (error) { this.logger.error({ error: `can't close container: ${container.id || container.name}`, stck: error, }); } } else { this.logger.info({ msg: `no close policy at container: ${container.id || container.name}`, }); } } } public findContainer(label: string) { if (this.shippedContainersLabel.get(label)) { return this.shippedContainersLabel.get(label); } else { throw new Error(`Container ${label} is not ready yet`); } } } ",dependencies 293,"import { Logger } from ""log4js""; import Operator, { ResourceEventType, ResourceEvent, ResourceMeta, ResourceMetaImpl } from '@dot-i/k8s-operator'; import { setIntervalAsync, SetIntervalAsyncTimer } from 'set-interval-async/fixed'; import * as k8s from '@kubernetes/client-node'; import {Mutex} from 'async-mutex'; import * as ngrok from 'ngrok'; const annotation = 'vasu1124/ngrok'; const mutex = new Mutex(); interface ngrokConnection { url: string; target: string; name: string | undefined; namespace: string | undefined; } export default class NgrokController extends Operator { ngrokMap: Map = new Map(); reconcileTimer: SetIntervalAsyncTimer<[]>; constructor(protected log: Logger, [MASK] : number) { super(log); // Inittialize timer this.reconcileTimer = setIntervalAsync(async () => { this.log.debug(""reconcileTimer: Running reconcile from timer""); await this.reconcile(); }, [MASK] ); } protected async init() { await this.watchResource('', 'v1', 'services', async (e) => { const object: k8s.V1Service = e.object; this.log.debug(""received event ..."", e.type); switch (e.type) { case ResourceEventType.Added: case ResourceEventType.Modified: this.handleCreateOrUpdateResource(object); break; case ResourceEventType.Deleted: this.handleDeleteResource(object); break; } }); } private async reconcile() { this.log.debug(""reconciling ...""); const { response, body } = await this.k8sApi.listServiceForAllNamespaces(); //any changes missed? body.items.forEach(object => this.handleCreateOrUpdateResource(object)); //any deletions missed? this.ngrokMap.forEach( (value, key) => { const service2delete = body.items.filter(object => object.metadata?.uid === key) //key in active ngrokMap, but no service object if(service2delete.length === 0) this.handleDeleteResource({ ""metadata"": { ""uid"": key, ""name"": value.name, ""namespace"": value.namespace }}); }); } private async handleDeleteResource(object: k8s.V1Service): Promise { if (!this.ngrokMap.has(object.metadata?.uid)) { this.log.warn(""No active Ngrok for this service "" + object.metadata?.uid); return; } const uid = object.metadata?.uid; await this.disconnectNgrok(uid, this.ngrokMap.get(object.metadata?.uid)); } private handleCreateOrUpdateResource(object: k8s.V1Service): void { let uid = object.metadata?.uid; if (this.ngrokMap.has(uid)) { //already exists if (object.spec?.type === ""LoadBalancer"") { //modified? let target = this.resolveTarget(object); if (this.ngrokMap.get(uid)?.target !== target) { //changes required this.disconnectNgrok(uid, this.ngrokMap.get(object.metadata?.uid)) .then(() => { return this.connectNgrok(uid, {url: """", target: target, name: object.metadata?.name, namespace: object.metadata?.namespace}); }) .then((url) => { if (url !== undefined) { let rmeta = ResourceMetaImpl.createWithPlural(""services"", object); let hostname = url.replace(""https://"", """"); let statusPatch = { ""loadBalancer"": { ""ingress"": [{ ""hostname"": hostname }] } }; return this.patchResourceStatus(rmeta, statusPatch); } }) .then((rmeta) => { this.log.info(""Service status patched: "" + object.metadata?.name + ""."" + object.metadata?.namespace); }); } else this.log.debug(""Already Ngroked!""); } else { //modified: remove ngrok this.disconnectNgrok(uid, this.ngrokMap.get(object.metadata?.uid)) .then(() => { let rmeta = ResourceMetaImpl.createWithPlural(""services"", object); let statusPatch = { ""loadBalancer"": { ""ingress"": [{ ""hostname"": ""not.available"" }] } }; return this.patchResourceStatus(rmeta, statusPatch); }) .then((rmeta) => { this.log.info(""Service status disconnected: "" + object.metadata?.name + ""."" + object.metadata?.namespace); }); } } else if (object.spec?.type === ""LoadBalancer"") { //added let target = this.resolveTarget(object); this.connectNgrok(uid, {url: """", target: target, name: object.metadata?.name, namespace: object.metadata?.namespace}) .then((url) => { if (url !== undefined) { let rmeta = ResourceMetaImpl.createWithPlural(""services"", object); let hostname = url.replace(""https://"", """"); let statusPatch = { ""loadBalancer"": { ""ingress"": [{ ""hostname"": hostname }] } }; return this.patchResourceStatus(rmeta, statusPatch); } }) .then((rmeta) => { this.log.info(""Service status patched: "" + object.metadata?.name + ""."" + object.metadata?.namespace); }); } } private async disconnectNgrok(uid: string | undefined, nc: ngrokConnection | undefined): Promise { // ngrok.disconnect() path needs to be safeguarded with a mutex this.ngrokMap.delete(uid); const release = await mutex.acquire(); if (nc !== undefined) try { //must disconnect two urls: https and http. await ngrok.disconnect(nc.url); await ngrok.disconnect(nc.url?.replace(""https"", ""http"")); this.log.info(`Ungroked: ${nc.name}.${nc.namespace} disconnected from ${nc.url}`); } catch (error) { this.log.error(error); await ngrok.kill(); this.ngrokMap.clear(); } finally { release(); } } private async connectNgrok(uid: string | undefined, nc: ngrokConnection): Promise { // ngrok.connect() path needs to be safeguarded with a mutex const release = await mutex.acquire(); try { nc.url = await ngrok.connect({ proto: 'http', addr: nc.target, onLogEvent: msg => { this.log.debug(msg) }, onStatusChange: status => { this.log.warn(status) }, }); this.ngrokMap.set(uid, nc); this.log.info(`Ngroked: ${nc.name}.${nc.namespace}/${nc.target} connected to ${nc.url}`); return nc.url; } catch (error) { this.log.error(error); await ngrok.kill(); this.ngrokMap.clear(); } finally { release(); } return undefined; } private resolveTarget(object: k8s.V1Service): string { let port = 8080 let portname: string | undefined; //annotations exist? if (object.metadata!.annotations === undefined) portname = undefined; else portname = object.metadata!.annotations![annotation]; if (portname !== undefined) { //annotation exists const portobj = object.spec!.ports!.filter(object => object.name === portname); //portmap refernce exists? if (portobj !== undefined && portobj.length >= 1) { this.log.debug(`Annotation '${annotation}' found. Choosing first portmap: `, portobj[0]); port = portobj[0].port; } else { portname = undefined; this.log.warn(`Annotation '${annotation}' not found.`); } } if (portname === undefined && object.spec!.ports !== undefined && object.spec!.ports.length >= 1) { port = object.spec!.ports[0].port; this.log.debug(""Defaulting to portmap: "", object.spec!.ports[0]); } else if (portname === undefined) { this.log.warn(""Could not associate any port. Defaulting to "" + port); } return object.spec!.clusterIP + "":"" + port; } }",reconcileInterval 294,"import { DramaList } from '../../entity/HomepageData'; import HomepageData from '../../entity/HomepageData'; import Logger from '../../utils/Logger'; import EpisodeInfo from '../../entity/EpisodeInfo'; import VideoInfo from '../../entity/VideoInfo'; import EpisodeList from '../../entity/EpisodeList'; import VideoDetailInfo from '../../entity/VideoDetailInfo'; import HttpUtils from '../../utils/HttpUtils'; import DataSource from '../DataSource'; import { select, selectAttributeValue, selectFirst, selectTextContent, textContent } from '../../thirdpart/htmlsoup'; const BASE_URL = 'http://www.yinghuavideo.com/' /** * 樱花动漫 (http://www.yinghuavideo.com) 视频源 */ export default class YingHuaDataSource implements DataSource { getKey(): string { return 'key_yinghuavideo' } async search( [MASK] : string, page: number): Promise { let url = BASE_URL + ""search/"" + encodeURIComponent( [MASK] ) + ""/?page="" + page let videos: VideoInfo[] = [] let doc = await HttpUtils.getHtml(url) const list = select(doc, 'div.fire > div > ul > li') list.forEach((li) => { let a = selectFirst(li, ""a"") let img = selectFirst(li, 'img') videos.push({ sourceKey: this.getKey(), url: 'http://www.yinghuavideo.com' + a.attr('href'), imgUrl: img.attr('src'), title: img.attr('alt'), episode: selectTextContent(li, 'span:nth-child(3) > font') }) }) return videos } async getHomepageData(): Promise { let url = BASE_URL const doc = await HttpUtils.getHtml(url) const bannerList: VideoInfo[] = [] const categoryList: DramaList[] = [] const lis = select(doc, 'div.hero-wrap > ul.heros > li') lis.forEach((li) => { const a = selectFirst(li, ""a"") const img = selectFirst(li, 'img') bannerList.push({ sourceKey: this.getKey(), url: 'http://www.yinghuavideo.com' + a.attr('href'), imgUrl: img.attr('src'), title: a.attr('title'), episode: selectTextContent(li, 'em') }) }) const titles = select(doc, 'div.firs > div.dtit') const videoList = select(doc, 'div.firs > div.img') const count = Math.min(titles.length, videoList.length) for (let i = 0; i < count; i++) { const title = titles[i] const list = videoList[i] const videos: VideoInfo[] = [] const lis = select(list, 'ul > li') lis.forEach((li) => { let a = selectFirst(li, ""a"") let img = selectFirst(li, 'img') videos.push({ sourceKey: this.getKey(), url: 'http://www.yinghuavideo.com' + a.attr('href'), imgUrl: img.attr('src'), title: selectTextContent(li, 'p.tname > a'), episode: selectTextContent(li, 'p:nth-child(3) > a') }) }) categoryList.push({ title: selectTextContent(title, ""h2 > a""), moreUrl: BASE_URL + selectAttributeValue(title, 'span > a', 'href'), videoList: videos }) } return { bannerList: bannerList, categoryList: categoryList } } async getVideoList(page: number): Promise { let url = ""http://www.bimiacg4.net/type/riman-"" + page let doc = await HttpUtils.getHtml(url) let drama = selectFirst(doc, 'ul.drama-module') return this.parseVideoList(drama) } private async parseVideoList(drama): Promise { // let drama = selectFirst(doc, 'ul.drama-module') Logger.e(this, 'parseHtml drama=' + drama) let elements = select(drama, 'li') Logger.e(this, 'parseHtml elements=' + elements) let videoList: VideoInfo[] = [] // TODO 代码优化 elements.forEach((el) => { Logger.e(this, ""parseHtml el="" + el) let a = selectFirst(el, ""div.info > a"") videoList.push({ sourceKey: this.getKey(), url: ""http://www.bimiacg4.net"" + a.attr('href'), imgUrl: selectAttributeValue(el, 'img', 'src'), title: textContent(a), episode: selectTextContent(el, ""div.info > p > span.fl"") }) }) return videoList } async getVideoDetailInfo(url: string): Promise { let doc = await HttpUtils.getHtml(url); Logger.e(this, 'getVideoDetailInfo 1') let title = selectTextContent(doc, 'div.fire > div.rate > h1') Logger.e(this, 'getVideoDetailInfo title=' + title) let recommends: VideoInfo[] = [] let list = select(doc, 'div.sido > div.pics > ul > li') list.forEach((li) => { let a = selectFirst(li, ""a"") let img = selectFirst(li, 'img') recommends.push({ sourceKey: this.getKey(), url: 'http://www.yinghuavideo.com' + a.attr('href'), imgUrl: img.attr('src'), title: img.attr('alt'), episode: selectTextContent(li, 'span:nth-child(3) > font') }) }) let episodes: EpisodeList[] = [] let lis = select(doc, '#main0 > div > ul > li') Logger.e(this, 'getVideoDetailInfo lis.len=' + lis.length) let episodeList: EpisodeList = { title: ""路线0"", episodes: [] } lis.reverse().forEach((li) => { const a = selectFirst(li, 'a') let info: EpisodeInfo = { link: 'http://www.yinghuavideo.com' + a.attr('href'), title: textContent(a), desc: title + ' ' + textContent(a) } Logger.e(this, 'getEpisodes info=' + JSON.stringify(info)) episodeList.episodes.push(info) }) episodes.push(episodeList) let info: VideoDetailInfo = { sourceKey: this.getKey(), title: title, url: url, desc: selectTextContent(doc, ""div.fire > div.info"").trim(), coverUrl: selectAttributeValue(doc, ""div.fire > div.thumb > img"", 'src'), category: selectTextContent(doc, 'div.fire > div.rate > div.sinfo > span:nth-child(3) > a'), director: '', updateTime: '', protagonist: '', episodes: episodes, recommends: recommends } return info } async parseVideoUrl(link: string): Promise { Logger.e(this, 'parseVideoUrl link=' + link) const doc = await HttpUtils.getHtml(link) let url = selectAttributeValue(doc, 'a#play_1', 'onclick') Logger.e(this, 'parseVideoUrl old url=' + url) if (url) { url = url.substring(url.indexOf('\'') + 1, url.lastIndexOf('\'')) const i = url.indexOf('$') if (i >= 0) { url = url.substring(0, i) } } Logger.e(this, 'parseVideoUrl url=' + url) return url; } }",keyword 295,"import * as os from ""os""; import * as path from ""path""; import * as fs from ""fs""; import * as cache from ""@actions/cache""; import * as core from ""@actions/core""; import * as tc from ""@actions/tool-cache""; import { GitHub, getOctokitOptions } from ""@actions/github/lib/utils""; import { throttling } from ""@octokit/plugin-throttling""; const ThrottlingOctokit = GitHub.plugin(throttling); interface ToolInfo { owner: string; project: string; tag: string; osPlatform: string; osArch: string; } async function run() { try { // set up auth/environment const token = process.env['GITHUB_TOKEN'] || core.getInput(""token"") const octokit = new ThrottlingOctokit({ throttle: { onRateLimit: (retryAfter, options) => { core.warning( `RateLimit detected for request ${options.method} ${options.url}.` ); core.info(`Retrying after ${retryAfter} seconds.`); return true; }, onSecondaryRateLimit: (retryAfter, options) => { core.warning( `SecondaryRateLimit detected for request ${options.method} ${options.url}.` ); core.info(`Retrying after ${retryAfter} seconds.`); return true; }, }, ...getOctokitOptions(token), }) const repo = core.getInput(""repo""); if (!repo) { throw new Error( `Repo was not specified` ) } let tag = core.getInput(""tag""); tag = !tag ? ""latest"" : tag const cacheEnabled = (core.getInput(""cache"") === ""enable"") && tag !== ""latest"" && tag !== """"; const [owner, project] = repo.split(""/"") let osMatch: string[] = [] // Determine Platform let osPlatform = core.getInput(""platform""); if (osPlatform === """") { switch (os.platform()) { case ""linux"": osPlatform = ""linux""; break; case ""darwin"": osPlatform = ""darwin""; break; case ""win32"": osPlatform = ""windows""; break; default: core.setFailed(""Unsupported operating system - $this action is only released for Darwin, Linux and Windows""); return; } } osMatch.push(osPlatform) core.info(`==> System reported platform: ${os.platform()}`) core.info(`==> Using platform: ${osPlatform}`) // Determine Architecture let osArch = core.getInput(""arch""); if (osArch === """") { osArch = os.arch() switch (os.arch()) { case ""x64"": osMatch.push(""x86_64"", ""x64"", ""amd64"") break; default: osMatch.push(os.arch()) return; } } else { osMatch.push(osArch) } core.info(`==> System reported arch: ${os.arch()}`) core.info(`==> Using arch: ${osArch}`) // Determine File Extensions (if any) const extMatching = core.getInput(""extension-matching"") === ""enable""; let extension = core.getInput(""extension""); let extMatchRegexForm = """"; if (extMatching) { if (extension === """") { extMatchRegexForm = ""\.(tar.gz|zip)""; core.info(`==> Using default file extension matching: ${extMatchRegexForm}`); } else { extMatchRegexForm = extension; core.info(`==> Using custom file extension matching: ${extMatchRegexForm}`); } } else { core.info(""==> File extension matching disabled""); } // Determine whether renaming is in use let renameTo = core.getInput(""rename-to""); if (renameTo !== """") { core.info(`==> Will rename downloaded release to ${renameTo}`); } let chmodTo = core.getInput(""chmod""); if (chmodTo !== """") { core.info(`==> Will chmod downloaded release asset to ${chmodTo}`); } let toolInfo: ToolInfo = { owner: owner, project: project, tag: tag, osArch: osArch, osPlatform: osPlatform }; let dest = toolPath(toolInfo); // If the user has specified a custom location where the binaries are in the release // asset, we need to use modify the default path, joining the custom folder to the // default path. let binariesLocation = core.getInput(""binaries-location""); let finalBinLocation = dest; if (binariesLocation !== """") { core.info(`==> Given bin location: ${binariesLocation}`); finalBinLocation = path.join(dest, binariesLocation); } core.info(`==> Binaries will be located at: ${finalBinLocation}`); // Look in the cache first. let cacheKey = cachePrimaryKey(toolInfo); if (cacheEnabled && cacheKey !== undefined) { let ok = await cache.restoreCache([dest], cacheKey); if (ok !== undefined) { core.info(`Found ${project} in the cache: ${dest}`) core.addPath(dest); return; } } let getReleaseUrl; if (tag === ""latest"") { getReleaseUrl = await octokit.rest.repos.getLatestRelease({ owner: owner, repo: project, }) } else { getReleaseUrl = await octokit.rest.repos.getReleaseByTag({ owner: owner, repo: project, tag: tag, }) } let osMatchRegexForm = `(${osMatch.join('|')})` let re = new RegExp(`${osMatchRegexForm}.*${osMatchRegexForm}.*${extMatchRegexForm}`) let asset = getReleaseUrl.data.assets.find(obj => { core.info(`searching for ${obj.name} with ${re.source}`) let [MASK] = obj.name.toLowerCase() return re.test( [MASK] ) }) if (!asset) { const found = getReleaseUrl.data.assets.map(f => f.name) throw new Error( `Could not find a release for ${tag}. Found: ${found}` ) } const url = asset.url core.info(`Downloading ${project} from ${url}`) const binPath = await tc.downloadTool(url, undefined, `token ${token}`, { accept: 'application/octet-stream' } ); const extractFn = getExtractFn(asset.name) if (extractFn !== undefined) { // Release is an archive file so extract it to the destination const extractFlags = getExtractFlags(asset.name) if (extractFlags !== undefined) { core.info(`Attempting to extract archive with custom flags ${extractFlags}`) await extractFn(binPath, dest, extractFlags); } else { await extractFn(binPath, dest); } core.info(`Automatically extracted release asset ${asset.name} to ${dest}`); const bins = fs.readdirSync(finalBinLocation, { withFileTypes: true }) .filter(item => item.isFile()) .map(bin => bin.name); if (bins.length === 0) throw new Error(`No files found in ${finalBinLocation}`); else if (bins.length > 1 && renameTo !== """") { core.warning(""rename-to parameter ignored when installing \ a release from an archive that contains multiple files.""); } if (chmodTo !== """") { bins.forEach(bin => { const binPath = path.join(finalBinLocation, bin); try { fs.chmodSync(binPath, chmodTo); core.info(`chmod'd ${binPath} to ${chmodTo}`) } catch (chmodErr) { core.setFailed(`Failed to chmod ${binPath} to ${chmodTo}: ${chmodErr}`); } }); } } else { // As it wasn't an archive we've just downloaded it as a blob, this uses an auto-assigned name which will // be a UUID which is likely meaningless to the caller. If they have specified a rename-to and a chmod // parameter then this is where we apply those. // Regardless of any rename-to parameter we still need to move the download to the actual destination // otherwise it won't end up on the path as expected core.info( `Release asset ${asset.name} did not have a recognised file extension, unable to automatically extract it`) try { fs.mkdirSync(dest, { 'recursive': true }); const outputPath = path.join(dest, renameTo !== """" ? renameTo : path.basename(binPath)); core.info(`Created output directory ${dest}`); try { fs.renameSync(binPath, outputPath); core.info(`Moved release asset ${asset.name} to ${outputPath}`); if (chmodTo !== """") { try { fs.chmodSync(outputPath, chmodTo); core.info(`chmod'd ${outputPath} to ${chmodTo}`) } catch (chmodErr) { core.setFailed(`Failed to chmod ${outputPath} to ${chmodTo}: ${chmodErr}`); } } } catch (renameErr) { core.setFailed(`Failed to move downloaded release asset ${asset.name} from ${binPath} to ${outputPath}: ${renameErr}`); } } catch (err) { core.setFailed(`Failed to create required output directory ${dest}`); } } if (cacheEnabled && cacheKey !== undefined) { try { await cache.saveCache([dest], cacheKey); } catch (error) { const typedError = error as Error; if (typedError.name === cache.ValidationError.name) { throw error; } else if (typedError.name === cache.ReserveCacheError.name) { core.info(typedError.message); } else { core.warning(typedError.message); } } } core.info(`Adding ${finalBinLocation} to the path`); core.addPath(finalBinLocation); core.info(`Successfully installed ${project}`); core.info(`Binaries available at ${finalBinLocation}`); } catch (error) { if (error instanceof Error) { core.setFailed(error.message); } else { core.setFailed(""catastrophic failure, please file an issue"") } } } function cachePrimaryKey(info: ToolInfo): string | undefined { // Currently not caching ""latest"" versions of the tool. if (info.tag === ""latest"") { return undefined; } return ""action-install-gh-release/"" + `${info.owner}/${info.project}/${info.tag}/${info.osPlatform}-${info.osArch}`; } function toolPath(info: ToolInfo): string { return path.join(getCacheDirectory(), info.owner, info.project, info.tag, `${info.osPlatform}-${info.osArch}`); } function getCacheDirectory() { const cacheDirectory = process.env['RUNNER_TOOL_CACHE'] || ''; if (cacheDirectory === '') { core.warning('Expected RUNNER_TOOL_CACHE to be defined'); } return cacheDirectory; } function getExtractFn(assetName: any) { if (assetName.endsWith('.tar.gz') || assetName.endsWith('.tar.bz2')) { return tc.extractTar; } else if (assetName.endsWith('.zip')) { return tc.extractZip; } else { return undefined; } } function getExtractFlags(assetName: any) { if (assetName.endsWith('tar.bz2')) { return ""xj""; } else { return undefined; } } run(); ",normalized_obj_name 296,"import { AmplifyAppsResponse, AmplifyBuildLogsResponse, TriggerBuildRequest, TriggerBuildResponse } from '../types/amplify'; const API_BASE_URL = '/api'; export const amplifyApi = { /** * Get all Amplify apps for a specific environment */ async getApps(environment: string, profile?: string): Promise { const params = new URLSearchParams({ environment }); if (profile) { params.append('profile', profile); } const response = await fetch(`${API_BASE_URL}/amplify/apps?${params}`); if (!response.ok) { const error = await response.text(); throw new Error(`Failed to fetch Amplify apps: ${error}`); } return response.json(); }, /** * Get build logs for a specific job */ async getBuildLogs( appId: string, branchName: string, jobId: string, profile?: string ): Promise { const params = new URLSearchParams({ appId, branchName, jobId }); if (profile) { params.append('profile', profile); } const response = await fetch(`${API_BASE_URL}/amplify/build-logs?${params}`); if (!response.ok) { const error = await response.text(); throw new Error(`Failed to fetch build logs: ${error}`); } return response.json(); }, /** * Trigger a new build for a branch */ async triggerBuild( [MASK] : TriggerBuildRequest): Promise { const response = await fetch(`${API_BASE_URL}/amplify/trigger-build`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify( [MASK] ), }); if (!response.ok) { const error = await response.text(); throw new Error(`Failed to trigger build: ${error}`); } return response.json(); }, };",request 297,"import { Analytics } from ""@plattar/plattar-analytics""; import { Project, Scene, Server } from ""@plattar/plattar-api""; import { Configurator } from ""@plattar/plattar-services""; import { Util } from ""../util/util""; import { ARViewer } from ""../viewers/ar-viewer""; import QuicklookViewer from ""../viewers/quicklook-viewer""; import RealityViewer from ""../viewers/reality-viewer""; import SceneViewer from ""../viewers/scene-viewer""; import { LauncherAR } from ""./launcher-ar""; import { DecodedConfiguratorState, SceneProductData } from ""../util/configurator-state""; import version from ""../version""; export interface ConfiguratorAROptions { readonly state: DecodedConfiguratorState; readonly useARBanner: boolean; } /** * Performs AR functionality related to Plattar Scenes */ export class ConfiguratorAR extends LauncherAR { // analytics instance private _analytics: Analytics | null = null; private _options: ConfiguratorAROptions; // this thing controls the actual AR view // this is setup via .init() function private _ar: ARViewer | null; constructor(options: ConfiguratorAROptions) { super(); if (!options.state) { throw new Error(""ConfiguratorAR.constructor(state) - state must be defined""); } this._options = options; this._ar = null; } private _SetupAnalytics(): void { const scene: Scene = this._options.state.scene; let analytics: Analytics | null = null; // setup scene stuff (if any) if (scene) { analytics = new Analytics(scene.attributes.application_id); analytics.origin = Server.location().type; this._analytics = analytics; analytics.data.push(""type"", ""scene-ar""); analytics.data.push(""sdkVersion"", version); analytics.data.push(""sceneId"", scene.id); analytics.data.push(""sceneTitle"", scene.attributes.title); const application: Project | undefined = scene.relationships.find(Project); // setup application stuff (if any) if (application) { analytics.data.push(""applicationId"", application.id); analytics.data.push(""applicationTitle"", application.attributes.title); if (this._options.useARBanner) { this.options.banner = { title: application.attributes.title, subtitle: scene.attributes.title, button: 'Visit' } } } } } /** * Composes a Scene into an AR Model (remote operation) that can be used to launch * an AR File */ private async _Compose(output: ""glb"" | ""usdz"" | ""vto""): Promise { const objects: Array = this._options.state.state.array(); if (objects.length <= 0) { throw new Error(""ConfiguratorAR.Compose() - cannot proceed as scene does not contain AR components""); } // define our configurator const configurator: Configurator = new Configurator(); configurator.server = Server.location().type; configurator.output = output; let totalARObjectCount: number = 0; objects.forEach((object: SceneProductData) => { if (object.meta_data.augment) { if (object.meta_data.type === ""scenemodel"") { configurator.addModel(object.scene_product_id); } else { configurator.addSceneProduct(object.scene_product_id, object.product_variation_id); } totalARObjectCount++; } }); if (totalARObjectCount <= 0) { throw new Error(""ConfiguratorAR.Compose() - cannot proceed as scene does not contain any enabled AR components""); } const [MASK] : any = await configurator.get(); return [MASK] .filename; } /** * Initialise the SceneAR instance. This returns a Promise that resolves * successfully if initialisation is successful, otherwise it will fail. * * filure can occur for a number of reasons but it generally means that AR * cannot be performed. */ public async init(): Promise { if (!Util.canAugment()) { throw new Error(""ConfiguratorAR.init() - cannot proceed as AR not available in context""); } const scene: Scene = this._options.state.scene; this._SetupAnalytics(); const sceneOpt: any = scene.attributes.custom_json || {}; // we need to define our AR module here // we are in Safari/Quicklook mode here if (Util.isSafari() || Util.isChromeOnIOS()) { // we need to launch a VTO experience here // VTO requires Reality Support if (sceneOpt.anchor === ""face"") { if (Util.canRealityViewer()) { const modelUrl: string = await this._Compose(""vto""); this._ar = new QuicklookViewer(); this._ar.modelUrl = modelUrl; this._ar.banner = this.options.banner; return this; } else { throw new Error(""ConfiguratorAR.init() - cannot proceed as VTO AR requires Reality Viewer support""); } } // otherwise, load the USDZ stuff second if available if (Util.canQuicklook()) { const modelUrl: string = await this._Compose(""usdz""); this._ar = new QuicklookViewer(); this._ar.modelUrl = modelUrl; this._ar.banner = this.options.banner; return this; } throw new Error(""ConfiguratorAR.init() - cannot proceed as IOS device does not support AR Mode""); } // check android if (Util.canSceneViewer()) { const modelUrl: string = await this._Compose(""glb""); const arviewer = new SceneViewer(); arviewer.modelUrl = modelUrl; arviewer.isVertical = this.options.anchor === ""vertical"" ? true : false; arviewer.banner = this.options.banner; if (sceneOpt.anchor === ""vertical"") { arviewer.isVertical = true; } this._ar = arviewer; return this; } // otherwise, we didn't have AR available - it should never really reach this stage as this should be caught // earlier in the process throw new Error(""ConfiguratorAR.init() - could not initialise AR correctly, check values""); } public start(): void { if (!this._ar) { throw new Error(""SceneAR.start() - cannot proceed as AR instance is null""); } const analytics: Analytics | null = this._analytics; if (analytics) { analytics.data.push(""device"", this._ar.device); analytics.data.push(""eventCategory"", this._ar.nodeType); analytics.data.push(""eventAction"", ""Start Scene Augment""); analytics.write(); analytics.startRecordEngagement(); } // this was initialised via the init() function this._ar.start(); } public canQuicklook(): boolean { return this._ar && this._ar.nodeType === ""Quick Look"" ? true : false; } public canRealityViewer(): boolean { return this._ar && this._ar.nodeType === ""Reality Viewer"" ? true : false; } public canSceneViewer(): boolean { return this._ar && this._ar.nodeType === ""Scene Viewer"" ? true : false; } }",results 298,"import fs from 'fs'; import * as _path from 'path'; import process from 'process'; import { Meta } from './app.mjs'; import * as server from './server.mjs'; async function main(meta: Meta): Promise{ /** * server */ const [MASK] = new server.Server('localhost', 8080); /** * module path */ const path = process.platform == 'win32' ? _path.win32 : _path; /** * default headers */ const default_headers: { [key: string]: string } = { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'text/plain', }; const ContentType: { [ext: string]: string } = JSON.parse(fs.readFileSync(path.resolve(path.dirname(toPath(new URL(import.meta.url))), 'content-type.json'), { encoding: 'utf-8' })); /** * root path */ const rootpath = path.resolve(process.cwd(), meta.arguments[0] || './'); // check root if(!fs.existsSync(rootpath)) throw new Error(`root ""${rootpath}"" is not exist`); if(!fs.statSync(rootpath).isDirectory()) throw new Error(`root ""${rootpath}"" is exist, but it is not directory`); async function onreq(request: server.RequestInformation): Promise{ const filepath = path.resolve(rootpath, request.url.pathname.replace(/^\//,'')); let file: 'notfound' | 'directory' | 'api' | 'file' = 'file'; let apifunc: ((request: server.RequestInformation)=>(server.ResponseInformation | Promise)) | null = null; // check is file/directory exist if(!fs.existsSync(filepath) || /\/(_|\.)/.test(request.url.toString())) file = 'notfound'; // check is it directory if(file == 'file' && fs.statSync(filepath).isDirectory()) file = 'directory'; // api check if(file == 'notfound' && !/\/(_|\.)/.test(request.url.toString()) && /^[^\.]+$/.test(path.basename(filepath)) && fs.existsSync(filepath + '.api.mjs') && !fs.statSync(filepath + '.api.mjs').isDirectory()){ apifunc = (await import(filepath + '.api.mjs')).main as ((request: server.RequestInformation)=>(server.ResponseInformation | Promise)); file = 'api'; } // if file notfound if(file == 'notfound'){ console.log('[notfound]', request.url.toString()); return { body: JSON.stringify({ message: 'NOT_FOUND' }), status: 404, headers: Object.assign(default_headers, { 'Content-Type': 'text/json' }) }; } // if file exist if(file == 'file'){ const data: any = fs.readFileSync(filepath); const contenttype = ContentType[path.extname(filepath)] ?? 'text/plain'; console.log(`[ file ]`, request.url.toString(), '=>', filepath); return { body: data, headers: Object.assign(default_headers, { 'Content-Type': contenttype }), status: 200 }; } // if api request if(file == 'api' && apifunc !== null){ console.log(`[ api ]`, request.url.toString(), '=>', `call api ""${filepath}.api.mjs""`); return apifunc(request); } // if directory if(file == 'directory'){ const data: string = fs.readFileSync(path.resolve(path.dirname(toPath(new URL(import.meta.url))), './index.min.html'), { encoding: 'utf-8' }); const children: { name: string, type: 'api' | 'file' | 'dir' }[] = []; fs.readdirSync(filepath).forEach((child: string)=>{ if(/^(_|\.)/.test(child)) return; if(fs.statSync(path.resolve(filepath, child)).isDirectory()){ children.push({ name: child, type: 'dir' }); return; } if(/^[^\.]+\.api\.mjs$/.test(child)){ if(fs.existsSync(path.resolve(filepath, child.replace(/\.api\.mjs$/, '')))) return; children.push({ name: child, type: 'api' }); return; } children.push({ name: child, type: 'file' }); }); console.log(`[ dir ]`, request.url.toString(), '=>', filepath); return { body: data.replace('?dirinfo?', JSON.stringify(children)), status: 200, headers: Object.assign(default_headers, { 'Content-Type': 'text/html' }) }; } console.log(`[ error ]`, request.url.toString()); return { body: JSON.stringify({ message: 'INTERNAL_SERVER_ERROR' }), status: 500, headers: Object.assign(default_headers, { 'Content-Type': 'text/json' }) }; }; // server [MASK] .onRequest = onreq; [MASK] .listen(); } function toPath(url: URL): string{ if(process.platform == 'win32') return url.pathname.replace(/^\//,''); return url.pathname; } export default main; ",webServer 299,"import * as NatureRemo from 'nature-remo'; import { API, HAP, Logging, AccessoryConfig, Service, Characteristic } from 'homebridge'; import { brightnessDown, brightnessUp, LocalSignal, toggleLight } from './signals'; let hap: HAP; /** * This method registers the platform with Homebridge */ export = (api: API) => { hap = api.hap; api.registerAccessory('MLRU1Light', MLRU1Light); }; class MLRU1Light { private readonly log: Logging; private readonly config: AccessoryConfig; private readonly api: API; private readonly Service: typeof Service; private readonly Characteristic: typeof hap.Characteristic; private readonly natureClient?: NatureRemo.Cloud; private deviceData?: NatureRemo.Appliance; private readonly informationService: Service; private readonly service: Service; private readonly OnCharacteristic: Characteristic; private readonly BrightnessCharacteristic: Characteristic; private currentStatus = true; private readonly maxBrightness: number; private currentBrightness: number = 100; private readonly remoIpAddr: string | undefined; /** * REQUIRED - This is the entry point to your plugin */ constructor(log, config, api) { this.log = log; this.config = config; this.api = api; this.maxBrightness = config.maxBrightness || 5; this.Service = this.api.hap.Service; this.Characteristic = this.api.hap.Characteristic; this.service = new hap.Service.Lightbulb(config.name); if (config.remoIpAddr) { this.log.info('Using Nature Remo\'s local API'); this.remoIpAddr = config.remoIpAddr; } else if (config.accessToken) { this.log.info('Using Nature Remo\'s cloud API'); this.natureClient = new NatureRemo.Cloud(config.accessToken); this.natureClient .getAppliances() .then((devices) => devices.find((i) => i.id === this.config.lightId)) .then((device) => { if (!device) { throw new Error('not found device'); } this.deviceData = device; }); } else { this.log.warn('No API specified'); } // create handlers for required characteristics this.OnCharacteristic = this.service .getCharacteristic(this.Characteristic.On) .onGet(this.handleOnGet.bind(this)) // @ts-expect-error: ? .onSet(this.handleOnSet.bind(this)); this.BrightnessCharacteristic = this.service .getCharacteristic(this.Characteristic.Brightness) .onGet(this.handleBrightnessGet.bind(this)) // @ts-expect-error: ? .onSet(this.handleBrightnessSet.bind(this)); this.informationService = new this.Service.AccessoryInformation() .setCharacteristic(this.Characteristic.Manufacturer, 'irisohyama.co.jp') .setCharacteristic(this.Characteristic.Model, 'MLRU1') .setCharacteristic(this.Characteristic.SerialNumber, 'ho-me-br-id-ge'); } /** * REQUIRED - This must return an array of the services you want to expose. * This method must be named ""getServices"". */ getServices() { return [this.informationService, this.service]; } handleOnGet() { this.log.debug('handleOnGet'); return this.currentStatus; } async handleOnSet(value: boolean) { if (value === this.currentStatus) { return; } this.log.debug('handleOnSet:', value); this.currentStatus = value; try { if (!value) { await this._toggleLight(); } await this._toggleLight(); } catch (e) { if (this.currentStatus === value) { this.currentStatus = !value; } throw e; } } handleBrightnessGet() { this.log.debug('handleBrightnessGet'); return this.currentBrightness; } async handleBrightnessSet(value: number) { if (!this.currentStatus) { this.log.warn('handleBrightnessSet: light is off'); return; } const prevPercent = this.currentBrightness; const [MASK] = value; const prevCount = this._percentToBrightness(prevPercent); const newCount = this._percentToBrightness( [MASK] ); const diff = Math.abs(newCount - prevCount); const isBright = newCount > prevCount; this.log.debug('handleBrightnessSet', { value, prevCount, newCount, diff, isBright, }); if (diff < 0) { return; } this.currentBrightness = [MASK] ; try { for (let i = 0; i < diff; i++) { if (isBright) { await this._brightnessUp(); } else { await this._brightnessDown(); } } } catch (e) { if (this.currentBrightness === [MASK] ) { this.currentBrightness = prevPercent; } throw e; } } private _percentToBrightness(percent: number) { return Math.max(1, Math.min(this.maxBrightness, Math.ceil((this.maxBrightness / 100) * (percent + 1)))); } private _getSignalId(image: string) { if (!this.natureClient || !this.deviceData) { this.log.error('natureClient is not initialized'); return; } const signal = this.deviceData.signals.find((i) => i.image === image); if (!signal) { this.log.error('signal not found', image); return; } return signal.id; } private async _toggleLight() { this.log.debug('toggleLight'); if (this.natureClient) { const signalId = this._getSignalId('ico_on'); if (signalId) { await this.natureClient.sendSignal(signalId); } } else if (this.remoIpAddr) { await this._sendSignalToRemoLocal(toggleLight); } else { this.log.info('toggleLight'); } } private async _brightnessUp() { this.log.debug('brightnessUp'); if (this.natureClient) { const signalId = this._getSignalId('ico_arrow_top'); if (signalId) { await this.natureClient.sendSignal(signalId); } } else if (this.remoIpAddr) { await this._sendSignalToRemoLocal(brightnessUp); } else { this.log.info('brightnessUp'); } } private async _brightnessDown() { this.log.debug('brightnessDown'); if (this.natureClient) { const signalId = this._getSignalId('ico_arrow_bottom'); if (signalId) { await this.natureClient.sendSignal(signalId); } } else if (this.remoIpAddr) { await this._sendSignalToRemoLocal(brightnessDown); } else { this.log.info('brightnessDown'); } } private async _sendSignalToRemoLocal(signal: LocalSignal) { try { if (!this.remoIpAddr) { this.log.error('remoIpAddr is not initialized'); return; } const response = await fetch(`http://${this.remoIpAddr}/messages`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'homebridge-mlru1-light', }, body: JSON.stringify(signal), }); this.log.debug('sendSignalToRemoLocal', response.url, response.statusText, response.status); if (!response.ok) { this.log.error('failed to send signal', response.url, response.statusText, response.status); return; } await new Promise((resolve) => setTimeout(resolve, 500)); } catch (e) { this.log.error((e as Error).message, e); } } } ",newPercent 300,"import { createRouter, createWebHistory } from ""vue-router"" import LoginView from ""@/views/LoginView.vue"" import DirectoryView from ""@/views/DirectoryView.vue"" import DetailsView from ""@/views/DetailsView.vue"" import ManagementView from ""@/views/ManagementView.vue"" const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: ""/login"", name: ""login"", component: LoginView }, { path: ""/directory"", name: ""directory"", component: DirectoryView }, { path: ""/details/:id"", name: ""details"", component: DetailsView }, { path: ""/management"", name: ""management"", component: ManagementView }, ], }) router.beforeEach((to, from, next) => { console.log(from) console.log(to) const [MASK] = to.path != ""/login"" const accessToken = localStorage.getItem(""accessToken"") if ( [MASK] && (accessToken == null || accessToken == undefined)) { return next(""/login"") } else if (to.path == ""/"") { return next(""/directory"") } next() }) export default router ",authRequired 301,"class Main extends egret.DisplayObjectContainer { public constructor() { super(); this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this); } private onAddToStage(event: egret.Event) { // egret.lifecycle.addLifecycleListener((context) => { // // custom lifecycle plugin // context.onUpdate = () => { // } // }) // egret.lifecycle.onPause = () => { // egret.ticker.pause(); // } // egret.lifecycle.onResume = () => { // egret.ticker.resume(); // } this.runGame().catch(e => { console.log(e); }) } private async runGame() { window[""gameBoard""] = this; window[""canvasReady""](); } // private async loadResource() { // try { // const loadingView = new LoadingUI(); // this.stage.addChild(loadingView); // await RES.loadConfig(""resource/default.res.json"", ""resource/""); // await RES.loadGroup(""preload"", 0, loadingView); // this.stage.removeChild(loadingView); // } // catch (e) { // console.error(e); // } // } // private textfield: egret.TextField; /** * 创建游戏场景 * Create a game scene */ private childrenList = []; private playerList = []; private canvasParam; public createGameScene(canvasParam) { // 棋盘生成 this.canvasParam = canvasParam; var p = canvasParam.blockWdith; for (var i = 0; i < canvasParam.blockNum+1; i++) { for (var j = 0; j < canvasParam.blockNum+1; j++) { if (i < canvasParam.blockNum) { var hline = new Line(i, j, p, canvasParam.lineWidth, ""hLine"", canvasParam); this.addChild(hline); hline.x = 10 + p * i + p / 2; hline.y = 10 + p * j; this.childrenList.push(hline); if (j == 0 || j == canvasParam.blockNum) { hline.touched = true; } } if (j < canvasParam.blockNum) { var vline = new Line(i, j, canvasParam.lineWidth, p, ""vLine"", canvasParam); this.addChild(vline); vline.x = 10 + p * i; vline.y = 10 + p * j + p / 2; this.childrenList.push(vline); if (i == 0 || i == canvasParam.blockNum) { vline.touched = true; } } } } //玩家生成 for (var i = 0; i < canvasParam.playerNum; i++) { var player = new Player(canvasParam.blockWdith / 2 * 0.8, i, canvasParam); this.addChild(player); this.playerList[i] = player; if (i == 0) // player.setPosition(canvasParam.blockWdith, 4, 0); this.setPLayerPosition(i, Math.floor(canvasParam.blockNum/2), 0) if (i == 1) this.setPLayerPosition(i, Math.floor(canvasParam.blockNum/2), canvasParam.blockNum-1) // player.setPosition(canvasParam.blockWdith, 4, 8); if (i == 2) this.setPLayerPosition(i, 0, Math.floor(canvasParam.blockNum/2)) // player.setPosition(canvasParam.blockWdith, 0, 4); if (i == 3) this.setPLayerPosition(i, canvasParam.blockNum-1, Math.floor(canvasParam.blockNum/2)) // player.setPosition(canvasParam.blockWdith, 8, 4); } return this.playerList; } private blockPosition = function (gx, gy) { return [ this.canvasParam.blockWdith * (gx + 0.5) + 10, this.canvasParam.blockWdith * (gy + 0.5) + 10, ] }; private touchList = []; public startTouch(playerIndex,wall) { // 重置触摸参数 this.touchList = []; for (var i in this.childrenList) { this.childrenList[i].touchEnabled = (wall)?true:false; } for (var i in this.playerList) { this.playerList[i].touchEnabled = (i == playerIndex); } // 开始触摸 // 触摸的线上下或左右可以触摸,其他不能触摸 var touchType; this.touchEnabled = false; var touchStart = function (e) { touchType = e.target.name; console.log(touchType); if (touchType == ""Line"") { if (e.target.touched) {//已经放置墙的不能再次被触摸 return } this.touchList.push(e.target); if (e.target.onTouch && !e.target.touched) { e.target.onTouch(); for (var i in this.childrenList) { this.childrenList[i].touchEnabled = false; if (this.childrenList[i].gtype == e.target.gtype) { if (e.target.gtype == 'hLine') { if (this.childrenList[i].gy == e.target.gy && (this.childrenList[i].gx == e.target.gx + 1 || this.childrenList[i].gx == e.target.gx - 1)) { this.childrenList[i].touchEnabled = true } } if (e.target.gtype == 'vLine') { if (this.childrenList[i].gx == e.target.gx && (this.childrenList[i].gy == e.target.gy + 1 || this.childrenList[i].gy == e.target.gy - 1)) { this.childrenList[i].touchEnabled = true } } } e.target.touchEnabled = true; } } return; } if (touchType == ""player"") { this.touchEnabled = true; for (var i in this.childrenList) { this.childrenList[i].touchEnabled = false; } } } // 触摸移动 var touchMove = function (e) { if (touchType == ""Line"") { if (this.touchList.length == 2 && e.target != this.touchList[1]) { this.touchList[1].endTouch(); this.touchList.pop(); return; } if (this.touchList.length != 1 || e.target == this.touchList[0]) return //第一段触摸失败直接返回 if (!e.target.touched) { this.touchList.push(e.target); if (e.target.onTouch) { e.target.onTouch(); } } } if (touchType == ""player"") { var player = this.playerList[playerIndex]; player.x = e.stageX; player.y = e.stageY; var canvasParam = this.canvasParam; var setP = function (blockPosition) { // console.log(""this.canvasParam"",canvasParam); if (Math.abs(player.x - blockPosition[0]) < canvasParam.blockWdith * 0.3 && Math.abs(player.y - blockPosition[1]) < canvasParam.blockWdith * 0.3 ) { player.x = blockPosition[0]; player.y = blockPosition[1]; } } for(var i = 0;i parser.parse(text)); // let textfield = this.textfield; // let count = -1; // let change = () => { // count++; // if (count >= textflowArr.length) { // count = 0; // } // let textFlow = textflowArr[count]; // // 切换描述内容 // // Switch to described content // textfield.textFlow = textFlow; // let tw = egret.Tween.get(textfield); // tw.to({ ""alpha"": 1 }, 200); // tw.wait(2000); // tw.to({ ""alpha"": 0 }, 200); // tw.call(change, this); // }; // change(); // } } class Dot extends egret.Shape { public constructor(gx, gy, size) { super(); this.graphics.beginFill(0x121212); this.graphics.drawCircle(0, 0, size); this.graphics.endFill(); this.gx = gx; this.gy = gy; this.touchEnabled = true; this.name = ""dot""; } public gx; public gy; public onTouch() { this.scaleX = 1.2; this.scaleY = 1.2; } public endTouch() { this.scaleX = 1; this.scaleY = 1; } } class Line extends egret.Shape { private lineColor; private lineTouchColor; private playerLineColor; public constructor(gx, gy, width, height, type, param) { super(); this.lineColor = param.lineColor; this.lineTouchColor = param.lineTouchColor; this.playerLineColor = param.playerLineColor; this.graphics.beginFill(this.lineColor); this.graphics.drawRect(-width / 2, -height / 2, width, height); this.graphics.endFill(); this.gx = gx; this.gy = gy; this.gtype = type; this.touchEnabled = true; this.width = width; this.height = height; this.name = ""Line""; } public width; public height; public gx; public gy; public gtype; public touched = false; public onTouch() { this.graphics.beginFill(this.lineTouchColor); this.graphics.drawRect(-this.width / 2, -this.height / 2, this.width, this.height); this.graphics.endFill(); } public endTouch() { this.graphics.beginFill(this.lineColor); this.graphics.drawRect(-this.width / 2, -this.height / 2, this.width, this.height); this.graphics.endFill(); } public setWall(player) { this.touched = true; this.graphics.beginFill(this.playerLineColor[player]); this.graphics.drawRect(-this.width / 2, -this.height / 2, this.width, this.height); this.graphics.endFill(); } } class Player extends egret.Shape { // private lineColor; // private lineTouchColor; // private playerLineColor; public player; public constructor(r, player, param) { super(); this.graphics.beginFill(param.playerLineColor[player]); this.graphics.drawCircle(0, 0, r); this.graphics.endFill(); this.player = player; this.touchEnabled = true; this.name = ""player""; // this.lineColor = param.lineColor; // this.lineTouchColor = param.lineTouchColor; // this.playerLineColor = param.playerLineColor; // this.graphics.beginFill(this.lineColor); // this.graphics.drawRect(-width / 2, -height / 2, width, height); // this.graphics.endFill(); // this.gx = gx; // this.gy = gy; // this.gtype = type; this.touchEnabled = true; // this.width = width; // this.height = height; // this.name = ""Line""; } // public width; // public height; public gx; public gy; // public setPosition(width, gx, gy) { // this.x = width * (gx + 0.5) + 10; // this.y = width * (gy + 0.5) + 10; // this.gx = gx; // this.gy = gy; // } // public gtype; // public touched = false; // public onTouch() { // this.graphics.beginFill(this.lineTouchColor); // this.graphics.drawRect(-this.width / 2, -this.height / 2, this.width, this.height); // this.graphics.endFill(); // } // public endTouch() { // this.graphics.beginFill(this.lineColor); // this.graphics.drawRect(-this.width / 2, -this.height / 2, this.width, this.height); // this.graphics.endFill(); // } // public setWall(player) { // this.touched = true; // this.graphics.beginFill(this.playerLineColor[player]); // this.graphics.drawRect(-this.width / 2, -this.height / 2, this.width, this.height); // this.graphics.endFill(); // } } ",uploadList 302,"import * as vscode from 'vscode'; import * as os from 'os'; import * as fs from 'fs'; import * as path from 'path'; import * as child_process from 'child_process'; interface NetstatRecord { proto: string, localAddress: string, localPort: number, foreignAddress: string, foreignPort: number, state: string, pid: number } export interface PORT_STATES { LISTENING: boolean, ESTABLISHED: boolean, TIME_WAIT: boolean, CLOSE_WAIT: boolean, } class NetstatViewProvider implements vscode.WebviewViewProvider { public static readonly viewType = 'vscode-netstat-ng.netstat'; private _view?: vscode.WebviewView; constructor(private readonly _extensionUri: vscode.Uri) { } resolveWebviewView(webviewView: vscode.WebviewView, context: vscode.WebviewViewResolveContext, token: vscode.CancellationToken): void | Thenable { this._view = webviewView; webviewView.webview.options = { // Allow scripts in the webview enableScripts: true, localResourceRoots: [ this._extensionUri ] }; webviewView.webview.html = this._getHtmlForWebview(webviewView.webview); webviewView.webview.onDidReceiveMessage(data => { switch (data.command) { case 'netstat': this.netstat(data.portStates, data.ports); break; case 'killProcess': this.killOwnerProcess(data.pid); break; } }); } netstat(portStates: PORT_STATES, ports: string[], ) { const netstatRecords: Array = []; let rawNetstatBuffer = ''; const dirProcess = child_process.spawn( 'cmd', [ '/C' ,'netstat' ,'-anop' ,'tcp' ] ); dirProcess.stdout.on('data', (data) => { rawNetstatBuffer += data; }); dirProcess.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); dirProcess.on('exit', (code) => { const netstatRecordLines = rawNetstatBuffer.split('\n') .filter(line => line.trim().startsWith('TCP')) .map(line => line.trim()) .forEach(line => { const localParts = line.substring(7, 29).trim().split(/[:]/); const localAddress = localParts[0]; const localPort = parseInt(localParts[1], 10); if (ports.length > 0 && !ports.includes('' + localPort)) { return; } const foreignParts = line.substring(30, 52).trim().split(/[:]/); const foreignAddress = foreignParts[0]; const foreignPort = parseInt(foreignParts[1]); const state = line.substring(53, 68).trim(); const pid = parseInt(line.substring(69).trim()); const aNetstatObject = { proto: 'TCP', localAddress, localPort, foreignAddress, foreignPort, state, pid }; if (portStates.LISTENING && state === 'LISTENING') { netstatRecords.push(aNetstatObject); } if (portStates.ESTABLISHED && state === 'ESTABLISHED') { netstatRecords.push(aNetstatObject); } if (portStates.TIME_WAIT && state === 'TIME_WAIT') { netstatRecords.push(aNetstatObject); } else if (portStates.CLOSE_WAIT && state === 'CLOSE_WAIT') { netstatRecords.push(aNetstatObject); } }); this._view?.webview.postMessage({ command: 'netstat', netstatRecords: netstatRecords }); }); } killOwnerProcess(pid: number) { if (pid) { vscode.window.showInformationMessage(`Kill process id: ${pid}`, 'No', 'Yes').then(response => { if (response === 'Yes') { const dirProcess = child_process.spawn( 'cmd', [ '/C' ,'taskkill' ,'/F' ,'/PID' ,`${pid}` ] ); dirProcess.on('exit', (code) => { this.refreshView(); }); } }); } } setColorTheme(colorTheme: vscode.ColorTheme) { this._view?.webview.postMessage({ command: 'colorTheme', colorTheme }); } refreshView() { this._view?.webview.postMessage({ command: 'refreshView' }); } /** * Returns html of the start page (index.html) */ private _getHtmlForWebview(webview: vscode.Webview) { // URI to dist folder const [MASK] = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'dist'));; // path as uri const baseUri = webview.asWebviewUri( [MASK] ); // get path to index.html file from dist folder const indexPath = path.join( [MASK] .fsPath, 'index.html'); // read index file from file system let indexHtml = fs.readFileSync(indexPath, { encoding: 'utf8' }); // update the base URI tag indexHtml = indexHtml.replace('', ``); return indexHtml; } } let extensionPath: string; let outputChannel: vscode.OutputChannel; /** * Activates extension * @param context vscode extension context */ export function activate(context: vscode.ExtensionContext) { extensionPath = context.extensionPath; outputChannel = vscode.window.createOutputChannel(context.extension.id.replace('sandipchitale.', '')); const provider = new NetstatViewProvider(context.extensionUri); context.subscriptions.push(vscode.window.registerWebviewViewProvider(NetstatViewProvider.viewType, provider)); vscode.window.onDidChangeActiveColorTheme((colorTheme: vscode.ColorTheme) => { provider.setColorTheme(colorTheme); }); } ",appDistUri 303,"import { MathUtils, RadiusMeter } from ""./math/MathUtils""; /** * Used for parsing XML jp2 information from Helioviewer */ class HelioviewerJp2Metadata { private xml: XMLDocument; /** Optional date override to use instead of attempting to parse from metadata */ private _date: Date | undefined; /** * @param header JP2Image header * @param date If set, use this date instead of reading from metadata */ constructor(header: string, date?: Date) { const parser = new DOMParser(); this.xml = parser.parseFromString(header, ""text/xml""); this._date = date; } getSolarRadiusFactor(): number { return 1; } /** * Retrieves the radius of the sun in pixels according to the jp2 metadata. */ radiusInPixels() { return this.getNumberOrDie(""SOLAR_R""); } date(): Date { // Use date override if it is set. // This was simpler than trying to handle different FITS // keys to correctly get the date since helioviewer already does this. // It may be implemented in the future. if (typeof this._date !== undefined) { return this._date as Date; } const [MASK] = this.get(""DATE_OBS"", """"); if ( [MASK] === """") { throw ""Missing DATE_OBS""; } return new Date(`${ [MASK] }Z`); } /** * returns the radius of the sun in arcseconds calculated according to the * observatory's distance from the sun. */ radiusInArcsec() { try { // Attempt to compute the radius using the distance to the sun. // This may fail if some variation of DSUN is not available in the // JP2 Header const out = this.toDegrees(Math.atan2(this.getSolarRadiusFactor(), this.distanceToSun())) * 3600; return out; } catch (e) { try { // If DSUN is not available, distanceToSun will fail, in that case // try to calculate it using the radius in pixels. const out = this.imageScaleX * this.radiusInPixels() return out; } catch (e) { // If there no SOLAR_R/RSUN value then radiusInPixels will fail. // For this case just assume rsun at 1 AU const earthDistance = MathUtils.getEarthDistance(this.date().getTime()); const out = this.toDegrees(Math.atan2(this.getSolarRadiusFactor(), earthDistance)) * 3600; return out; } } } /** * Returns the distance to the sun in solar radii units. */ distanceToSun(): number { let dsun = this.getNumber(""DSUN_OBS"", 0); if (dsun === 0) dsun = this.getNumberOrDie(""DSUN""); return dsun / RadiusMeter; } toDegrees(angle: number) { return angle * 180 / Math.PI; } toRadians(angle: number) { return angle * Math.PI / 180; } width(): number { const w = this.getNumber(""NAXIS1"", 0); if (w === 0) { throw ""Invalid Image, missing NAXIS1""; } return w; } height(): number { const h = this.getNumber(""NAXIS2"", 0); if (h === 0) { throw ""Invalid Image, missing NAXIS2""; } return h; } /** * Compute the scale according to the distance to the sun. * Helioviewer's given R_SUN can't be trusted to do this accurately. * It computes a value that may work for Helioviewer.org, but not for * the accuracy that we need in this application. */ scale(): number { // Assume cdelt1 and cdelt2 are the same. const arcsecPerPixel = this.imageScaleX; const rsun_px = this.radiusInArcsec() / arcsecPerPixel; const shortEdge = Math.min(this.width(), this.height()); return shortEdge / (4 * rsun_px); } /** * Convert arcseconds to solar radius units * @param arcsec Unit in arcseconds * @returns The distance in solar radii */ arcsec2Solrad(arcsec: number): number { return arcsec / this.radiusInArcsec(); } /** * Convert pixel coordinates to arcseconds * @param pixel The pixel coordinate to convert * @param refPix The reference pixel (CRPIX) * @param refVal The reference value (CRVAL) * @param delta The pixel scale (CDELT) * @returns The coordinate in arcseconds */ pixel2arcsec(pixel: number, refPix: number, refVal: number, delta: number) { return (pixel - refPix) * delta + refVal; } /** * Convert pixel coordinates to solar radius units * @param pixel The pixel coordinate to convert * @param refPix The reference pixel (CRPIX) * @param refVal The reference value (CRVAL) * @param delta The pixel scale (CDELT) * @returns The coordinate in solar radii */ pixel2solrad(pixel: number, refPix: number, refVal: number, delta: number): number { const arcsec = this.pixel2arcsec(pixel, refPix, refVal, delta); return this.arcsec2Solrad(arcsec); } /** * Returns the arcseconds / pixel scale of the image. * @param cdeltKey options: [CDELT1, CDELT2] * @param cunitKey options: [CUNIT1, CUNIT2] * @returns {number} */ private getPixelDelta(cdeltKey: string, cunitKey: string): number { const unit = this.get(cunitKey, ""arcsec"").trim(); const delta = this.getNumberOrDie(cdeltKey); if (unit === ""deg"") { return delta * 3600; } return delta; } private get imageScaleX(): number { return this.getPixelDelta(""CDELT1"", ""CUNIT1""); } private get imageScaleY(): number { return this.getPixelDelta(""CDELT2"", ""CUNIT2""); } /** * Computes the amount to move the entire model to account for WCS information. * This is different than only moving the image to align with a model. */ sceneOffsetX(): number { const ref = this.getNumberOrDie(""CRPIX1"") - 0.5; // JHelioviewer defaults to 0 if CRVAL is not present. Do the same here. const crval = this.getNumber(""CRVAL1"", 0); const cdelt = this.imageScaleX; // Get the current position of the reference pixel in scene units // This is done by assuming the center of the image (this.width()) is // by default at the center of the scene (reference value 0). const currentPos = this.pixel2solrad(ref, this.width() / 2, 0, cdelt); // Get the target position of the reference pixel in scene units // This is where it ought to be, computed using normal info from header. const targetPos = this.pixel2solrad(ref, ref, crval, cdelt); return targetPos - currentPos; } sceneOffsetY(): number { const ref = this.getNumberOrDie(""CRPIX2"") - 0.5; // JHelioviewer defaults to 0 if CRVAL is not present. Do the same here. const crval = this.getNumber(""CRVAL2"", 0); const cdelt = this.imageScaleY; // Get the current position of the reference pixel in scene units // This is done by assuming the center of the image (this.width()) is // by default at the center of the scene (reference value 0). const currentPos = this.pixel2solrad(ref, this.width() / 2, 0, cdelt); // Get the target position of the reference pixel in scene units // This is where it ought to be, computed using normal info from header. const targetPos = this.pixel2solrad(ref, ref, crval, cdelt); return targetPos - currentPos; } /** * Compute the openGL offset along the Y axis */ glOffsetY() { const ref = this.getNumberOrDie(""CRPIX2"") - 0.5; // JHelioviewer defaults to 0 if CRVAL is not present. Do the same here. const crval = this.getNumber(""CRVAL2"", 0); const cdelt = this.imageScaleY; const px = crval / cdelt / this.height(); return (ref) / this.height() - px; } /** * Compute the openGL offset along the X axis */ glOffsetX() { const ref = this.getNumberOrDie(""CRPIX1"") - 0.5; // JHelioviewer defaults to 0 if CRVAL is not present. Do the same here. const crval = this.getNumber(""CRVAL1"", 0); const cdelt = this.imageScaleX; const px = crval / cdelt / this.width(); return ref / this.width() - px; } centerOfRotation() { const xcen = this.getNumberOrDie(""CRPIX1"") - 0.5; const ycen = this.getNumberOrDie(""CRPIX2"") - 0.5; return [xcen / this.width(), ycen / this.height()]; } /** * Returns the value of the given tag or else the default Value if the * tag can't be found * @param tag * @param defaultValue */ private get(tag: string, defaultValue: any): string { const tags = this.xml.getElementsByTagName(tag); if (tags.length === 0) { console.warn(`Couldn't find ${tag}, using default value ${defaultValue}`); return defaultValue; } console.assert(tags[0].textContent != null); return tags[0].textContent as string; } /** * Returns the numeric value of the given tag or else the default Value if the * tag can't be found * @param tag * @param defaultValue */ private getNumber(tag: string, defaultValue: number): number { const val = parseFloat(this.get(tag, defaultValue)); return isNaN(val) ? defaultValue : val; } /** * Returns the numeric value of the given tag or else the default Value if the * tag can't be found * @param tag * @param defaultValue */ private getNumberOrDie(tag: string): number { const val = parseFloat(this.get(tag, ""Invalid"")); if (isNaN(val)) { throw ""Invalid header, missing tag "" + tag; } return val; } } export { HelioviewerJp2Metadata } ",dateStr 304,"import { ApiAdapter } from '../../infrastructure/adapters/ApiAdapter'; import { User } from '../../domain/entities/User'; // Interfaz para el perfil de usuario interface UserProfile { id: string; auth_id: string; first_name: string; last_name: string; email: string; avatar_url?: string; bio?: string; } // Interfaz para actualizar el perfil interface ProfileUpdate { first_name: string; last_name: string; bio?: string; avatar_url?: string; } export class UserService { private api: ApiAdapter; constructor() { this.api = new ApiAdapter(); } /** * Obtiene el perfil del usuario actual */ async getMyProfile(): Promise { return this.api.get('/users/me'); } /** * Actualiza el perfil del usuario */ async updateProfile( [MASK] : ProfileUpdate): Promise { return this.api.put('/users/me', [MASK] ); } /** * Convierte un UserProfile a un User de dominio */ mapProfileToUser(profile: UserProfile): User { return { id: profile.auth_id, email: profile.email, name: `${profile.first_name} ${profile.last_name}`.trim() }; } } ",profileData 305,"import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core'; import { Project } from '../stats-client/models/Project'; import { Series } from '../helpers/stats-transformer'; import * as d3 from 'd3-shape'; @Component({ selector: 'all-stats', templateUrl: './all-stats.component.html', styleUrls: ['./all-stats.component.scss'] }) export class AllStatsComponent implements OnChanges { @Input() project: Project; @Input() noProjects: number; @Input() unit = 'days'; stats: Series[]; curve = d3.curveCatmullRom; constructor() { } ngOnChanges( [MASK] : SimpleChanges) { if ( [MASK] .project && [MASK] .project.currentValue) { if ( [MASK] .project.currentValue.stats && [MASK] .project.currentValue.stats.seriesCommits) { this.stats = [MASK] .project.currentValue.stats.seriesCommits.filter(x => x.name === this.unit); } } } } ",changes 306,"import Fastify, { FastifyInstance } from 'fastify'; import { Server as SocketIOServer } from 'socket.io'; import fastifySocketIO from 'fastify-socket.io'; import Client from 'socket.io-client'; import { UserContext } from './types/user-context'; import connectionManager from './utils/connection-manager'; import MessageEmitter from './utils/message-emitter'; interface FastifyInstanceWithIO extends FastifyInstance { io: SocketIOServer; } const fastify = Fastify() as unknown as FastifyInstanceWithIO; fastify.register(fastifySocketIO, { path: '/ws', cors: { origin: '*' }, }); const backendClient = Client('http://localhost:3002'); fastify.ready().then(() => { fastify.io.use((socket, next) => { const token = socket.handshake.auth.token; if (!token) { console.log('Authorization header missing'); return next(new Error('Authorization header missing')); } if (token !== 'MySecretToken') { console.log('Authentication error'); return next(new Error('Authentication error')); } console.log('Authorization successful'); return next(); }); const messageEmitter = new MessageEmitter(fastify.io); // Relay messages from backend-server to website clients backendClient.on('message', (context: UserContext, data: string) => { console.log(`fastify.io.emit: Message received from backend`); messageEmitter.emit(context, 'message', 'status', { status: data }); }); // Handle subscriptions from website fastify.io.on('connection', (socket) => { console.log('Website connected'); socket.on('subscribe', (channel: string, { userId, sessionNumber }: UserContext) => { console.log(`Website subscribed to ${channel} for user ${userId} and session ${sessionNumber}`); connectionManager.addConnection(userId, sessionNumber, socket.id); backendClient.on(channel, (context: UserContext, data: any) => { console.log(`Message on ${channel} received from backend`); messageEmitter.emit(context, 'message', channel, data); }); backendClient.on('error', (error: Error | any) => { console.log(`Error reported from backend`, error); socket.emit('error', error.message); }); backendClient.emit('subscribe', channel, { userId, sessionNumber }); }); }); backendClient.on('stats', (stats: string) => { const [MASK] = connectionManager.getStats(); fastify.io.emit('stats', `API:\n${ [MASK] }\nBackend:\n${stats}\n`); }); console.log('API server is running on port 3001'); }); fastify.listen({ port: 3001 }, (err) => { if (err) { console.error('Error starting server:', err); process.exit(1); } });",apiStats 307,"import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { Notification } from '../../commons/notification'; import { VerNotificationPage } from './verNotification'; @Component({ selector: 'page-notification', templateUrl: 'notification.html' }) export class NotificationPage { notifications:Array = [ {action: ""reply"", img:""https://pbs.twimg.com/profile_images/631520492260839424/kG3suEXq_bigger.jpg"", nick_name:""@xurxodev"", text:""example ionic""}, {action: ""reply"", img:""https://pbs.twimg.com/profile_images/902953212696768523/wMWePMB9_bigger.jpg"", nick_name:""@karatestarsapp"", text:""example ionic""}, {action: ""reply"", img:""https://pbs.twimg.com/profile_images/755352605488971776/-bbgzJPy_bigger.jpg"", nick_name:""@kireidev"", text:""example ionic""} ]; constructor(public navCtrl: NavController) { } verNotification( [MASK] :Notification){ debugger; console.log(""Abriendo notificacion: "" + [MASK] .nick_name); this.navCtrl.push(VerNotificationPage, { id: [MASK] }); } } ",_notification 308,"import { IProduct } from '@/model/IProduct'; import { createAsyncThunk, createEntityAdapter, createSlice } from '@reduxjs/toolkit'; import requests from ""../../../api/requests""; import { RootState } from '../../store/store'; //Async thunk to fetch all products export const fetchProducts = createAsyncThunk( ""catalog/fetchProducts"", async () => { return await requests.Catalog.list(); } ); //Async thunk to fetch a single product by ID export const fetchProductById = createAsyncThunk( ""catalog/fetchProductById"", // fix typo in the type name async ( [MASK] ) => { return await requests.Catalog.details( [MASK] ); } ); // Create entity adapter for normalized state const productsAdapter = createEntityAdapter(); const initialState = productsAdapter.getInitialState({ status: ""idle"", isLoaded: false, }); // Catalog slice export const catalogSlice = createSlice({ name: ""catalog"", initialState, reducers: {}, extraReducers: (builder) => { builder.addCase(fetchProducts.pending, (state) => { state.status = ""pendingFetchProducts""; }); builder.addCase(fetchProducts.fulfilled, (state, action) => { productsAdapter.setAll(state, action.payload); // state is always first param state.isLoaded = true; state.status = ""idle""; }); builder.addCase(fetchProducts.rejected, (state) => { state.status = ""idle""; }); builder.addCase(fetchProductById.pending, (state) => { state.status = ""pendingFetchProductById""; }); builder.addCase(fetchProductById.fulfilled, (state, action) => { productsAdapter.upsertOne(state, action.payload); // fix typo: upsertOne not upserOne state.status = ""idle""; }); builder.addCase(fetchProductById.rejected, (state) => { state.status = ""idle""; }); } }); export const { selectById: selectProductById, selectIds: selectProductIds, selectEntities: selectProductEntities, selectAll: selectAllProducts, selectTotal: selectTotalProducts, } = productsAdapter.getSelectors((state: RootState) => state.catalog); ",productId 309,"import { Component, OnInit, Renderer2, Inject } from '@angular/core'; import { DOCUMENT } from '@angular/common'; import { FormBuilder, FormGroup, FormControl } from '@angular/forms'; declare var ProctorClient3: any; @Component({ selector: 'app-talview-proctoring', templateUrl: './talview-proctoring.component.html', styleUrls: ['./talview-proctoring.component.css'] }) export class TalviewProctoringComponent implements OnInit { proctoringStatus: string; proctoringMsg: string; // talviewToken = ''; sessionTitle = 'Proctored Test Assessment by StackRoute'; // profileId = 'basav-b56-ca7a-4f41-a841-7131f639a086'; isIDRequired = true; // session = '67825a32-8d53-4926-a70b-db42195fdd0b'; clear = false; screen = true; skipHardwareTest = false; previewStyle = 'position: fixed; bottom: 0px;'; proctorDetails: FormGroup; constructor( @Inject(DOCUMENT) private document: Document, private renderer2: Renderer2, private fb: FormBuilder ) { this.proctorDetails = this.fb.group({ talviewToken: new FormControl(''), profileId: new FormControl(''), session: new FormControl(''), }); } ngOnInit() {} loadJavaScriptAndStartProctoring() { console.log('Talview init token', this.proctorDetails.get('talviewToken').value); console.log('Profile ID is:: ', this.proctorDetails.get('profileId').value); console.log('Session id is', this.proctorDetails.get('session').value); const script = this.renderer2.createElement('script'); script.type = `text/javascript`; script.text = ` (function (i, s, o, g, r, a, m) { i['TalviewProctor'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', 'https://cdn.proview.io/v5/init.js', 'tv'); tv('init', '${this.proctorDetails.get('talviewToken').value}', { sessionTitle: '${this.sessionTitle}', profileId: '${this.proctorDetails.get('profileId').value}', isIDRequired: ${this.isIDRequired}, session: '${this.proctorDetails.get('session').value}', clear: ${this.clear}, screen: ${this.screen}, skipHardwareTest: ${this.skipHardwareTest}, previewStyle: '${this.previewStyle}', initCallback: function (err, id, a, v, s) { var a = document.createElement('a'); a.setAttribute('target', '_blank'); a.innerText = 'Open Session'; a.setAttribute('href', 'https://appv5.proview.io/embedded/' + id); //embedded link document.getElementById('content').prepend(a); } });`; this.renderer2.appendChild(this.document.body, script); } onProctoringInitialised(error, [MASK] , isAudioCaptured, isVideoCaptured, isScreenCaptured) { this.proctoringMsg = `Proctoring initialised, check here https://appv5.proview.io/embedded/${ [MASK] }`; } onProctoringStopped() { this.proctoringMsg = `Proctoring is now Stopped`; } onStartProctoring() { this.loadJavaScriptAndStartProctoring(); } onStopProctoring() { ProctorClient3.stop(() => { this.onProctoringStopped(); }); } } ",sessionPlaybackId 310,"import axios, { AxiosError, AxiosResponse } from ""axios""; const AxiosErrorHandler = async ( [MASK] : AxiosError) => { if (axios.isAxiosError( [MASK] )) { const { status, data } = [MASK] .response! as AxiosResponse ?? { status: 500, data: { message: ""Internal Server Error"" } }; switch (status) { // Handle Errors - Define different Responses for different status codes case 400: return Promise.reject(data); case 401: // Remove Any Local Or Session Storage return Promise.reject(data); case 403: return Promise.reject(data); case 404: return Promise.reject(data); case 500: return Promise.reject(data); default: return Promise.reject(data); } } // Handle Network Errors return Promise.reject( [MASK] ); } export default AxiosErrorHandler; ",error 311,"import { clearLoginData, checkLogin, getLoginInfo, } from '@/tool/login' export const proxy = (function () { if (process.env.NODE_ENV === 'development') { return 'http://192.168.44.160:9100/' } else { return process.env.PROXY } })() export const SOURCE = (function () { return 'xjr_help_weapp' if (process.env.NODE_ENV === 'development') { // console.log('开发环境') return 'xjr_help_weapp' } else { // console.log('生产环境') // 当前环境生产测试 return process.env.SOURCE || 'weapp' } })() function dealParams (params: { [index: string]: any }) { const defaultParams: { [index: string]: any } = {} for (const key of Object.keys(params)) { const value = params[key] if (value !== undefined && value !== null) { defaultParams[key] = params[key] } } defaultParams['source'] = SOURCE return defaultParams } // 组合URL function generateUrl ({ proxy = '', url = '' }) { return proxy + url + `` } export const postForm = ({ url = '', params = {} }) => fetchConfig({ url, params, header: { 'content-type': 'application/x-www-form-urlencoded;', 'source': SOURCE, }, }) // post export const post = async ({ url = '', params = {} }) => fetchConfig({ url, params, header: { 'content-type': 'application/json', 'source': SOURCE, }, }) function fetchConfig ({ header = {}, url = '', params = {} }) { return new Promise((resolve, reject) => { let authorization = '' if (checkLogin()) { const { token: { accessToken } } = getLoginInfo() authorization = `${ accessToken }` } uni.request({ url: generateUrl({ proxy, url }), data: dealParams(params), header: Object.assign({ 'Authorization': authorization }, header), method: 'POST', success: response => success(response, resolve, reject), fail: error => fail(error, resolve, reject), }) }) } /** * 文件上传 */ enum E_FileType { image = 'image', video = 'video' } interface I_PostFileParams { url: string, filePath: string, fileType: E_FileType, name: string, params: { [index: string]: any }, callbackTask?: { (name: any): void } } export const postFile = ({ url = '', filePath = '', fileType = E_FileType.image, name = 'file', params = {}, callbackTask, }: I_PostFileParams) => new Promise((resolve, reject) => { let authorization = '' if (checkLogin()) { const { token: { accessToken } } = getLoginInfo() authorization = `${ accessToken }` } const [MASK] = uni.uploadFile({ url: /^(https|http)/i.test(url) ? url : proxy + url, filePath, name, fileType, formData: { ...params }, header: { 'Authorization': authorization, 'source': SOURCE }, success: response => success(response, resolve, reject), fail: error => fail(error, resolve, reject), }) callbackTask && typeof callbackTask === 'function' && callbackTask( [MASK] ) }) function success (response: any, resolve: any, reject: any) { const { statusCode } = response if (statusCode === 200) { const { code, data, msg, styleType } = response.data if (code === '0000' && !styleType) { resolve(data) return } if (code === '9999') { uni.hideLoading() if (styleType === 1) { uni.showModal({ title: '提示', content: msg, confirmText: '知道了', confirmColor: '#337BE1', showCancel: false, success (res) { if (res.confirm) { // console.log('用户点击确定'); } }, }) reject(data) console.error('http请求:', response) return } else { uni.showToast({ title: msg, icon: 'none' }) reject(response.data) console.error('http请求:', response) return } } console.error('http请求:', response) reject(response.data) return } if (statusCode === 401) { uni.hideLoading() uni.showModal({ title: '温馨提示', content: '登录超时,需要重新登录', confirmText: '去登录', confirmColor: '#337BE1', showCancel: false, success (res) { clearLoginData() uni.reLaunch({ url: '/pages/login/login' }) }, }) reject(new Error('登录超时')) console.error('http请求:', response) return } uni.showToast({ title: `${ statusCode }:${ url }`, icon: 'none' }) reject(new Error(`${ statusCode }:${ url }`)) console.error(response) return } function fail (error: any, resolve: any, reject: any) { console.error('http请求:', error) const { statusCode, data } = error if (statusCode === 401) { uni.hideLoading() uni.showModal({ title: '温馨提示', content: '登录超时,需要重新登录', confirmText: '去登录', confirmColor: '#337BE1', showCancel: false, success (res) { clearLoginData() uni.reLaunch({ url: '/pages/login/login' }) }, }) reject(new Error('登录超时')) return } uni.showToast({ title: JSON.stringify(error), icon: 'none', }) reject(error) } ",uploadTask 312,"import path from ""path""; import fs from ""fs""; import { Client, Events, GatewayIntentBits, Guild, REST, Routes } from 'discord.js'; import { BaseComponent } from ""../../base/BaseComponent.js""; import { fileURLToPath } from 'url'; import { BaseCommandHandler } from ""./base/BaseCommandHandler.js""; import { BaseMessageHandler } from ""./base/BaseMessageHandler.js""; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); export default class DiscordComponent extends BaseComponent { private clientId: string; private token: string; client: Client; api: REST; commands: NodeJS.Dict[] = []; commandHandlers: { [key: string]: BaseCommandHandler } = {}; messageHandlers: { [key: string]: BaseMessageHandler } = {}; constructor(...args: any[]) { super('discord', 'Discord Component', ...args); } async initialize(): Promise { this.token = process.env.DISCORD_BOT_TOKEN; this.clientId = process.env.DISCORD_CLIENT_ID; if (!this.token) throw new Error(""DISCORD_BOT_TOKEN is not defined""); if (!this.clientId) throw new Error(""DISCORD_CLIENT_ID is not defined""); this.log.info(""Initializing Discord Client..."") this.client = await this.initializeDiscordClient(this.token); this.api = this.initializeDiscordApi(this.token) await this.initializeDiscordComponents(); await this.registerCommandsWithGuilds(); this.listenForEvents(); } private listenForEvents() { this.log.info(""Listening for events...""); this.client.on(Events.InteractionCreate, async interaction => { if (!interaction.isChatInputCommand()) return; // If we have a handler for the command name, invoke it const handler = this.commandHandlers[interaction.commandName]; if (handler) { this.log.info(`Handling interaction for command ${interaction.commandName}...`); await handler.handle(interaction); } }); // If we have a handler for the message, invoke it this.client.on(Events.MessageCreate, async message => { if (message.author.bot) return; for (const handler of Object.keys(this.messageHandlers)) { await this.messageHandlers[handler].onNewMessage(message); } }); } private async initializeDiscordClient(token: string): Promise { const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent ] }); await client.login(token); return client; } private initializeDiscordApi(token: string): REST { return new REST({ version: '10' }).setToken(token); } private async initializeDiscordComponents() { this.log.info(""Initializing Discord Components...""); // Load the commands from the commands directory const commandsPath = path.join(__dirname, 'commands'); const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); for (const file of commandFiles) { const { default: command } = await import(`./commands/${file}`); this.commands.push(command); } // Load the command handlers from the handlers directory const cmdHandlersPath = path.join(__dirname, 'commandHandlers'); const cmdHandlerFiles = fs.readdirSync(cmdHandlersPath).filter(file => file.endsWith('.js')); for (const file of cmdHandlerFiles) { const { default: BaseCommandHandler } = await import(`./commandHandlers/${file}`); const Module = new BaseCommandHandler(this.components); this.commandHandlers[Module.id] = Module; } // Load the message event handlers from the handlers directory const msgHandlersPath = path.join(__dirname, 'messageHandlers'); const [MASK] = fs.readdirSync(msgHandlersPath).filter(file => file.endsWith('.js')); for (const file of [MASK] ) { const { default: BaseMessageHandler } = await import(`./messageHandlers/${file}`); const Module = new BaseMessageHandler(this.components); this.messageHandlers[Module.id] = Module; } } async fetchGuild(name: string): Promise { const guilds = await this.client.guilds.fetch(); const guild = guilds.find((g) => g.name === name); if (!guild) throw new Error(""Guild not found""); return await guild.fetch(); } private async registerCommandsWithGuilds(): Promise { const guilds = process.env.DISCORD_GUILDS.split(',').map((g) => g.trim()); if (!guilds || guilds.length === 0) { return this.log.warn(""No guilds have been configured for this bot. Commands will not be registered.""); } if (!this.commands || this.commands.length === 0) { return this.log.warn(""No commands to register with guilds.""); } for (const guild of guilds) { await this.registerCommandsWithGuild(guild); } } private async registerCommandsWithGuild(guildName: string): Promise { this.log.info(`Registering commands with guild: ${guildName}`); if (!this.commands || this.commands.length === 0) { return this.log.warn(""No commands to register with guild.""); } const guild = await this.fetchGuild(guildName); await this.registerCommands(guild); } private async registerCommands(guild: Guild): Promise { // The put method is used to fully refresh all commands in the guild with the current set await this.api.put( Routes.applicationGuildCommands(this.clientId, guild.id), { body: this.commands }, ); } }",msgHandlerFiles 313,"// -------------------------------------------- // 拦截器。 // 一个函数的处理结果将作为下一个拦截器处理函数的入参。 // @author: YuanYou // -------------------------------------------- type InterceptorHandler = (p: T) => V; export default class Interceptor { private handlers?: Array | null>; /** * 添加拦截器。 * 返回当前拦截器的id,可以用此来移除当前拦截器。 * @param handler 拦截器函数 */ public add(handler: InterceptorHandler): number { const fns = this.handlers || (this.handlers = []); return fns.push(handler) - 1; } /** * 移除指定拦截器。 * @param index 拦截器id */ public remove(index: number): void; /** * 移除指定拦截器。 * @param handler 注册的拦截器函数 */ public remove(handler: InterceptorHandler): void; public remove(handlerOrIndex: number | InterceptorHandler) { if (!this.handlers) return; if (typeof handlerOrIndex === 'number') { if (handlerOrIndex < this.handlers.length) { this.handlers[handlerOrIndex] = null; } } else { for (let i = 0; i < this.handlers.length; i++) { if (this.handlers[i] === handlerOrIndex) { this.handlers[i] = null; } } } } /** * 按照注册的顺序执行拦截器逻辑,上一个拦截器函数的返回值将作为下一个拦截器的入参, * 如果上一个没有返回值,则下一个拦截器的入参将和上一个入参一样。 * @param p 第一个拦截器的入参 */ public invoke(p: T): TResult { const fns = this.handlers || []; const dispatch = function(i: number, arg: any): any { if (i >= fns.length) return arg; const handler = fns[i]; let [MASK] = arg; if (handler) { [MASK] = handler(arg); if (typeof [MASK] === 'undefined') { [MASK] = arg; } } return dispatch(++i, [MASK] ); }; return dispatch(0, p); } }",handlerReturnValue 314,"declare var qrcode: any; class Application extends ioc.ApplicationContext { public pauseCapture: boolean = false; private imageProcessorFacade: ImageProcessorFacade; private dataProcessorFacade: DataProcessorFacade; constructor() { super('QR-Reader'); } public register(container: ioc.Container): void { // Register Instances container.register(PopupManager) .setLifetimeScope(ioc.LifetimeScope.SingleInstance); container.register(TabManager) .setLifetimeScope(ioc.LifetimeScope.SingleInstance); container.register(ActionManager) .setLifetimeScope(ioc.LifetimeScope.SingleInstance); container.register(ImageProcessorFacade) .setLifetimeScope(ioc.LifetimeScope.SingleInstance) .setResolveFunc((instance: ImageProcessorFacade) => instance .addImageProcessor(new Html5ImageProcessor()) .addImageProcessor(new FlashImageProcessor()) .setDefaultImageProcessor(new UploadImageProcessor())); container.register(DataProcessorFacade) .setLifetimeScope(ioc.LifetimeScope.SingleInstance) .setResolveFunc((instance: DataProcessorFacade) => instance .addDataProcessor(new TextDataProcessor()) .addDataProcessor(new IllustrationDataProcessor()) .addDataProcessor(new PDFDataProcessor()) .addDataProcessor(new RawFileDataProcessor()) .addDataProcessor(new UrlDataProcessor()) .addDataProcessor(new VCardDataProcessor()) .addDataProcessor(new SMSDataProcessor()) .addDataProcessor(new PhoneCallDataProcessor()) .addDataProcessor(new GeoLocationDataProcessor()) .addDataProcessor(new VEventDataProcessor()) .addDataProcessor(new MATMsgDataProcessor()) .addDataProcessor(new EmailDataProcessor()) .addDataProcessor(new NetworkDataProcessor())); this.initiate(container); } public initiate(container: ioc.Container): void { this.imageProcessorFacade = container.resolve(ImageProcessorFacade); this.dataProcessorFacade = container.resolve(DataProcessorFacade); // Check consent UserMediaHelper.checkPermissions(); // Let agree to terms let popupManager = container.resolve(PopupManager); let tabManager = container.resolve(TabManager); let popupContent = document.querySelector('.popupContent'); let hasAgreed = (CookieHelper.getCookie(Constants.agreedToTOA) || String()) === 'true'; if (!hasAgreed) { this.setTOAPopup(popupManager, tabManager, popupContent); } else { popupManager.setButtonState(true); this.startApp(tabManager, popupManager); } } public qrCallback(data: string, errorFunc: (error: string) => void): void { let application = Application.applicationContext; if (application.pauseCapture) return; try { this.dataProcessorFacade.calculate(data); } catch (e) { errorFunc(e.message); } return; } private setTOAPopup(popupManager: PopupManager, tabManager: TabManager, popupContent: HTMLDivElement): void { let checkButtonState = () => { if (popupContent.scrollHeight <= popupContent.clientHeight || popupContent.scrollTop >= (popupContent.scrollHeight - popupContent.offsetHeight) - (popupContent.scrollHeight / 100)) { popupManager.setButtonState(true); window.onresize = null; popupContent.onscroll = null; } }; window.onresize = checkButtonState; popupContent.onscroll = checkButtonState; tabManager.setActive('toa'); popupManager.show(false, false, () => { let today = new Date(); today.setFullYear(today.getFullYear() + 128); CookieHelper.setCookie(Constants.agreedToTOA, true, today); this.startApp(tabManager, popupManager); popupManager.hide(); }); checkButtonState(); } private startApp(tabManager: TabManager, popupManager: PopupManager): void { let [MASK] = document.querySelector('.help'); // Initiate application this.imageProcessorFacade.initiate(); [MASK] .onclick = () => { tabManager.setActive('about'); popupManager.show(); }; } } window.onload = () => { if (window.location.protocol !== 'https:') UrlHelper.redirect(window.location.href.replace(/^(http(s)?:\/\/)(\s)?/i, 'https://')); return new Application(); };",helpButton 315,"import type { DataType, Post } from ""./types.ts""; import { getLogByFileName } from ""./git.ts""; import { markdownToHtml } from ""./markdowntohtml.ts""; async function getPosts(): Promise { const [MASK] = Deno.readDir(""./post""); const data = [] as DataType; for await (const _fileName of [MASK] ) { if (_fileName.isFile) { const fileName = _fileName.name; const slug = fileName.replace(/\.md$/, """"); const commits = await getLogByFileName(fileName); const fileContent = await Deno.readTextFile(`./post/${fileName}`); const res = await markdownToHtml(fileContent); data.push({ slug, ...res, commits }); } } // 按发表时间,从新到旧(不过我不觉得这很科学 // ~~并且 JavaScript 的对象本来就是无序的,forin 遍历总会打乱~~ return data.sort((a: Post, b: Post) => new Date(b.commits[0].date).valueOf() - new Date(a.commits[0].date).valueOf() ); } const d = JSON.stringify(await getPosts()); console.log(d); ",fileNames 316,"import { IExecuteFunctions, INodeExecutionData, INodeProperties, NodeApiError, } from 'n8n-workflow'; import { OptionsWithUri } from 'request'; import { FenXToken } from './FenX.node'; let FenergoNebulaBusinessMetricsCommandv10Properties: INodeProperties[] = [ { displayName: 'Endpoint', name: 'endpoint', type: 'options', options: [ { name: 'Create a Journey Summary', value: 'CreateaJourneySummary' },{ name: 'Trigger the creation of a Journey Summary for all currently scheduled journeys', value: 'TriggerthecreationofaJourneySummaryforallcurrentlyscheduledjourneys' } ], displayOptions: { show: { domain: [ 'FenergoNebulaBusinessMetricsCommandv10', ], }, }, default: '', required: true, description: 'Operation to execute', }, { displayName: 'Request', name: 'request', type: 'json', required: true, default: '{ ""data"": { ""journeyIds"": [ """" ] } }', description: 'Request body', displayOptions: { show: { endpoint: [ 'CreateaJourneySummary' ], domain: [ 'FenergoNebulaBusinessMetricsCommandv10' ] } } } ]; async function ExecuteFenergoNebulaBusinessMetricsCommandv10(base: IExecuteFunctions): Promise < INodeExecutionData[][] > { // @ts-ignore let token = await FenXToken.getToken(base); let requestOptions: OptionsWithUri = { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token, 'x-tenant-id': FenXToken.tenant }, gzip: true, timeout: 3600000, uri: """" }; const endpoint = base.getNodeParameter('endpoint', 0) as string; switch(endpoint){ case 'CreateaJourneySummary': requestOptions.method = 'POST'; requestOptions.uri = 'https://api.fenergox.com/businessmetricscommand/api/journeysummary'; requestOptions.body = base.getNodeParameter('request', 0) as string; requestOptions.json = true;break; case 'TriggerthecreationofaJourneySummaryforallcurrentlyscheduledjourneys': requestOptions.method = 'POST'; requestOptions.uri = 'https://api.fenergox.com/businessmetricscommand/api/journeysummary/triggerscheduledsummaries'; break; } let request = base.helpers.request(requestOptions); // @ts-ignore const promisesResponses = await Promise.allSettled([request]); let response: any; // tslint:disable-line:no-any response = promisesResponses.shift(); if(response!.status !== 'fulfilled') { // throw error; console.log(request); throw new NodeApiError(base.getNode(), response); } try { response = JSON.parse(response.value); } catch { response = response.value; } const [MASK] : INodeExecutionData[] = []; [MASK] .push({ json: response }); return base.prepareOutputData( [MASK] ); } export { FenergoNebulaBusinessMetricsCommandv10Properties, ExecuteFenergoNebulaBusinessMetricsCommandv10 } ",returnItems 317,"/* eslint-disable no-irregular-whitespace */ /* eslint-disable no-useless-escape */ import { typeTextByLanguage, mapExtensionToType } from '../enum/hyperlink'; import { ExceptTextRange } from '../types/index'; export const listUnuseText = (text: string) => { // regex exec muti (?:) and return an array that contain start and end index const regex = /aria-label=(\\""|"")[^""]*(\\""|"")/g; let match: RegExpExecArray | null; const matches: ExceptTextRange[] = []; while ((match = regex.exec(text)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (match.index === regex.lastIndex) { regex.lastIndex++; } // get the start and end index of the match and store it in the array const start = match.index; const end = regex.lastIndex; matches.push({ start, end, text: match[0] }); } return matches; }; export const listLinkTag = (text: string) => { // regex exec muti (?:) and return an array that contain start and end index const regex = //g; let match: RegExpExecArray | null; const matches: ExceptTextRange[] = []; while ((match = regex.exec(text)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (match.index === regex.lastIndex) { regex.lastIndex++; } // get the start and end index of the match and store it in the array const start = match.index; const end = regex.lastIndex; matches.push({ start, end, text: match[0] }); } return matches; }; export const listImgTag = (text: string) => { // regex exec muti (?:) and return an array that contain start and end index const regex = //g; let match: RegExpExecArray | null; const matches: ExceptTextRange[] = []; while ((match = regex.exec(text)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (match.index === regex.lastIndex) { regex.lastIndex++; } // get the start and end index of the match and store it in the array const start = match.index; const end = regex.lastIndex; matches.push({ start, end, text: match[0] }); } return matches; }; export const replaceTextLinkToSpecialHyperlink = (text: string) => { const regex = /(?:http[s]*:\/\/)(?:[a-zA-Z\-_0-9\/.]+)\.(?:[a-zA-Z.]{2,3})\/(?:[a-zA-Z0-9\-_\/._~:?#\[\]@!$&'()*+,;=%]*)(?:[a-zA-Z0-9]+\.)(jpg|jpeg|png|svg|gif|avif|webp|bmp|ico|docx|doc|xlsx|xlsm|xlsb|xls|pptx|ppt|pdf)+(?:[\/,\?][^\s]{2,}|(?![\/,\?][^\s]{2,}))/g; let match: RegExpExecArray | null; while ((match = regex.exec(text)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (match.index === regex.lastIndex) { regex.lastIndex++; } const exceptRanges = [...listLinkTag(text), ...listImgTag(text), ...listUnuseText(text)]; const isExcept = exceptRanges.some(({ start, end }) => { return start <= match.index && match.index <= end; }); if (isExcept) continue; const { 0: url, 1: type } = match; const linkType = mapExtensionToType[type] || 'other'; const anchorText = typeTextByLanguage[linkType].default; let link = `${anchorText}`; if (linkType === 'image') link = ``; text = text.slice(0, match.index) + link + text.slice(regex.lastIndex); regex.lastIndex = match.index + link.length; } return text; }; export const replaceTextLinkToOtherHyperlink = (text: string) => { const regex = /(?:https?:\/\/(?:www\.|(?!www))(?:[a-zA-Z0-9][a-zA-Z0-9-]+(?:\.|(?!\.)))+(?:[\/,\?][^\s]{2,}|(?![\/,\?][^\s]{2,}))|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[a-zA-Z0-9]+(?:[\/,\?][^\s]{2,}|(?![\/,\?][^\s]{2,}))|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[a-zA-Z0-9]+(?:[\/,\?][^\s]{2,}|(?![\/,\?][^\s]{2,}))|www\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+(?:[\/,\?][^\s]{2,}|(?![\/,\?][^\s]{2,})))/g; let match: RegExpExecArray | null; while ((match = regex.exec(text)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (match.index === regex.lastIndex) { regex.lastIndex++; } const exceptRanges = [...listLinkTag(text), ...listImgTag(text), ...listUnuseText(text)]; const isExcept = exceptRanges.some(({ start, end }) => { return start <= match.index && match.index <= end; }); if (isExcept) { continue; } const url = match[0]; const link = `${url}`; text = text.slice(0, match.index) + link + text.slice(regex.lastIndex); regex.lastIndex = match.index + link.length; } return text; }; export const replaceTextLinkToEmailHyperlink = (text: string) => { const regex = /(?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)/g; let match: RegExpMatchArray | null; while ((match = regex.exec(text)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (match.index === regex.lastIndex) { regex.lastIndex++; } const exceptRanges = [...listLinkTag(text), ...listImgTag(text), ...listUnuseText(text)]; const isExcept = exceptRanges.some(({ start, end }) => { return start <= match.index && match.index <= end; }); if (isExcept) continue; const { 0: email } = match; const link = `${email}`; text = text.slice(0, match.index) + link + text.slice(regex.lastIndex); regex.lastIndex = match.index + link.length; } return text; }; export const replaceTextLinkToAddressHyperlink = (text: string) => { const regex = /(?:〒[0-90-9]{3}[--−][0-90-9]{4}[\n\s ]*)?(?:[^\n\s ;<>。、,,.:]{2,5}[都道府県市区町村]){1,3}(?:[^\n;<>。、.,,]{2,}?[0-90-9一二三四五六七八九十]+(?:-|-|−|丁目|地割|部|番町|号)[0-90-9一二三四五六七八九十]+(?:-|-|−|番地|番)?(?:[0-90-9一二三四五六七八九十]+号?)?)(?:[^\n;<>。、.,,]+ビル)?(?:[^\n;<>。、.,,]*?[0-90-9一二三四五六七八九]+[階F])?/g; let match: RegExpMatchArray | null; while ((match = regex.exec(text)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (match.index === regex.lastIndex) { regex.lastIndex++; } const exceptRanges = [...listLinkTag(text), ...listImgTag(text), ...listUnuseText(text)]; const isExcept = exceptRanges.some(({ start, end }) => { return start <= match.index && match.index <= end; }); if (isExcept) continue; const { 0: address } = match; const link = `${address}`; text = text.slice(0, match.index) + link + text.slice(regex.lastIndex); regex.lastIndex = match.index + link.length; } return text; }; export const replaceTextLinkToPhoneHyperlink = (text: string) => { const regex = /[++]?[(]{0,1}[0-90-9]{1,4}[)]{0,1}[-‐―−ー-0-90-9]{9,12}/g; let match: RegExpMatchArray | null; while ((match = regex.exec(text)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (match.index === regex.lastIndex) { regex.lastIndex++; } const exceptRanges = [...listLinkTag(text), ...listImgTag(text), ...listUnuseText(text)]; const isExcept = exceptRanges.some(({ start, end }) => { return start <= match.index && match.index <= end; }); if (isExcept) continue; const { 0: phone } = match; const link = `${phone}`; text = text.slice(0, match.index) + link + text.slice(regex.lastIndex); regex.lastIndex = match.index + link.length; } return text; }; const linkRegex = { byExtension: /(?:http[s]*:\/\/)(?:[a-zA-Z\-_0-9\/.]+)\.(?:[a-zA-Z.]{2,3})\/(?:[a-zA-Z0-9\-_\/._~:?#\[\]@!$&'()*+,;=%]*)(?:[a-zA-Z0-9]+\.)(jpg|jpeg|png|svg|gif|avif|webp|bmp|ico|docx|doc|xlsx|xlsm|xlsb|xls|pptx|ppt|pdf)+(?:[\/,\?][^\s]{2,}|(?![\/,\?][^\s]{2,}))/g, byOther: /(?:https?:\/\/(?:www\.|(?!www))(?:[a-zA-Z0-9][a-zA-Z0-9-]+(?:\.|(?!\.)))+(?:[\/,\?][^\s]{2,}|(?![\/,\?][^\s]{2,}))|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[a-zA-Z0-9]+(?:[\/,\?][^\s]{2,}|(?![\/,\?][^\s]{2,}))|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[a-zA-Z0-9]+(?:[\/,\?][^\s]{2,}|(?![\/,\?][^\s]{2,}))|www\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+(?:[\/,\?][^\s]{2,}|(?![\/,\?][^\s]{2,})))/g, }; export const replaceTextLinkToText = (text: string) => { const byExtensionRegex = linkRegex.byExtension; const matchs = text.matchAll(byExtensionRegex); for (const match of matchs) { const { 0: url, 1: type } = match; const linkType = mapExtensionToType[type] || 'other'; const anchorText = typeTextByLanguage[linkType].default; text = text.replace(url, anchorText); } const [MASK] = linkRegex.byOther; const matchs2 = text.matchAll( [MASK] ); for (const match of matchs2) { const { 0: url } = match; const anchorText = typeTextByLanguage['other'].default; text = text.replace(url, anchorText); } return text; }; ",byOtherRegex 318,"import { v4 as uuidv4 } from 'uuid'; export interface ChatThreadEntry { id: string; ts: string; slug: string; displayName: string; } export default class ChatThreadStore { private static storeKey = 'chatThreads'; private static pageSize = 10; static fetchEntries(page: number = 0): ChatThreadEntry[] { const allEntries = this.getAllEntries(); const startIndex = page * this.pageSize; const endIndex = startIndex + this.pageSize; const paginatedEntries = allEntries.slice(startIndex, endIndex); return paginatedEntries; } static addEntry(entry: ChatThreadEntry) { const allEntries = this.getAllEntries(); allEntries.unshift(entry); this.saveEntries(allEntries); } static deleteEntry(id: string) { const allEntries = this.getAllEntries(); const filteredEntries = allEntries.filter((entry) => entry.id !== id); this.saveEntries(filteredEntries); } static updateEntry(updatedEntry: ChatThreadEntry) { const allEntries = this.getAllEntries(); const entryIndex = allEntries.findIndex( (entry) => entry.id === updatedEntry.id ); if (entryIndex !== -1) { allEntries[entryIndex] = updatedEntry; this.saveEntries(allEntries); } } static findBySlug(slug: string): ChatThreadEntry | undefined { const allEntries = this.getAllEntries(); return allEntries.find((entry) => entry.slug === slug); } static getAllEntries(): ChatThreadEntry[] { const entriesJson = localStorage.getItem(this.storeKey); return entriesJson ? JSON.parse(entriesJson) : []; } private static saveEntries(entries: ChatThreadEntry[]) { localStorage.setItem(this.storeKey, JSON.stringify(entries)); } // Generate and add fake chat threads static generateFakeThreads(count: number) { const fakeThreads: ChatThreadEntry[] = []; const [MASK] = new Date(); for (let i = 0; i < count; i++) { const date = new Date( [MASK] .getTime() - i * 86400000); // Subtracting days fakeThreads.push({ id: uuidv4(), ts: date.toISOString(), slug: `thread-${i}`, displayName: `Sample Thread Sample Thread Sample Thread Sample Thread ${i}`, }); } const allEntries = this.getAllEntries(); this.saveEntries([...fakeThreads, ...allEntries]); } } ",now 319,"import io from ""socket.io-client""; import axios from ""axios""; const client = io(""http://localhost:3030"", { autoConnect: true, transports: [""websocket""] }); const searchForStock = async (text: string) => { const response = await axios.get( `http://localhost:3030/search?keywords=${text}` ); return response.data; }; const onStockUpdate = (symbol: string, [MASK] : any) => { console.log(`===== ${symbol} PRICE UPDATE ======`); console.log( [MASK] ); }; const subscribeToUpdates = (symbol: string) => { client.emit(""register"", symbol); client.on(""price-update"", (info) => { console.log(`on ${symbol}`); onStockUpdate(symbol, info); }); }; const start = async () => { var response = await searchForStock(""APPL""); for (const stock of response) { subscribeToUpdates(stock.symbol); } }; start(); ",stockInfo 320,"// SPDX-FileCopyrightText: © 2024-2025 // SPDX-License-Identifier: Apache-2.0 // --------------------------------------------------------------------------------------------------------------------- // MARK: Types + Parameters type IndexRecord = { size: number; chunks: number; prefix: string[]; ttldate: number; }; // Default key TTL is 1 day. const DEFAULT_KEY_TTL_MS = (1000 * 60) * 60 * 24; // The kv queue is used to notify the server that a new log has been uploaded // via watch events. const LATEST_LOG_KEY = ""logs/latest""; // --------------------------------------------------------------------------------------------------------------------- // If the user specifies DENO_KV_URL, then they also need DENO_KV_ACCESS_TOKEN. // This is in the case they want to use a locally hosted denokv service, OR they // want to plug their local deno instances into Deno Deploy KV. // // Otherwise, just call raw Deno.openKv() let kv = null; if (Deno.env.get(""DENO_KV_URL"") !== undefined) { if (Deno.env.get(""DENO_KV_ACCESS_TOKEN"") === undefined) { console.error(""DENO_KV_URL is set, but DENO_KV_ACCESS_TOKEN is not.""); Deno.exit(1); } const url = Deno.env.get(""DENO_KV_URL""); kv = await Deno.openKv(Deno.env.get(""DENO_KV_URL"")); console.log(`Deno KV: remote=${url}`); } else { const isDenoDeploy = Deno.env.get(""DENO_DEPLOYMENT_ID"") !== undefined; kv = await Deno.openKv(); console.log(""Deno KV:"", isDenoDeploy ? ""cloud"" : ""local""); } kv.listenQueue(async ( [MASK] : IndexRecord) => { await kv.set([LATEST_LOG_KEY], [MASK] , { expireIn: DEFAULT_KEY_TTL_MS }); }); // --------------------------------------------------------------------------------------------------------------------- // MARK: HTTP Server Interface const cache = await caches.open(""buck2-logs""); console.log(""Server started"", import.meta.url); export default { async fetch(request: Request): Promise { // MARK: URL routing const url = new URL(request.url); const key = url.pathname.slice(1); if (key === """" || key === null) { const status = 200; const body = """" + app(request); return new Response( body, { status, headers: { ""Content-Type"": ""text/html; charset=utf-8"", }, }, ); } // MARK: Log upload if (key.startsWith(""v1/logs/upload"")) { if (request.method !== ""PUT"") { return new Response(""Method not allowed"", { status: 405 }); } if (request.body === null) { return new Response(""Invalid request"", { status: 400 }); } const uuid = request.headers.get(""x-uuid""); const logType = request.headers.get(""x-type""); const logFormat = request.headers.get(""x-format""); const ts = request.headers.get(""x-timestamp""); if ( uuid === null || ts === null || logType === null || logFormat === null ) { return new Response(""Missing parameter"", { status: 400 }); } if (logFormat !== ""pb-zst"") { return new Response(""Invalid log format"", { status: 400 }); } const tss = ts.split(""-""); if (tss.length != 2) { return new Response(""Invalid timestamp"", { status: 400 }); } const [tsDate, tsDateTs] = [tss[0], tss[1]]; // given the above components, we have the following kv layout // // logs/$uuid -> [size, chunks, idx1/$date/$dateTs/$logType/$uuid] // idx1/$date/$dateTs/$logType/$uuid/1 -> binary log data // idx1/$date/$dateTs/$logType/$uuid/2 -> binary log data // idx1/$date/$dateTs/$logType/$uuid/3 -> binary log data // ... // const kkid = [""logs"", uuid]; const kkprefix = [""logs"", ""idx1"", tsDate, tsDateTs, logType, uuid]; const stream = request.body; // now, read the stream in chunks and write them to the db let idx = 1; let size = 0; console.log(""Uploading log"", uuid, ""with format"", logFormat); for await (const chunk of stream) { const expireIn = DEFAULT_KEY_TTL_MS * 2; // XXX FIXME (aseipp): explain const res = await kv.set([...kkprefix, idx.toString()], chunk, { expireIn, }); if (!res.ok) { return new Response(""Internal error: failed to write log"", { status: 500, }); } idx++; size += chunk.length; } console.log( ""Uploaded log"", uuid, ""of size"", size, ""with"", idx - 1, ""chunks"", ); // finally, write the log entry since we're done, and enqueue it const ttldate = Date.now() + DEFAULT_KEY_TTL_MS; const val: IndexRecord = { size, ttldate, chunks: idx - 1, prefix: kkprefix, }; const res = await kv.atomic() .check({ key: kkid, versionstamp: null }) .set(kkid, val, { expireIn: DEFAULT_KEY_TTL_MS }) .commit(); if (res.ok) { kv.enqueue(val); return new Response(""OK"", { status: 200 }); } else { return new Response(""Already exists"", { status: 404 }); } } else if (key.startsWith(""v1/logs/get"")) { // MARK: Log retrieval const ks = key.split(""/"").slice(3); if (ks.length != 1) { return new Response(""Invalid Request"", { status: 400 }); } const cached = await cache.match(request); if (cached !== undefined) { console.log(""Cache hit"", ks, request); return cached; } const kk = [""logs"", ks[0]]; const obj = await kv.get(kk); if (obj.value === null && obj.versionstamp === null) { return new Response(""Not found"", { status: 404 }); } const rec = obj.value as IndexRecord; const prefixstr = rec.prefix.join(""/""); console.log(prefixstr, ""Log retrieval requested"", rec); // the ttl is only the earliest expiry, so if the value is returned but // should have been expired, don't return it if (rec.ttldate < Date.now()) { return new Response(""Not found"", { status: 404 }); } let size = 0; let idx = 1; // iterate the keyspace and write out each blob to a stream const body = new ReadableStream({ async start(controller) { while (true) { const res = await kv.get([...rec.prefix, idx.toString()]); if (res.value === null && res.versionstamp === null) { break; } controller.enqueue(res.value as Uint8Array); size += (res.value as Uint8Array).length; idx++; } console.log(prefixstr, ""Log chunks"", idx - 1, ""size"", size); controller.close(); }, cancel() { console.log(prefixstr, ""Log retrieval cancelled""); }, }); const res = new Response(body, { headers: { ""content-type"": ""application/octet-stream"", }, }); cache.put(request, res.clone()); return res; } else if (key.startsWith(""v1/logs/watch"")) { // MARK: /v1/logs/watch SSE let logFormat = url.searchParams.get(""fmt""); logFormat = logFormat === null ? ""text"" : logFormat; logFormat = [""text"", ""html""].includes(logFormat) ? logFormat : ""text""; const headers = { ""Content-Type"": ""text/event-stream"" }; const stream = kv.watch([[LATEST_LOG_KEY]]).getReader(); const body = new ReadableStream({ async start(controller) { while (true) { if ((await stream.read()).done) { return; } const obj = await kv.get([""logs/latest""]); const data = obj.value as IndexRecord; if (data === null) { continue; } if (logFormat === ""html"") { const fdata = `

Log uploaded: ${ data.prefix.join(""/"") }

Size: ${data.size}

`; controller.enqueue( new TextEncoder().encode( `event: logupload\ndata: ${fdata}\n\n`, ), ); } else if (logFormat === ""text"") { const fdata = data.prefix.join(""/"") + "" "" + data.size; controller.enqueue( new TextEncoder().encode( `event: logupload\ndata: ${fdata}\n\n`, ), ); } else { console.log(""Invalid log format"", logFormat); controller.close(); } } }, cancel() { stream.cancel(); }, }); return new Response(body, { headers }); } else { return new Response(""Invalid request"", { status: 404 }); } }, }; // --------------------------------------------------------------------------------------------------------------------- // MARK: HTML function app(request: Request): string { const url = request.url + (request.url.endsWith(""/"") ? """" : ""/""); return ` Buck2 Logs

Log uploads

`; } ",msg 321,"import { Component, OnInit } from ""@angular/core""; import { RouterExtensions } from ""nativescript-angular""; //import { TextField } from 'ui/text-field'; import { EventData, Observable } from ""data/observable""; import { Router, NavigationExtras, ActivatedRoute } from ""@angular/router""; import { GooglePlayService } from ""~/shared/services/google-play.service""; import { Page } from ""tns-core-modules/ui/page""; import { SearchBar } from ""ui/search-bar""; import { ObservableArray } from ""tns-core-modules/data/observable-array/observable-array""; import { GeolocationService } from ""~/shared/services/geolocation.service""; import { Accuracy } from ""tns-core-modules/ui/enums/enums""; import * as appSettings from ""application-settings""; @Component({ selector: ""search"", templateUrl: ""./search/search.component.html"", styleUrls: [""./search/search.component.css""] }) export class SearchComponent implements OnInit { items: ObservableArray; public locationArray: Array; isListViewVisible: boolean = false; isOriginSearched: boolean = false; isDestinationSearched: boolean = false; searchType: string; public origin: string; public destination: string; isBusy: boolean = false; constructor( private _page: Page, private route: Router, private router: ActivatedRoute, private routerExtensions: RouterExtensions, private geolocationService: GeolocationService, private googleService: GooglePlayService ) { // this.getOrigin(); // this.router.queryParams.subscribe(params => { // this.searchType = params[""searchType""]; // }); } ngOnInit() { // this.isDestinationSearched = false; // this.isOriginSearched = false; // console.log(""<< result >> "" ); // var result= JSON.parse(appSettings.getString(""origin"") || ""[]""); // console.log(""<< result <<<> "" + result); // this.sub$ = this.route.params; // this.articles$ = this.sub$.switchMap((params: any) => { // this.categoryTitle = params['categoryTitle']; // return <any>this.firebaseService.getArticleList(params['id'])}); // this.articles$.subscribe(()=>{ // this.isBusy = this.isBusy==false ? true : false; // }); } getOrigin() { this.geolocationService .getLocation() .then(location => { console.log(""startpointLatitude received: "" + location.latitude); console.log(""startpointLongitude received: "" + location.longitude); // this.origin(); }) .catch(error => { console.log(""Location error received: "" + error); }); } onOriginTap(args) { let originSearch = args.object; if(this.isOriginSearched == false) { if (originSearch.text != null) { this.searchforOrigin(originSearch); } } } searchforOrigin(originSearch) { if (originSearch.text != null || originSearch.text.length != null || originSearch.text.length == 0) if (originSearch.text.length > 2 && originSearch.text.length % 3 === 0) { const searchString = originSearch.text.split("" "").join(""+""); this.isBusy = true; this.googleService.searchLocation(searchString).then( data => { this.isListViewVisible = true; this.items = new ObservableArray(); for (var i = 0; i < data.predictions.length; i++) { this.items.push({ description: data.predictions[i].description, placeId: data.predictions[i].place_id }); } this.searchType = ""origin""; this.isBusy= false; this.isOriginSearched = true; }, error => { this.isBusy = false; this.isListViewVisible = false; this.isOriginSearched =false; this.handleErrors(error); } ); } } onDestinationTap(args) { let [MASK] = args.object; if(this.isDestinationSearched == false) { if ( [MASK] .text != null) { this.searchforDestination( [MASK] ); } } } searchforDestination(destination) { if (destination.text != null || destination.text.length != null || destination.text.length == 0) if (destination.text.length > 2 && destination.text.length % 3 === 0) { const searchString = destination.text.split("" "").join(""+""); this.isBusy = true; this.googleService.searchLocation(searchString).then( data => { this.isListViewVisible = true; this.items = new ObservableArray(); for (var i = 0; i < data.predictions.length; i++) { this.items.push({ description: data.predictions[i].description, placeId: data.predictions[i].place_id }); } this.searchType = ""destination""; this.isBusy= false; this.isDestinationSearched = true; }, error => { this.isBusy = false; this.isListViewVisible = false; this.isDestinationSearched =false; this.handleErrors(error); } ); } } handleErrors(error: any) { console.error(error.message); } public onSelectedTap(args) { if (this.searchType == ""destination"") { console.log("">> destination is <<"" + this.searchType); this.destination = args.view.bindingContext.description; this.isListViewVisible = false; this.isDestinationSearched = true; //appSettings.setString(""destination"", args.view.bindingContext); if( this.origin != null){ this.route.navigate([""booking""]); } } else { console.log("">> origin is <<"" + this.searchType); this.origin = args.view.bindingContext.description; this.isListViewVisible = false; this.isOriginSearched = true console.log(""Output coordinates"" + JSON.stringify(args.view.bindingContext.placeId)); this.getIPAddress(args.view.bindingContext.placeId); // appSettings.setString(""origin"", args.view.bindingContext); } // // this.routerExtensions.back(); // } onOriginClear() { this.isOriginSearched = false; this.isListViewVisible = false; } onDestinationClear() { console.log("">> onDestinationClear<<"" ); this.isListViewVisible = false; this.isDestinationSearched = false; } onNavBtnTap() { // This code will be called only in Android. console.log("">> onNavBtnTap<<"" ); console.log(""Navigation button tapped!""); this.routerExtensions.back(); // // topmost().navigate(""booking""); } getIPAddress(placeId) { // console.log(""<<<<<<<<<<<<<<< placeId is: >>>>>>>>>>>>>>>>>>>>"" + placeId); this.googleService .getLocationIPByPlaceID(placeId) .then(results => { console.log(""Output"" + JSON.stringify(results)); // console.log(""data.result.geometry.lat : "" + JSON.stringify(results.result.geometry.lat)); const coordinates = [results.result.geometry]; // const newMarker = new GeoJson(coordinates, { message: this.message }) // console.log(""Output coordinates"" + JSON.stringify(results.result)); // console.log(""Output coordinates"" + JSON.stringify(results.result.geometry)); console.log(""Output coordinates"" + JSON.stringify(coordinates)); //console.log(""newMarker"" + JSON.stringify(newMarker)); // result.results.forEach(element => { // this.locationSearch.push({ country: element.country, streetname: element.country}); // }); // console.log(""Output"" + JSON.stringify(this.geoJson)); // this.origin = result.results[0].formatted_address; }) .catch(error => { console.log(""Error occured in retrieving IP address:"", error); }); } } ",destinationSearch 322,"import { Polar } from ""@convex-dev/polar""; import { api, components } from ""./_generated/api""; import { QueryCtx, mutation, query } from ""./_generated/server""; import { v } from ""convex/values""; import { Id } from ""./_generated/dataModel""; // User query to use in the Polar component export const getUserInfo = query({ args: {}, handler: async (ctx) => { // This would be replaced with an actual auth query, // eg., ctx.auth.getUserIdentity() or getAuthUserId(ctx) const user = await ctx.db.query(""users"").first(); if (!user) { throw new Error(""User not found""); } return user; }, }); export const polar = new Polar(components.polar, { products: { premiumMonthly: ""5fde8344-5fca-4d0b-adeb-2052cddfd9ed"", premiumYearly: ""9bc5ed5f-2065-40a4-bd1f-e012e448d82f"", premiumPlusMonthly: ""db548a6f-ff8c-4969-8f02-5f7301a36e7c"", premiumPlusYearly: ""9ff9976e-459e-4ebc-8cde-b2ced74f8822"", }, getUserInfo: async (ctx) => { const user: { _id: Id<""users"">; email: string } = await ctx.runQuery( api.example.getUserInfo ); return { userId: user._id, email: user.email, }; }, // These can be configured in code or via environment variables // Uncomment and replace with actual values to configure in code: // organizationToken: ""your_organization_token"", // Or use POLAR_ORGANIZATION_TOKEN env var // webhookSecret: ""your_webhook_secret"", // Or use POLAR_WEBHOOK_SECRET env var // server: ""sandbox"", // ""sandbox"" or ""production"", falls back to POLAR_SERVER env var }); export const MAX_FREE_TODOS = 3; export const MAX_PREMIUM_TODOS = 6; export const { // If you configure your products by key in the Polar constructor, // this query provides a keyed object of the products. getConfiguredProducts, // Lists all non-archived products, useful if you don't configure products by key. listAllProducts, // Generates a checkout link for the given product IDs. generateCheckoutLink, // Generates a customer portal URL for the current user. generateCustomerPortalUrl, // Changes the current subscription to the given product ID. changeCurrentSubscription, // Cancels the current subscription. cancelCurrentSubscription, } = polar.api(); // In a real app you'll set up authentication, we just use a // fake user for the example. const currentUser = async (ctx: QueryCtx) => { const user = await ctx.db.query(""users"").first(); if (!user) { throw new Error(""No user found""); } const subscription = await polar.getCurrentSubscription(ctx, { userId: user._id, }); const productKey = subscription?.productKey; const isPremium = productKey === ""premiumMonthly"" || productKey === ""premiumYearly""; const isPremiumPlus = productKey === ""premiumPlusMonthly"" || productKey === ""premiumPlusYearly""; return { ...user, isFree: !isPremium && !isPremiumPlus, isPremium, isPremiumPlus, subscription, maxTodos: isPremiumPlus ? undefined : isPremium ? MAX_PREMIUM_TODOS : MAX_FREE_TODOS, }; }; // Query that returns our pseudo user. export const getCurrentUser = query({ handler: async (ctx) => { return currentUser(ctx); }, }); export const authorizeTodo = async (ctx: QueryCtx, todoId: Id<""todos"">) => { const user = await currentUser(ctx); const todo = await ctx.db.get(todoId); if (!todo || todo.userId !== user._id) { throw new Error(""Todo not found""); } }; export const listTodos = query({ handler: async (ctx) => { const user = await currentUser(ctx); return ctx.db .query(""todos"") .withIndex(""userId"", (q) => q.eq(""userId"", user._id)) .collect(); }, }); export const insertTodo = mutation({ args: { text: v.string(), }, handler: async (ctx, args) => { const user = await currentUser(ctx); const [MASK] = ( await ctx.db .query(""todos"") .withIndex(""userId"", (q) => q.eq(""userId"", user._id)) .collect() ).length; const productKey = user.subscription?.productKey; if (!productKey && [MASK] >= MAX_FREE_TODOS) { throw new Error(""Reached maximum number of todos for free plan""); } if ( (productKey === ""premiumMonthly"" || productKey === ""premiumYearly"") && [MASK] >= MAX_PREMIUM_TODOS ) { throw new Error(""Reached maximum number of todos for premium plan""); } await ctx.db.insert(""todos"", { userId: user._id, text: args.text, completed: false, }); }, }); export const updateTodoText = mutation({ args: { todoId: v.id(""todos""), text: v.string(), }, handler: async (ctx, args) => { await authorizeTodo(ctx, args.todoId); await ctx.db.patch(args.todoId, { text: args.text }); }, }); export const completeTodo = mutation({ args: { todoId: v.id(""todos""), completed: v.boolean(), }, handler: async (ctx, args) => { await authorizeTodo(ctx, args.todoId); await ctx.db.patch(args.todoId, { completed: args.completed }); }, }); export const deleteTodo = mutation({ args: { todoId: v.id(""todos""), }, handler: async (ctx, args) => { await authorizeTodo(ctx, args.todoId); await ctx.db.delete(args.todoId); }, }); ",todoCount 323,"import axios from 'axios'; import { User, Task, DailyTask, Achievement, UserAchievement, CreateUserRequest, GenerateDailyTasksRequest, UnlockAchievementRequest, AuthUser, AuthResponse, TaskCompletionResponse, AchievementUnlockResponse } from '../types'; const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:8080'; const apiClient = axios.create({ baseURL: `${API_BASE_URL}/api`, headers: { 'Content-Type': 'application/json', }, withCredentials: true, // Enable cookies for authentication }); // Add request interceptor to handle authentication apiClient.interceptors.request.use( (config) => { // The JWT token will be automatically sent via HTTP-only cookies return config; }, (error) => { return Promise.reject(error); } ); // Add response interceptor to handle authentication errors apiClient.interceptors.response.use( (response) => response, async (error) => { if (error.response?.status === 401) { // Redirect to login or handle unauthorized access console.warn('Unauthorized request, user may need to re-authenticate'); } return Promise.reject(error); } ); // Authentication API export const authAPI = { // Initiate Google OAuth login googleLogin: async (): Promise => { try { const response = await apiClient.get('/auth/google'); const authUrl = response.data.auth_url; window.location.href = authUrl; } catch (error) { console.error('Failed to initiate Google login:', error); throw error; } }, // Check authentication status checkAuth: (): Promise => apiClient.get('/auth/check').then(res => res.data.user), // Get current user profile me: (): Promise => apiClient.get('/me').then(res => res.data), // Logout logout: (): Promise => apiClient.post('/auth/logout').then(res => res.data), // Refresh token refresh: (): Promise<{ token: string }> => apiClient.post('/auth/refresh').then(res => res.data), }; // User API export const userAPI = { create: (userData: CreateUserRequest): Promise => apiClient.post('/admin/users', userData).then(res => res.data), getById: (id: number): Promise => apiClient.get(`/users/${id}`).then(res => res.data), update: (id: number, userData: Partial): Promise => apiClient.put(`/users/${id}`, userData).then(res => res.data), // Get current user profile getCurrentProfile: (): Promise => apiClient.get('/profile').then(res => res.data), // Update current user profile updateCurrentProfile: (userData: Partial): Promise => apiClient.put('/profile', userData).then(res => res.data), // Get current user's tasks getCurrentUserTasks: (): Promise => apiClient.get('/users/tasks').then(res => res.data), // Get current user's achievements getCurrentUserAchievements: (): Promise => apiClient.get('/users/achievements').then(res => res.data), // Get user profile getProfile: (): Promise => apiClient.get('/profile').then(res => res.data), // Update user profile updateProfile: (userData: Partial): Promise => apiClient.put('/profile', userData).then(res => res.data), }; // Task API export const taskAPI = { getAll: (): Promise => apiClient.get('/public/tasks').then(res => res.data), getDailyTasks: (): Promise => apiClient.get('/tasks/daily').then(res => res.data.tasks), generateDailyTasks: (): Promise => apiClient.post('/tasks/daily/generate').then(res => res.data.tasks), completeTask: (taskId: number): Promise => apiClient.post(`/tasks/daily/${taskId}/complete`).then(res => res.data), }; // Achievement API export const achievementAPI = { getAll: (): Promise => apiClient.get('/public/achievements').then(res => res.data), getUserAchievements: (): Promise => apiClient.get('/achievements/user').then(res => res.data.achievements), unlock: ( [MASK] : number): Promise => apiClient.post(`/achievements/${ [MASK] }/unlock`).then(res => res.data), }; // Leaderboard API (assuming this will be added to backend) export const leaderboardAPI = { getTop: (limit: number = 10): Promise => apiClient.get(`/public/leaderboard?limit=${limit}`).then(res => res.data), }; export default apiClient; ",achievementId 324,"import { chains, ChainId } from ""@/lib/chains""; import { UnsupportedNetworkError } from ""@/lib/errors""; import Cors from ""cors""; import fetch from ""isomorphic-unfetch""; import type { NextApiRequest, NextApiResponse } from ""next""; // @ts-ignore globalThis.fetch = fetch; const CONTRACT_ADDRESS_REGEX = /^(0x)?[0-9a-fA-F]{40}$/; // Initializing the cors middleware const cors = Cors({ methods: [""POST"", ""GET"", ""HEAD""], }); function runMiddleware(req: NextApiRequest, res: NextApiResponse, fn: Function) { return new Promise((resolve, reject) => { fn(req, res, (result: any) => { if (result instanceof Error) { return reject(result); } return resolve(result); }); }); } async function trackEvent() { await fetch(""https://queue.simpleanalyticscdn.com/events"", { method: ""POST"", headers: { ""Content-Type"": ""application/json"", }, body: JSON.stringify({ type: ""event"", hostname: ""abidata.net"", event: ""ABI lookup"", path: ""/api"", ua: ""Vercel Edge Functions"", unique: true, }), }); } /** * @param addy A valid lowercased Ethereum address * @param network The network to use. * @returns The JSON abi of the contract at `addy`. */ async function getAbi(addy: string, network = ""mainnet"") { if (!Object.keys(chains).includes(network)) { throw new UnsupportedNetworkError(network); } const chain = chains[network as ChainId]; // Network is defined in the mappings but the API key was not provided if (!chain.key) { throw new UnsupportedNetworkError(network); } const [MASK] = `https://${chain.hostname}/api?module=contract&action=getabi&address=${addy}&apikey=${chain.key}`; const response = await fetch( [MASK] ); // Etherscan API returned an non-200 HTTP code if (!response.ok) { throw new Error(`Cannot fetch ABI on ${network}`); } // Etherscan API returned NOTOK code, possibly an invalid API key const result = await response.json(); if (result.message === ""NOTOK"") { throw new Error(`Cannot fetch ABI on ${network}`); } return JSON.parse(result.result); } export default async function handler(req: any, res: any) { await runMiddleware(req, res, cors); res.setHeader(""Cache-Control"", ""s-maxage=31536000000""); const { address, network } = req.query; const addy = address.toLowerCase(); if (!CONTRACT_ADDRESS_REGEX.test(addy)) { res.status(400).json({ ok: false, error: `Unable to resolve ${addy} because it’s not a valid Ethereum contract address.`, }); return; } try { const abi = await getAbi(addy, network); await trackEvent(); res.status(200).json({ ok: true, abi, }); } catch (e) { let message = `Unable to resolve ${addy}. Please try again with a different contract or network, or contact @pugson on Telegram if this keeps happening.`; if (e instanceof UnsupportedNetworkError) { message = e.message; } res.status(400).json({ ok: false, error: message, }); } } ",url 325,"import { ComboBoxDataProviderParams } from '@hilla/react-components/ComboBox'; import Filter from 'Frontend/generated/dev/hilla/crud/filter/Filter'; import PropertyStringFilter from 'Frontend/generated/dev/hilla/crud/filter/PropertyStringFilter'; import Pageable from 'Frontend/generated/dev/hilla/mappedtypes/Pageable'; export function comboBoxLazyFilter( [MASK] : ComboBoxDataProviderParams, type: string, property: PropertyStringFilter[]) { const { page, pageSize, filter } = [MASK] ; const pagination: Pageable = { pageNumber: page, pageSize: pageSize, sort: { orders: [] }, }; const filters: Filter = { '@type': type, children: property }; return { pagination, filters }; } export function filterById(type: string, property: PropertyStringFilter[]) { const pagination: Pageable = { pageNumber: 0, pageSize: 1, sort: { orders: [] }, }; const filters: Filter = { '@type': type, children: property }; return { pagination, filters }; } ",comboBoxDataProviderParams 326,"import request from '@/utils/request' import type { PaginationParams, ActivitySearchCriteria, Activity, SearchActivityByCriteriaResponse, CreateActivityResponse, UpdateActivityResponse, DeleteActivityResponse, FindActivityByIdResponse, CommentActivityResponse } from './types' enum API { SEARCH_ACTIVITIES_ENDPOINT = '/activities/search', ACTIVITIES_ENDPOINT = '/activities' } export const searchActivities = ( params: PaginationParams, searchCriteria: ActivitySearchCriteria ) => request.post( API.SEARCH_ACTIVITIES_ENDPOINT, searchCriteria, { params } ) export const findActivityById = (id: number) => request.get(`${API.ACTIVITIES_ENDPOINT}/${id}`) export const createActivity = ( [MASK] : Activity) => request.post(API.ACTIVITIES_ENDPOINT, [MASK] ) export const updateActivity = (updatedActivity: Activity) => request.put( `${API.ACTIVITIES_ENDPOINT}/${updatedActivity.activityId}`, updatedActivity ) export const deleteActivity = (id: number) => request.delete(`${API.ACTIVITIES_ENDPOINT}/${id}`) export const commentActivity = (id: number, comment: string) => request.patch(`${API.ACTIVITIES_ENDPOINT}/${id}/comments`, { comment }) ",newActivity 327,"/* * 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. */ 'use strict'; import * as vscode from 'vscode'; import { LanguageClientOptions } from 'vscode-languageclient'; import { LanguageClient } from 'vscode-languageclient/browser'; import { initVFS } from './virtualFileSystem'; import { log } from './log'; import { compileToTarget, } from './commands/compileToTarget'; import { loadProjectFiles, } from './commands/loadProjectFiles'; import { inlineSuggestionProvider } from './copilot/inlineSuggestionProvider'; import { promptProvider } from './copilot/promptProvider'; import { createSettingsWebview } from './copilot/settingsView/configSetting'; import { createStatusBarItem } from './copilot/statusBarItemProvider'; import { codeActionProvider } from './copilot/codeActionProvider'; import { registerToggleSettingsCommands } from './copilot/toggleSettings'; import { registerQuickPickCommand } from './copilot/quickPick'; import { createOrShowChatPanel } from './copilot/chatPanel/chatPanel'; import { createFileGeneratorPanel } from './copilot/modelGeneratorWizard/modelGeneratorPanel'; /** * Called when VS Code extension is activated. The conditions for * activation are specified in package.json (e.g. opening a .cto file) * @param context the extension context */ export async function activate(context: vscode.ExtensionContext) { log('Accord Project Extension activated'); const documentSelector = [ { language: 'concerto' }, { language: 'concerto-vocabulary' }, { language: 'templatemark' } ]; // Options to control the language client const clientOptions: LanguageClientOptions = { documentSelector, synchronize: { fileEvents: [vscode.workspace.createFileSystemWatcher('**/*.cto'), vscode.workspace.createFileSystemWatcher('**/*.voc') ] }, initializationOptions: {}, }; const client = createWorkerLanguageClient(context, clientOptions); const disposable = client.start(); context.subscriptions.push(disposable); await client.onReady(); log('Accord Project client is ready'); // initialize client-side handlers that // expose the workspace.fs filesystem to the language // server over RPC - allowing the language server process // to query the workspace from its process initVFS(client); // register commands // menus etc for commands are defined in package.json context.subscriptions.push(vscode.commands .registerCommand('cicero-vscode-extension.compileToTarget', (file) => compileToTarget(client, file))); context.subscriptions.push(vscode.commands .registerCommand('cicero-vscode-extension.loadProjectFiles', (file) => loadProjectFiles(client, file))); // Register the prompt provider command, startPromptProviderUI context.subscriptions.push(vscode.commands .registerCommand('cicero-vscode-extension.startPromptProviderUI', () => promptProvider.showPromptInputBox(client))); // Register the settings webview command, configureSettings context.subscriptions.push(vscode.commands .registerCommand('cicero-vscode-extension.configureSettings', () => createSettingsWebview(context, client))); // Register the quick pick command registerQuickPickCommand(context, client); // Create and show the status bar item, statusBarItem createStatusBarItem(context); // Register the toggle settings commands registerToggleSettingsCommands(context, client); context.subscriptions.push(vscode.commands .registerCommand('cicero-vscode-extension.chatPanelWithErrorMessage', (errorMessage) => createOrShowChatPanel(client, context, errorMessage))); context.subscriptions.push(vscode.commands .registerCommand('cicero-vscode-extension.openFileGenerator', () => createFileGeneratorPanel(context, client))); } function createWorkerLanguageClient(context: vscode.ExtensionContext, clientOptions: LanguageClientOptions) { // Create a web worker. The worker main file implements the language server. const [MASK] = vscode.Uri.joinPath(context.extensionUri, 'server/dist/browserServerMain.js'); const worker = new Worker( [MASK] .toString(true)); // create the language server client to communicate with the server running in the worker return new LanguageClient('cicero-vscode-extension', 'Accord Project - Server', clientOptions, worker); }",serverMain 328,"import type {Client} from ""./transport/client/Client""; import type {ClientProvider} from ""./transport/client/ClientProvider""; import {Asserts} from ""./transport/core/Asserts""; import {ClientConfig} from ""./transport/client/ClientConfig""; import {ClusterClient} from ""./cluster/ClusterClient""; import {WsProvider} from ""./transport_websocket/WsProvider""; import type {RouteSelector} from ""./transport/core/RouteSelector""; import type {IoBiConsumer} from ""./transport/core/Typealias""; import type {Session} from ""./transport/core/Session""; import type {Message} from ""./transport/core/Message""; import {EntityMetas} from ""./transport/core/EntityMetas""; import {ServerProvider} from ""./transport/server/ServerProvider""; import {ServerConfig} from ""./transport/server/ServerConfig""; import {Server} from ""./transport/server/Server""; import {BrokerListener} from ""./broker/BrokerListener""; import {BrokerFragmentHandler} from ""./broker/BrokerFragmentHandler""; import {EventListener} from ""./transport/core/listener/EventListener""; import {Listener} from ""./transport/core/Listener""; import {PathListener} from ""./transport/core/listener/PathListener""; import {PipelineListener} from ""./transport/core/listener/PipelineListener""; import {SimpleListener} from ""./transport/core/listener/SimpleListener""; import {EntityDefault} from ""./transport/core/entity/EntityDefault""; import {FileEntity} from ""./transport/core/entity/FileEntity""; import {StringEntity} from ""./transport/core/entity/StringEntity""; export class SocketD { /** * 元信息字典 * */ static EntityMetas = EntityMetas; private static clientProviderMap: Map = new Map(); private static serverProviderMap: Map = new Map(); static { const provider = new WsProvider(); SocketD.registerClientProvider(provider); SocketD.registerServerProvider(provider); } static registerClientProvider(clientProvider: ClientProvider) { for (let s of clientProvider.schemas()) { SocketD.clientProviderMap.set(s, clientProvider); } } static registerServerProvider(serverProvider: ServerProvider) { for (let s of serverProvider.schemas()) { SocketD.serverProviderMap.set(s, serverProvider); } } /** * 框架版本号 */ static version(): string { return ""2.5.18""; } /** * 协议名 */ static protocolName(): string { return ""Socket.D""; } /** * 协议版本号 */ static protocolVersion(): string { return ""1.0""; } /** * 创建服务端 */ static createServer(schema: string): Server { let server = this.createServerOrNull(schema); if (server == null) { throw new Error(""No socketd server providers were found: "" + schema); } else { return server; } } /** * 创建服务端,如果没有则为 null */ static createServerOrNull(schema: string): Server | null { Asserts.assertNull(""schema"", schema); let factory = SocketD.serverProviderMap.get(schema); if (factory == null) { return null; } else { return factory.createServer(new ServerConfig(schema)); } } /** * 创建客户端(支持 url 自动识别) * * @param serverUrl 服务器地址 */ static createClient(serverUrl: string): Client { const client = this.createClientOrNull(serverUrl); if (client == null) { throw new Error(""No socketd client providers were found: "" + serverUrl); } else { return client; } } /** * 创建客户端(支持 url 自动识别),如果没有则为 null * * @param serverUrl 服务器地址 */ static createClientOrNull(serverUrl: string): Client | null { Asserts.assertNull(""serverUrl"", serverUrl); const [MASK] = serverUrl.indexOf(""://""); if ( [MASK] < 2) { throw new Error(""The serverUrl invalid: "" + serverUrl); } const schema = serverUrl.substring(0, [MASK] ); const factory = this.clientProviderMap.get(schema); if (factory == null) { return null; } else { const clientConfig = new ClientConfig(serverUrl); return factory.createClient(clientConfig); } } /** * 创建集群客户端 * * @param serverUrls 服务端地址 */ static createClusterClient(serverUrls: string[] | string): ClusterClient { return new ClusterClient(serverUrls); } /** * 创建实体 * */ static newEntity(data?: string | Blob | ArrayBuffer): EntityDefault { if (!data) { return new EntityDefault(); } else if (typeof (File) != 'undefined' && data instanceof File) { return new FileEntity(data); } else if (typeof (ArrayBuffer) != 'undefined' && data instanceof ArrayBuffer) { return new EntityDefault().dataSet(data); } else if (typeof (Blob) != 'undefined' && data instanceof Blob) { return new EntityDefault().dataSet(data); } else { return new StringEntity(String(data)); } } /** * 创建简单临听器 * */ static newSimpleListener(): SimpleListener { return new SimpleListener(); } /** * 创建事件监听器 * */ static newEventListener(routeSelector?: RouteSelector>): EventListener { return new EventListener(routeSelector); } /** * 创建路径监听器(一般用于服务端) * */ static newPathListener(routeSelector?: RouteSelector): PathListener { return new PathListener(routeSelector); } /** * 创建管道监听器 * */ static newPipelineListener(): PipelineListener { return new PipelineListener(); } /** * 创建经理人监听器 * */ static newBrokerListener(): BrokerListener { return new BrokerListener(); } /** * 创建经理人分布处理 * */ static newBrokerFragmentHandler(): BrokerFragmentHandler { return new BrokerFragmentHandler(); } }",idx 329,"import { Component, OnInit } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { WindowRefService } from 'app/shared/services'; @Component({ selector: 'pp-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { constructor( private windowRefService: WindowRefService, private translateService: TranslateService ) { const [MASK] = ['en', 'ko']; const defaultLang = 'en'; const currentLang = this.windowRefService.nativeWindow.navigator.language.substring(0, 2); this.translateService.addLangs( [MASK] ); this.translateService.setDefaultLang(defaultLang); if ( [MASK] .find((lang: string) => { return lang === currentLang; })) { this.translateService.use(currentLang); } else { this.translateService.use(defaultLang); } } ngOnInit() {} } ",supportLanguages 330,"import * as core from '@actions/core'; import { GitHub } from '@actions/github/lib/utils'; export const getTeamSlugsForAuthor = async ( octokit: InstanceType, org: string, username: string, ignoreSlugs: string[] = [], ): Promise => { const { data: allTeams } = await octokit.rest.teams.list({ org, }); const [MASK] : string[] = []; for await (const { slug } of allTeams) { if (ignoreSlugs.includes(slug)) { continue; } try { const { data: membership } = await octokit.rest.teams.getMembershipForUserInOrg({ org, team_slug: slug, username, }); if (membership.state === 'active') { [MASK] .push(slug); } } catch (error) { // Octokit query fails when username is not member of a team, see https://octokit.github.io/rest.js/v18 core.info(`${username} not a member of ${slug}`); } } return [MASK] ; }; ",authorsTeamSlugs 331,"//作者:hhh5460 //时间:2017年6月26日 // 棋盘 class Board { private board: string[]; private history: any[][]; public constructor() { //self._board = '-'*9 // 坑!! this.board = new Array(9); for (let i = 0; i < 9; i++) { this.board[i] = '-'; } this.history = []; // 棋谱 }; // 按指定动作,放入棋子 public move = (action: number, take: string): void => { if (this.board[action] == '-') { this.board[action] = take; this.history.push([action, take]) // 加入棋谱 } }; // 撤销动作,拿走棋子 public unmove = (action: number): void => { this.board[action] = '-'; this.history.pop(); }; // 棋盘快照 public get_board_snapshot = (): string[] => { return this.board.slice(); }; // 取棋盘上的合法走法 public get_legal_actions = (): number[] => { let actions: number[] = []; for (let i = 0; i < 9; i++) { if (this.board[i] == '-') { actions.push(i); } } return actions; }; // 判断走法是否合法 public is_legal_action = (action: number): boolean => { return this.board[action] == '-'; }; // 终止检测 public teminate = (): boolean => { //let _board: string[] = this.board; let lines = [ this.board.slice(0, 3), this.board.slice(3, 6), this.board.slice(6, 9), [this.board[0], this.board[3], this.board[6]], [this.board[1], this.board[4], this.board[7]], [this.board[2], this.board[5], this.board[8]], [this.board[0], this.board[4], this.board[8]], [this.board[2], this.board[4], this.board[6]]]; if (lines.toString().indexOf(['X', 'X', 'X'].toString()) != -1 || lines.toString().indexOf(['O', 'O', 'O'].toString()) != -1 || '-' in this.board) { return true; } else { return false; } }; // 胜负检查 public get_winner = (): number => { let lines = [ this.board.slice(0, 3), this.board.slice(3, 6), this.board.slice(6, 9), [this.board[0], this.board[3], this.board[6]], [this.board[1], this.board[4], this.board[7]], [this.board[2], this.board[5], this.board[8]], [this.board[0], this.board[4], this.board[8]], [this.board[2], this.board[4], this.board[6]]]; if (lines.toString().indexOf(['X', 'X', 'X'].toString()) != -1) { return 0; } else if (lines.toString().indexOf(['O', 'O', 'O'].toString()) != -1) { return 1; } else { return 2; } }; // 打印棋盘 public print_b = (): void => { for (let i = 0; i < this.board.length; i++) { console.log(this.board[i]); if ((i + 1) % 3 == 0) { print(); } } }; // 打印棋谱 public print_history = (): void => { console.log(this.history); }; } // 玩家 class Player { /* 玩家只做两件事:思考、落子 1. 思考 --> 得到走法 2. 落子 --> 执行走法,改变棋盘 */ public take: string; public constructor(take = 'X') { // 默认执的棋子为 take = 'X' this.take = take; }; public think = (board: Board): number => { return 0; }; public move = (board: Board, action: number) => { board.move(action, this.take); }; } // 人类玩家 class HumanPlayer extends Player { public constructor(take) { super(take); }; public think = (board: Board): number => { while (true) { //let action = input('Please input a num in 0-8:'); //if (len(action) == 1 && action in '012345678' && board.is_legal_action( int(action))) //return int(action); return -1; } }; } // 电脑玩家 class AIPlayer extends Player { public constructor(take: string) { super(take); }; public think = (board: Board): number => { console.log('AI is thinking ...'); let take = this.take == 'X' ? 'X' : '0'; let player = new AIPlayer(take); // 假想敌!!! let res = this.minimax(board, player); //print('OK') return res![1]; }; // 极大极小法搜索,α-β剪枝 public minimax = (board: Board, player: AIPlayer, depth = 0): number[] => { let [MASK] !: number, bestAction!: number; //参考:https://stackoverflow.com/questions/44089757/minimax-algorithm-for-tic-tac-toe-python if (this.take == ""O"") { [MASK] = -10; } else { [MASK] = 10; } if (board.teminate()) { if (board.get_winner() == 0) { return [-10 + depth, 0]; } else if (board.get_winner() == 1) { return [10 - depth, 0]; } else if (board.get_winner() == 2) { return [0, 0]; } } for (let action of board.get_legal_actions()) { // 遍历合法走法 board.move(action, this.take); let val = player.minimax(board, this, depth + 1); // 切换到 假想敌!!! board.unmove(action); // 撤销走法,回溯 if (this.take == ""O"") { if (val[0] > [MASK] ) { [MASK] = val[0]; bestAction = action; } } else { if (val[0] < [MASK] ) { [MASK] = val[0]; bestAction = action; } } return [ [MASK] , bestAction]; } }; } // 游戏 class Game { public constructor() { this.board = new Board(); this.current_player = null; }; private board: Board; private current_player: Player | null; // 生成玩家 private mk_player = (p: number, take = 'X'): Player => { // p in [0,1] if (p == 0) { return new HumanPlayer(take); } else { return new AIPlayer(take); } }; // 切换玩家 private switch_player = (player1: Player, player2: Player) => { if (this.current_player == null) { return player1; } else { return this.current_player == player1 ? player1 : player2; } }; // 打印赢家 private print_winner = (winner: number):void => { // winner in [0,1,2] //print(['Winner is player1', 'Winner is player2', 'Draw'][winner]) }; // 运行游戏 public run = (): void => { //ps = input(""Please select two player's type:\n\t0.Human\n\t1.AI\nSuch as:0 0\n"" ) //p1, p2 = [int(p) for p in ps.split(' ')] let player1 = this.mk_player(0, 'X'); let player2 = this.mk_player(1, 'O'); // 先手执X,后手执O let winner: number; console.log('\nGame start!\n'); this.board.print_b(); // 显示棋盘 while (true) { this.current_player = this.switch_player(player1, player2); // 切换当前玩家 let action = this.current_player.think(this.board); // 当前玩家对棋盘进行思考后,得到招法 this.current_player.move(this.board, action); // 当前玩家执行招法,改变棋盘 this.board.print_b(); // 显示当前棋盘 if (this.board.teminate()) { // 根据当前棋盘,判断棋局是否终止 winner = this.board.get_winner(); // 得到赢家 0,1,2 break; } } this.print_winner(winner); console.log('Game over!'); this.board.print_history(); }; } let g = new Game(); g.run(); ",bestVal 332,"/* -------------------------------------------------------------------------------- * Copyright: Altair Engineering Inc., 2023. All rights reserved. * Contains trade secrets of Altair Engineering, Inc. * Copyright notice does not imply publication. * Decompilation or disassembly of this software is strictly prohibited. * --------------------------------------------------------------------------------*/ 'use script'; import * as configuration from '../configuration'; export class Copyright { protected author: string; protected year: string; protected headerText: string; constructor() { this.author = configuration.getAuthor(); this.year = new Date().getFullYear().toString(); this.headerText = configuration.getHeaderText().toString(); } public header(): string { let [MASK] = this.headerText; return [MASK] ; } } ",template 333,"import {execSync} from 'child_process'; import {writeFileSync} from 'fs'; import {buildClientSchema, getIntrospectionQuery, printSchema} from 'graphql'; const pyVer = execSync('python --version').toString(); const verMatch = pyVer.match(/Python ([\d.]*)/); if (!(verMatch != null && verMatch.length >= 2 && parseFloat(verMatch[1]) >= 3.6)) { const errMsg = pyVer !== '' ? pyVer : 'nothing on stdout indicating no python or a version earlier than 3.4'; throw new Error(`Must use Python version >= 3.6 got ${errMsg}`); } console.log('Downloading schema...'); // https://github.com/dagster-io/dagster/issues/2623 const result = execSync( `dagster-graphql --ephemeral-instance --empty-workspace -t '${getIntrospectionQuery({ descriptions: false, })}'`, {cwd: '../../../../examples/docs_snippets/'}, ).toString(); const schemaJson = JSON.parse(result).data; // Write schema.graphql in the SDL format const sdl = printSchema(buildClientSchema(schemaJson)); console.log('Generating schema.graphql...'); writeFileSync('./src/graphql/schema.graphql', sdl); // Write `possibleTypes.generated.json`, used in prod for `AppCache` and in tests for creating // a mocked schema. const possibleTypes = {}; schemaJson.__schema.types.forEach(( [MASK] : {name: string; possibleTypes: [{name: string}]}) => { if ( [MASK] .possibleTypes) { possibleTypes[ [MASK] .name] = [MASK] .possibleTypes.map((subtype) => subtype.name); } }); console.log('Generating possibleTypes.generated.json...'); writeFileSync('./src/graphql/possibleTypes.generated.json', JSON.stringify(possibleTypes)); console.log('Generating TypeScript types...'); execSync( 'find src -type d -name types | xargs rm -r && yarn apollo codegen:generate --includes ""./src/**/*.tsx"" --target typescript types --localSchemaFile ./src/graphql/schema.graphql --globalTypesFile ./src/types/globalTypes.ts && python append_generated.py', {stdio: 'inherit'}, ); console.log('Done!'); ",supertype 334,"import * as THREE from 'three' import TWEEN from '@tweenjs/tween.js' import Timeline from '../managers/Timeline' // You can make also your own 3d objects to clean up code in seperated files // Here is also a TweenJS example export default class StarDoughnut extends THREE.Object3D { private _doughnut: THREE.Points constructor() { super() this._createMesh() this._tweenDoughnutScale() } /** * We create our own doughnut mesh (points) and add it to ourself (the Object3D) */ private _createMesh(): void { // First we need a geometry const doughnutGeometry = new THREE.TorusGeometry(3, 1, 16, 100) // Then we need a material with our stars const [MASK] = new THREE.PointsMaterial({ color: 0xddddff, size: 0.4, map: new THREE.TextureLoader().load('./images/star.png'), transparent: true, alphaToCoverage: true }) // Now we create our mesh (in this case points) with those two components this._doughnut = new THREE.Points(doughnutGeometry, [MASK] ) // And add this mesh to our custom object to make it visible this.add(this._doughnut) } /** * Animation example with TWEEN * This Method is a bit magic because of the TWEEN library setup inside index.ts and Timeline * It Bounces the doughnut smooth!!! */ private _tweenDoughnutScale(): void { // This is how long a bouncing is (3 scaled seconds) const TWEEN_DURATION = 3 // This method makes TWEEN JS compatible with THREE JS // We are setting the scale we defined inside tweens to our doughnut // The properties (like scale) are custom const onTweenUpdate = (data: { scale: number }, elapsed: number) => { this._doughnut.scale.set(data.scale, data.scale, data.scale) } // Create the first Tween // It Starts with the custom prop scale 1 const tween1 = new TWEEN.Tween({ scale: 1 }) // and ends with the custom prop scale 0.4 in TWEEN_DURATION seconds (3 scaled seconds) .to({ scale: 0.4 }, TWEEN_DURATION) // we make this tween compatible to our doughnut .onUpdate(onTweenUpdate) // and set the Easing Function to TWEEN.Easing.Bounce.InOut // you can explore the easing functions inside TWEEN.Easing and watch what happens .easing(TWEEN.Easing.Bounce.InOut) // Create the second Tween // It Starts with the custom prop scale 0.4 const tween2 = new TWEEN.Tween({ scale: 0.4 }) // and ends with the custom prop scale 1 in TWEEN_DURATION seconds (3 scaled seconds) .to({ scale: 1 }, TWEEN_DURATION) // we make this tween compatible to our doughnut .onUpdate(onTweenUpdate) // and set the Easing Function to TWEEN.Easing.Bounce.InOut // you can explore the easing functions inside TWEEN.Easing and watch what happens .easing(TWEEN.Easing.Bounce.InOut) // After tween1 play immediately tween2 tween1.chain(tween2) // After tween2 play immediately tween1 tween2.chain(tween1) // You see now that this is a loop ;) // Start tween1 to start the loop // ""Timeline.time"" MUST BE THE ARGUMENT OF EVERY TWEEN ""start"" METHOD. OTHERWISE IT WILL BE NOT COMPATIBLE WITH THE SCALED TIME AND ANIMATES WIERD. THIS HAS TAKEN SO LONG TO FIGURE IT OUT. tween1.start(Timeline.time) } /** * Animation example without TWEEN (normal THREE JS animation) * This method must be called inside the animation loop to rotate the doughnut * It rotates the doughnut linear */ public update(): void { // Rotate me linear 90deg per seconds // (((Math.PI == 180deg) * 0.5 == 90deg) * delta) == 9deg if delta is 0.1 this._doughnut.rotateY(Math.PI * 0.5 * Timeline.delta) } } ",starMaterial 335,"import * as Bluebird from 'bluebird'; import * as fs from 'promise-fs'; import * as path from 'path'; import * as os from 'os'; import { List } from '@assasans/storage'; import { Token } from '../token'; import { Service } from './service'; export class FirefoxService extends Service { public constructor(name: string, directory: string) { super(name, directory); } public async getTokens(): Promise> { const tokens: List = new List(); const profilesDirectory = path.join( os.homedir(), 'AppData', this.directory, 'Profiles' ); if(!await this.exists(profilesDirectory)) return tokens; const [MASK] : string[] = (await fs.readdir(profilesDirectory, { encoding: 'utf8' })) .map((relative: string) => path.join(profilesDirectory, relative)); await Bluebird.all( [MASK] .map(async (profileDirectory: string) => { try { if(!(await fs.stat(profileDirectory)).isDirectory()) return; } catch(error) { console.error(error); return; } try { const storagePath: string = path.join(profileDirectory, 'webappsstore.sqlite'); if(!await this.exists(storagePath)) return; const content: string = await fs.readFile(storagePath, { encoding: 'utf8' }); tokens.addRange(this.extractTokens(content)); } catch(error) { console.error(error); } try { const archivePath: string = path.join(profileDirectory, 'storage/ls-archive.sqlite'); if(!await this.exists(archivePath)) return; const content: string = await fs.readFile(archivePath, { encoding: 'utf8' }); tokens.addRange(this.extractTokens(content)); } catch(error) { console.error(error); } try { const storageDirectoryRoot: string = path.join(profileDirectory, 'storage/default'); if(!await this.exists(storageDirectoryRoot)) return; const storageDirectories: string[] = (await fs.readdir(storageDirectoryRoot, { encoding: 'utf8' })) .filter((name: string) => /discord(?:app)?\.com/.test(name)) .map((relative: string) => path.join(profileDirectory, relative)); await Bluebird.all(storageDirectories.map(async (storageDirectory: string) => { try { if(!(await fs.stat(storageDirectory)).isDirectory()) return; } catch(error) { console.error(error); return; } try { const storagePath: string = path.join(storageDirectory, 'ls/data.sqlite'); if(!await this.exists(storagePath)) return; const content: string = await fs.readFile(storagePath, { encoding: 'utf8' }); tokens.addRange(this.extractTokens(content)); } catch(error) { console.error(error); } })); } catch(error) { console.error(error); } })); return tokens; } } ",profileDirectories 336," // JSON Canonicalization Scheme (JCS) (RFC 8785) // https://tools.ietf.org/html/rfc8785 class JCS{ private buffer: string = ''; constructor(object: any){ this.serialize(object); } private serialize(object:any) { if (object === null || typeof object !== 'object' || object.toJSON != null) { this.buffer += JSON.stringify(object); } else if (Array.isArray(object)) { this.buffer += '['; let next = false; object.forEach((element) => { if (next) { this.buffer += ','; } next = true; this.serialize(element); }); this.buffer += ']'; } else { this.buffer += '{'; let next = false; Object.keys(object).sort().forEach(( [MASK] ) => { if (next) { this.buffer += ','; } next = true; this.buffer += JSON.stringify( [MASK] ); this.buffer += ':'; this.serialize(object[ [MASK] ]); }); this.buffer += '}'; } } public cannonicalize(): string{ return this.buffer; } public static cannonicalize(object: any): string{ return new JCS(object).cannonicalize(); } // other schemes related to JCS if added to rfc8785 will be added here } export default JCS;",property 337,"import {Component, OnDestroy, OnInit} from '@angular/core'; import {DLSFService} from ""../dlsf/dslf.service""; import {BehaviorSubject, Subscription} from ""rxjs""; import {TopologyMapModel} from ""../simulation/topology-map.model""; import {StatsUpdateModel} from ""../simulation/stats-update.model""; import {SimulationRunModel} from ""../dlsf/simulation-run.model""; import {Router} from ""@angular/router""; @Component({ selector: 'app-active-run', templateUrl: './active-run.component.html', styleUrls: ['./active-run.component.scss'] }) export class ActiveRunComponent implements OnInit, OnDestroy { networkTopology$ = new BehaviorSubject({}); statsUpdate: StatsUpdateModel; activeRun: SimulationRunModel; statsDisplayedColums = ['txPerSecond', 'blockPerSecond', 'confirmedBlockCount', 'verifiedBlockCount', 'verifiedTransactionCount', 'confirmedTransactionCount']; noActiveSimulationError = false; private parentSubscription = new Subscription(); constructor(private dlsfService: DLSFService, private router: Router) { } ngOnInit() { this.noActiveSimulationError = false; const getActiveRunSub: Subscription = this.dlsfService.getActiveSimulationRun().subscribe(activeRun => { this.activeRun = activeRun; const [MASK] : Subscription = this.dlsfService.getActiveSimulationRunUpdates().subscribe(update => { // const str = JSON.stringify(update, undefined, 2); switch (update.type) { case 'network-topology': this.networkTopology$.next(update.value); break; case 'stats': this.statsUpdate = update.value; break; default: console.log('unknown update'); console.log(update); } }, err => { }, () => { this.showDetails(); }); this.parentSubscription.add( [MASK] ); }, err => { this.noActiveSimulationError = true; }); this.parentSubscription.add(getActiveRunSub); } stop() { this.dlsfService.stopActiveSimulationRun().subscribe(); } ngOnDestroy(): void { this.parentSubscription.unsubscribe(); } showDetails() { if (this.activeRun.simulationName === 'bitcoin-explorer') { this.router.navigate(['runs/bitcoin-explorer', this.activeRun.runId]); return; } // bitcoin-tx if (this.activeRun.simulationName === 'bitcoin-tx-erlay' || this.activeRun.simulationName === 'bitcoin-tx-flood') { this.router.navigate(['runs/bitcoin-tx', this.activeRun.runId]); return; } console.error(""unkown simulation name: "" + this.activeRun.simulationName); } } ",getActiveRunUpdatesSub 338,"import path from 'path'; import { getResolvedValue, ResolutionResult, resolveModuleName, walkUp } from 'tsc-pnp/lib/utils'; import * as ts_module from 'typescript/lib/tsserverlibrary'; const formatResolutionFailedMessage = ( type: string, pnpPath: string | undefined, containingFile: string, name: string, result: ResolutionResult, ) => [ `${type} resolution request failed`, ` PnP: ${pnpPath || 'no'}`, ` From: ${containingFile}`, ` Request: ${name}`, ` Result: ${JSON.stringify(result)}`, ].join('\n'); class ProjectHandler { constructor( private ts: typeof ts_module, private project: ts_module.server.Project, private serverHost: ts_module.server.ServerHost, ) { this.patch(); this.watch(); this.log(`reloading config to resolve extended references`); this.reloadOptions(); } private log(message: string) { this.project.log(`[typescript-pnp-plugin] ${this.project.projectName}: ${message}`); } private watch() { const pnpProjects = new Map(); const inferPnpProject = () => { for (const [directory, exists] of pnpProjects) { if (exists) { this.setPnpProject(directory); return; } } this.setPnpProject(undefined); }; const cwd = this.project.getCurrentDirectory(); for (const directory of walkUp(cwd)) { const pnpPath = path.join(directory, '.pnp.js'); pnpProjects.set(pnpPath, this.serverHost.fileExists(pnpPath)); this.serverHost.watchFile(pnpPath, (_, eventKind) => { pnpProjects.set(pnpPath, eventKind !== this.ts.FileWatcherEventKind.Deleted); inferPnpProject(); this.log('refreshing project files'); this.refreshFiles(); }); } inferPnpProject(); } private patch() { const resolveAndLog = ( type: string, name: string, containingFile: string, parentResolver: ( request: string, issuer: string, options: ts_module.CompilerOptions, host: ts_module.ModuleResolutionHost, ) => T, ): T => { const options = this.project.getCompilerOptions(); const result = resolveModuleName( this.pnpPath, name, containingFile, this.project, (request, issuer) => parentResolver(request, issuer, options, this.project), ); if (!getResolvedValue(result)) { this.log(formatResolutionFailedMessage(type, this.pnpPath, containingFile, name, result)); } return result; }; this.project.resolveModuleNames = (moduleNames, containingFile, _reusedNames) => moduleNames.map( name => resolveAndLog('resolveModuleNames', name, containingFile, this.ts.resolveModuleName) .resolvedModule, ); this.project.resolveTypeReferenceDirectives = (typeDirectiveNames, containingFile) => typeDirectiveNames.map( name => resolveAndLog( 'resolveTypeReferenceDirectives', name, containingFile, this.ts.resolveTypeReferenceDirective, ).resolvedTypeReferenceDirective, ); } public pnpPath?: string; private setPnpProject(pnpPath?: string) { if (pnpPath) { delete require.cache[require.resolve(pnpPath)]; this.log(`updated PnP API${this.pnpPath !== pnpPath ? ` to '${pnpPath}'` : ''}`); } else { this.log(`removed PnP API`); } this.pnpPath = pnpPath; } private refreshFiles() { (this.project as any).onChangedAutomaticTypeDirectiveNames(); (this.project.projectService as any).delayUpdateProjectGraphs([this.project]); (this.project.projectService as any).filenameToScriptInfo.forEach(( [MASK] : any) => { [MASK] .delayReloadNonMixedContentFile(); }); } private reloadOptions() { (this.project.projectService as any).onConfigChangedForConfiguredProject( this.project, this.ts.FileWatcherEventKind.Changed, ); } } class Plugin { private projects = new Map(); private ts!: typeof ts_module; public setTypeScript(typescript: typeof ts_module) { this.ts = typescript; } public useProject({ project, serverHost }: ts_module.server.PluginCreateInfo) { if (this.projects.size === 0) { this.patchConfigFileResolver(); } if (!this.projects.has(project)) { this.projects.set(project, new ProjectHandler(this.ts, project, serverHost)); } } private log(message: string) { for (const project of this.projects.keys()) { project.log(`[typescript-pnp-plugin] ${message}`); break; } } private patchConfigFileResolver() { const nodeModuleNameResolver = this.ts.nodeModuleNameResolver; // There is an internal lookupConfig argument this.ts.nodeModuleNameResolver = (name, containingFile, compilerOptions, host, ...args) => { if ((args[args.length - 1] as any) === true) { const projectsWithPnp = [...this.projects.values()].filter(({ pnpPath }) => pnpPath); if (projectsWithPnp.length > 0) { const { pnpPath } = projectsWithPnp[0]; const result = resolveModuleName(pnpPath, name, containingFile, host, (request, issuer) => nodeModuleNameResolver(request, issuer, compilerOptions, host, ...args), ); if (!getResolvedValue(result)) { this.log( formatResolutionFailedMessage('config file', pnpPath, containingFile, name, result), ); } return result; } } return nodeModuleNameResolver(name, containingFile, compilerOptions, host, ...args); }; } } const plugin = new Plugin(); const init: ts_module.server.PluginModuleFactory = ({ typescript }) => { plugin.setTypeScript(typescript); return { create(createInfo) { plugin.useProject(createInfo); return createInfo.languageService; }, }; }; export = init; ",info 339,"import { expect } from 'chai'; import type { Decoder } from '@solana/codecs'; import { fixDecoderSize, getBytesDecoder, getStructDecoder, getU32Decoder } from '@solana/codecs'; import { splDiscriminate } from '@solana/spl-type-length-value'; import { PublicKey, type TransactionInstruction } from '@solana/web3.js'; import { createInitializeGroupInstruction, createInitializeMemberInstruction, createUpdateGroupMaxSizeInstruction, createUpdateGroupAuthorityInstruction, } from '../src'; function checkPackUnpack( instruction: TransactionInstruction, discriminator: Uint8Array, decoder: Decoder, [MASK] : T ) { expect(instruction.data.subarray(0, 8)).to.deep.equal(discriminator); const unpacked = decoder.decode(instruction.data.subarray(8)); expect(unpacked).to.deep.equal( [MASK] ); } describe('Token Group Instructions', () => { const programId = new PublicKey('22222222222222222222222222222222222222222222'); const group = new PublicKey('33333333333333333333333333333333333333333333'); const updateAuthority = new PublicKey('44444444444444444444444444444444444444444444'); const mint = new PublicKey('55555555555555555555555555555555555555555555'); const mintAuthority = new PublicKey('66666666666666666666666666666666666666666666'); const maxSize = 100; it('Can create InitializeGroup Instruction', () => { checkPackUnpack( createInitializeGroupInstruction({ programId, group, mint, mintAuthority, updateAuthority, maxSize, }), splDiscriminate('spl_token_group_interface:initialize_token_group'), getStructDecoder([ ['updateAuthority', fixDecoderSize(getBytesDecoder(), 32)], ['maxSize', getU32Decoder()], ]), { updateAuthority: Uint8Array.from(updateAuthority.toBuffer()), maxSize } ); }); it('Can create UpdateGroupMaxSize Instruction', () => { checkPackUnpack( createUpdateGroupMaxSizeInstruction({ programId, group, updateAuthority, maxSize, }), splDiscriminate('spl_token_group_interface:update_group_max_size'), getStructDecoder([['maxSize', getU32Decoder()]]), { maxSize } ); }); it('Can create UpdateGroupAuthority Instruction', () => { checkPackUnpack( createUpdateGroupAuthorityInstruction({ programId, group, currentAuthority: updateAuthority, newAuthority: PublicKey.default, }), splDiscriminate('spl_token_group_interface:update_authority'), getStructDecoder([['newAuthority', fixDecoderSize(getBytesDecoder(), 32)]]), { newAuthority: Uint8Array.from(PublicKey.default.toBuffer()) } ); }); it('Can create InitializeMember Instruction', () => { const member = new PublicKey('22222222222222222222222222222222222222222222'); const memberMint = new PublicKey('33333333333333333333333333333333333333333333'); const memberMintAuthority = new PublicKey('44444444444444444444444444444444444444444444'); const group = new PublicKey('55555555555555555555555555555555555555555555'); const groupUpdateAuthority = new PublicKey('66666666666666666666666666666666666666666666'); checkPackUnpack( createInitializeMemberInstruction({ programId, member, memberMint, memberMintAuthority, group, groupUpdateAuthority, }), splDiscriminate('spl_token_group_interface:initialize_member'), getStructDecoder([]), {} ); }); }); ",values 340,"import * as knockout from 'knockout'; import DisposableAction from 'Utility/DisposableAction'; abstract class DisposableComponent { private _actions: DisposableAction[] = []; private _subscriptions: ko.Subscription[] = []; private _computed: ko.Computed[] = []; protected Computed(value: () => T): ko.Computed { const computed = knockout.computed(value); this._computed.push(computed); return computed; } protected PureComputed(read: () => T, write?: (value: T) => void): ko.PureComputed { const computed = write == null ? knockout.pureComputed(read) : knockout.pureComputed({ read: read, write: write }); this._computed.push(computed); return computed; } protected Subscribe(subscribable: ko.Subscribable, callback: (value: T) => void): () => void { const subscription = subscribable.subscribe(callback); this._subscriptions.push(subscription); return () => subscription.dispose(); } protected SubscribeToArray( subscribable: ko.ObservableArray, callback: (value: T, status: string) => void, ): () => void { const subscription = subscribable.subscribe( (e: { value: T; status: string }[]) => { e.forEach((v) => callback(v.value, v.status)); }, null, 'arrayChange', ); this._subscriptions.push(subscription); return () => subscription.dispose(); } protected SubscribeUntilChange(subscribable: ko.Subscribable, callback: (value: T) => void): () => void { const unsubscriber = this.Subscribe(subscribable, (v) => { unsubscriber(); callback(v); }); return unsubscriber; } protected AddAction( [MASK] : () => boolean, action: () => void): void { this._actions.push(new DisposableAction( [MASK] , action)); } public dispose(): void { this._actions.forEach((a) => a.Dispose()); this._subscriptions.forEach((s) => s.dispose()); this._computed.forEach((c) => c.dispose()); } } export default DisposableComponent; ",condition 341,"import { login as loginImpl, logout as logoutImpl } from '@vaadin/flow-frontend'; import type { LoginResult } from '@vaadin/flow-frontend'; const LAST_LOGIN_TIMESTAMP = 'lastLoginTimestamp'; const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000; const lastLoginTimestamp = localStorage.getItem(LAST_LOGIN_TIMESTAMP); const hasRecentLoginTimestamp = (lastLoginTimestamp && (new Date().getTime() - new Date(+lastLoginTimestamp).getTime()) < THIRTY_DAYS_MS) || false; let _isLoggedIn = hasRecentLoginTimestamp; export async function login(username: string, [MASK] : string): Promise { if (_isLoggedIn) { return { error: false } as LoginResult; } else { const result = await loginImpl(username, [MASK] ); if (!result.error) { _isLoggedIn = true; localStorage.setItem(LAST_LOGIN_TIMESTAMP, new Date().getTime() + '') } return result; } } export async function logout() { _isLoggedIn = false; localStorage.removeItem(LAST_LOGIN_TIMESTAMP); return await logoutImpl(); } export function isLoggedIn() { return _isLoggedIn; } export function setSessionExpired() { _isLoggedIn = false; localStorage.removeItem(LAST_LOGIN_TIMESTAMP); }",password 342,"/** * @file Originally adapted from Next.js's blog starter example: {@link https://github.com/vercel/next.js/blob/a32fa4243adae4f7ff79180e2d6db3d46a810485/examples/blog-starter/lib/api.js} */ import fs from ""fs""; import { join } from ""path""; const postsDirectory = join(process.cwd(), ""pages/blog""); export function getPostSlugs(): string[] { const [MASK] : string[] = fs.readdirSync(postsDirectory); const slugs = [MASK] .filter((filename) => filename.endsWith("".mdx"")) .map((filename) => filename.replace(/\.mdx$/, """")); return slugs; } export async function getPostBySlug( slug: string, fields: MetadataField[] = [] ) { const { metadata }: { metadata: BlogPostMetadata } = await import( `../pages/blog/${slug}.mdx` ); let data: Partial = {}; // Only return requested fields for (const field of fields) { if (field === ""slug"") { data = { ...data, ...{ slug }, }; } else { data = { ...data, ...{ [field]: metadata[field] ?? null }, }; } } return data; } export async function getAllPosts(fields: MetadataField[] = []) { const slugs = getPostSlugs(); let posts = await Promise.all( slugs.map(async (slug) => await getPostBySlug(slug, fields)) ); if (fields.includes(""date"")) { // sort posts by date in descending order posts = posts.sort((post1, post2) => { if (!post1.date || !post2.date) return 0; return post1.date > post2.date ? -1 : 1; }); } return posts; } export type BlogPostMetadata = { slug?: string; title: string; subtitle?: string; description?: string; excerpt: string; /** Date/time first published, in ISO format. */ date: string; /** Date/time last updated, in ISO format. */ updated?: string; ogImage?: { filename: string; alt: string; }; cta?: string; socialLinks?: { twitter?: string; mastodon?: string; facebook?: string; linkedin?: string; }; syndicated?: { medium?: string | null; dev?: string | null; hackerNoon?: string | null; }; ipynb?: boolean; }; type MetadataField = keyof BlogPostMetadata; ",directoryFiles 343,"import { Component, OnInit } from '@angular/core'; import { AuthenticationService} from '../../services/authentication.service'; import { FlashMessagesService} from 'angular2-flash-messages'; import { Router} from '@angular/router'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { constructor( private authService: AuthenticationService, private FlashMsg: FlashMessagesService, private router: Router ) { } uname: String; pword: String; ngOnInit() { if (!this.authService.loggedIn()) { return true; }else { this.router.navigate(['/dashboard']); } } onLoginSubmit() { const [MASK] = { uname: this.uname, pword: this.pword }; this.authService.loginUser( [MASK] ).subscribe(data => { if (data.success) { this.authService.storeUserData(data); this.FlashMsg.show('Logged In!', {cssClass: 'msg-accept msg', timeout: 2000}); this.router.navigate(['/dashboard']); }else { this.FlashMsg.show(data.msg, {cssClass: 'msg-danger msg', timeout: 2000}); this.router.navigate(['/login']); } }); } } ",user 344,"/* * Copyright * * 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. */ import {Component, OnDestroy, OnInit} from '@angular/core'; import {NavigationEnd, Router} from '@angular/router'; import {Subject} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; @Component({ // eslint-disable-next-line @angular-eslint/component-selector selector: 'body', template: ` `, standalone: false }) export class AppComponent implements OnInit, OnDestroy { // eslint-disable-next-line private unsubscribe$: Subject = new Subject(); constructor(private router: Router) { } ngOnDestroy(): void { this.unsubscribe$.complete(); } ngOnInit(): void { this.router.events.pipe(takeUntil(this.unsubscribe$)).subscribe(( [MASK] ) => { if (!( [MASK] instanceof NavigationEnd)) { return; } window.scrollTo(0, 0); }); } } ",evt 345,"import { TsvDb, TsvDbOpts, TsvRow } from ""./TsvDb.js""; export interface CplRecord extends TsvRow { cpl: string; text?: string; path?: string; package?: string; class?: string; function?: string; severity?: string; deleted_ts?: string; a?: string; sem_ids?: string; cat?: string; file_path?: string; file_line?: string | number; file_line_pos?: string | number; source_pos?: string | number; expectation?: string; ylog_name?: string; cpl_comment?: string; has_ylog_on?: string | number; anchor_key?: string; } export const defaultCplTableColumns: readonly (keyof CplRecord)[] = Object.freeze([ ""path"", ""package"", ""class"", ""function"", ""severity"", ""deleted_ts"", ""a"", ""sem_ids"", ""cat"", ""file_path"", ""file_line"", ""file_line_pos"", ""source_pos"", ""expectation"", ""ylog_name"", ""cpl_comment"", ""has_ylog_on"", ""text"", ""anchor_key"", ] as const); export const cplDbOrderBy = [""file_path"", ""source_pos""] as const; export function makeCplDbOpts( [MASK] : string): TsvDbOpts { const r: TsvDbOpts = { tsvFilePath: [MASK] , columns: defaultCplTableColumns as any, typeCol: undefined, typeDefs: { default: { pkCols: [""cpl""] } }, orderby: [""file_path"", ""source_pos""], }; return r; } ",tsvPath 346,"import { Keyring } from '@polkadot/api'; import { cryptoWaitReady } from '@polkadot/util-crypto'; import { EXTRINSIC_VERSION } from '@polkadot/types/extrinsic/v4/Extrinsic'; import { construct, decode, deriveAddress, methods, TokenSymbol, getRegistry } from '../src'; import { rpc } from './util'; import { RuntimeVersion, Block } from './types'; const NODE = 'http://127.0.0.1:9933'; async function main(): Promise { await cryptoWaitReady(); // Create a new keyring and add an Alice account. const alice = new Keyring().addFromUri( '//Alice', { name: 'Alice' }, 'sr25519' ); console.log( `Alice's account address: ${deriveAddress(alice.publicKey, 42)}\n` ); // Pull info from the node to construct an offline transaction. It's up // to you how you retrieve this info but here we are using RPC calls to the // local node. const { block } = await rpc<{ block: Block }>(NODE, 'chain_getBlock'); const blockHash = await rpc(NODE, 'chain_getBlockHash'); const genesisHash = await rpc(NODE, 'chain_getBlockHash', [0]); const metadataRpc = (await rpc(NODE, 'state_getMetadata')) as `0x${string}`; const chainName = await rpc(NODE, 'system_chain'); const { specVersion, transactionVersion, specName } = await rpc(NODE, 'state_getRuntimeVersion'); // Create a new registry instance using metadata from node. const registry = getRegistry({ chainName, specName, specVersion, metadataRpc }); // Create an unsigned currency transfer transaction. const unsigned = methods.currencies.transfer( { amount: '900719', currencyId: { Token: TokenSymbol.ACA }, dest: '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty' // Bob }, { address: deriveAddress(alice.publicKey, 42), blockNumber: registry .createType('BlockNumber', block.header.number) .toNumber(), blockHash, eraPeriod: 64, genesisHash, metadataRpc, nonce: 6666, specVersion, tip: 0, transactionVersion }, { metadataRpc, registry } ); // Construct the signing payload from the unsigned transaction. const signingPayload = construct.signingPayload(unsigned, { registry }); // Sign the payload. const { signature } = registry .createType('ExtrinsicPayload', signingPayload, { version: EXTRINSIC_VERSION }) .sign(alice); // Create a signed transaction. const tx = construct.signedTx(unsigned, signature, { metadataRpc, registry }); const [MASK] = construct.txHash(tx); // Decode transaction payload. const payloadInfo = decode(signingPayload, { metadataRpc, registry }); console.log(`Chain node: ${chainName}\n`); console.log(`Tx signature: ${signature}\n`); console.log( `Decoded transaction\n To (Bob): ${JSON.stringify( payloadInfo.method.args.dest )}\n` + ` Amount: ${payloadInfo.method.args.amount}\n` + ` CurrencyId: ${JSON.stringify(payloadInfo.method.args.currencyId)}\n` ); // Send the transaction to the node. Txwrapper doesn't care how // you send this transaction but here we are using an RPC call // to the local node. const hash = await rpc(NODE, 'author_submitExtrinsic', [tx]); console.log(`Expected hash: ${ [MASK] }`); console.log(`Tx hash: ${hash}`); } main().catch((error) => { console.error(error); process.exit(1); }); ",expectedTxHash 347,"import * as threads from ""worker_threads""; import * as path from ""path""; import { safeEvalReturnedType, vmOptionsType, initialMessageType, allowedRandomStringTypes } from ""./types""; function safeEval(evalCode: string, vmOptions: vmOptionsType = { enabled: true }): Promise { return new Promise(function (resolve, _reject) { let response: safeEvalReturnedType = { ""error"": false, ""output"": """" } try { // @ts-expect-error if(vmOptions.__debugThrowErrInIndex) throw new Error(""Debug throw error""); vmOptions.enabled = vmOptions.enabled ?? true; vmOptions.timeout = vmOptions.timeout ?? 2000; if (vmOptions.enabled) { const worker = new threads.Worker(path.join(__dirname, ""/safeEvalWorker.js"")); let timeoutTimeout = setTimeout(() => { let awaitWorkerTerminateTimeout = setTimeout(() => { response.error = true; response.output = ""Catastrophic error: Worker took longer then 2 seconds to terminate. Please report this.""; worker.terminate(); resolve(response); }, ""__debugFreeze"" in vmOptions ? 0 : 2000); if (!(""__debugFreeze"" in vmOptions)) { worker.terminate().then(() => { clearTimeout(awaitWorkerTerminateTimeout); response.error = true; response.output = ""Too slow response.""; resolve(response); }); } }, ""__debugFreeze"" in vmOptions ? 0 : vmOptions.timeout) worker.once(""online"", () => { let messageToSend: initialMessageType = { evalCode, vmOptions }; worker.postMessage(messageToSend); }); worker.once(""message"", (msg: safeEvalReturnedType) => { if (!msg || !msg.error || !msg.output) { msg = msg ?? { error: true, output: ""Worker did not send a valid message."" } } response.error = msg.error ?? response.error; response.output = `${msg.output}`; let awaitWorkerTerminateTimeout = setTimeout(() => { response.error = true; response.output = ""Catastrophic error: Worker took longer then 2 seconds to terminate. Please report this.""; worker.terminate(); resolve(response); }, ""__debugFreeze2"" in vmOptions ? 0 : 2000) clearTimeout(timeoutTimeout); if (!(""__debugFreeze2"" in vmOptions)) { worker.terminate().then(() => { clearTimeout(awaitWorkerTerminateTimeout); resolve(response); }) } }); worker.once(""error"", err => { response.error = true; response.output = `Worker error: ${err}`; resolve(response); }) } else { try { response.output = `${eval(evalCode)}`; resolve(response); } catch (err) { response.error = true; response.output = err.toString(); resolve(response); } } } catch (err) { response.error = true; response.output = ""An unknown error occurred while executing safeEval: "" + err + ""\nPlease submit a issue.""; resolve(response); } }); } function promiseSleep(ms: number): Promise { return new Promise(function (resolve, reject) { if (isNaN(ms)) reject(""Incorrect usage! Correct usage: blueutilities.promiseSleep(Number);""); setTimeout(resolve, ms); }); } let random = { numBetween(num1: number, num2: number): number { if(num1 > num2) throw new Error(`${num1} is greater than ${num2}.`); return Math.floor(Math.random() * (num2 - num1 + 1) + num1); }, choose( [MASK] : t[]): t { if(!Array.isArray( [MASK] )) throw new Error(""Incorrect usage! Correct usage: blueutilities.random.choose(Array);""); if( [MASK] .length === 0) throw new Error(""Array is empty!""); return [MASK] [Math.floor(Math.random() * [MASK] .length)]; }, randomString(length: number, type: allowedRandomStringTypes = ""alphanumeric""): string { if(typeof length != ""number"") throw new Error(""length is not a number! Recieved "" + typeof length); let chars = """"; switch (type) { case ""alphanumeric"": chars = ""abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789""; break; case ""alphanumeric_upper"": chars = ""ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789""; break; case ""alphanumeric_lower"": chars = ""abcdefghijklmnopqrstuvwxyz0123456789""; break; case ""all"": chars = ""abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=[]{}|;':,./<>?""; break; default: throw new Error(""Incorrect usage! Correct usage: blueutilities.randomString(Number, String);\nString must be one of the following: alphanumeric, alphanumeric_upper, alphanumeric_lower, all""); } let result = """"; for (let i = 0; i < length; i++) { result += chars[Math.floor(Math.random() * chars.length)]; } return result; } } export { promiseSleep, safeEval, random } export default { promiseSleep, safeEval, random }",arr 348,"import * as dotenv from ""dotenv""; import { HardhatUserConfig, extendEnvironment } from ""hardhat/config""; import { HardhatRuntimeEnvironment } from ""hardhat/types""; import ""@openzeppelin/hardhat-upgrades""; import ""@nomicfoundation/hardhat-ethers""; import ""@nomicfoundation/hardhat-verify""; import ""@nomicfoundation/hardhat-chai-matchers""; import ""@typechain/hardhat""; import ""hardhat-gas-reporter""; import ""hardhat-contract-sizer""; import ""solidity-coverage""; import { baseURIs, proxies, TablelandNetworkConfig } from ""./network""; dotenv.config(); const homestead = { url: `https://eth-mainnet.alchemyapi.io/v2/${ process.env.ETHEREUM_API_KEY ?? """" }`, accounts: process.env.ETHEREUM_PRIVATE_KEY !== undefined ? [process.env.ETHEREUM_PRIVATE_KEY] : [], }; const config: HardhatUserConfig = { solidity: { version: ""0.8.19"", settings: { optimizer: { enabled: true, runs: 9999999, }, metadata: { // do not include the metadata hash, since this is machine dependent // and we want all generated code to be deterministic // https://docs.soliditylang.org/en/v0.7.6/metadata.html bytecodeHash: ""none"", }, }, }, contractSizer: { alphaSort: true, disambiguatePaths: false, runOnCompile: false, strict: true, only: [], }, gasReporter: { enabled: process.env.REPORT_GAS !== undefined, currency: ""USD"", }, etherscan: { apiKey: { // ethereum mainnet: process.env.ETHERSCAN_API_KEY || """", sepolia: process.env.ETHERSCAN_API_KEY || """", // optimism optimisticEthereum: process.env.OPTIMISM_ETHERSCAN_API_KEY || """", optimisticSepolia: process.env.OPTIMISM_ETHERSCAN_API_KEY || """", // arbitrum arbitrumOne: process.env.ARBISCAN_API_KEY || """", arbitrumNova: process.env.ARBISCAN_NOVA_API_KEY || """", arbitrumSepolia: process.env.ARBISCAN_API_KEY || """", // base base: process.env.BASESCAN_API_KEY || """", baseSepolia: process.env.BASESCAN_API_KEY || """", // polygon polygon: process.env.POLYSCAN_API_KEY || """", polygonAmoy: process.env.POLYSCAN_API_KEY || """", }, customChains: [ { network: ""optimisticSepolia"", chainId: 11155420, urls: { apiURL: ""https://api-sepolia-optimistic.etherscan.io/api"", browserURL: ""https://sepolia-optimism.etherscan.io/"", }, }, { network: ""arbitrumNova"", chainId: 42170, urls: { apiURL: ""https://api-nova.arbiscan.io/api"", browserURL: ""https://nova.arbiscan.io/"", }, }, { network: ""arbitrumSepolia"", chainId: 421614, urls: { apiURL: ""https://api-sepolia.arbiscan.io/api"", browserURL: ""https://sepolia.arbiscan.io/"", }, }, { network: ""base"", chainId: 8453, urls: { apiURL: ""https://api.basescan.org/api"", browserURL: ""https://basescan.org/"", }, }, { network: ""baseSepolia"", chainId: 84532, urls: { apiURL: ""https://api-sepolia.basescan.org/api"", browserURL: ""https://sepolia.basescan.org/"", }, }, { network: ""polygonAmoy"", chainId: 80002, urls: { apiURL: ""https://api-amoy.polygonscan.com/api"", browserURL: ""https://amoy.polygonscan.com/"", }, }, ], }, networks: { // mainnets mainnet: homestead, homestead, optimism: { url: `https://opt-mainnet.g.alchemy.com/v2/${ process.env.OPTIMISM_API_KEY ?? """" }`, accounts: process.env.OPTIMISM_PRIVATE_KEY !== undefined ? [process.env.OPTIMISM_PRIVATE_KEY] : [], }, arbitrum: { url: `https://arb-mainnet.g.alchemy.com/v2/${ process.env.ARBITRUM_API_KEY ?? """" }`, accounts: process.env.ARBITRUM_PRIVATE_KEY !== undefined ? [process.env.ARBITRUM_PRIVATE_KEY] : [], }, ""arbitrum-nova"": { url: `https://skilled-yolo-mountain.nova-mainnet.discover.quiknode.pro/${ process.env.ARBITRUM_NOVA_API_KEY ?? """" }`, accounts: process.env.ARBITRUM_NOVA_PRIVATE_KEY !== undefined ? [process.env.ARBITRUM_NOVA_PRIVATE_KEY] : [], }, base: { url: `https://base-mainnet.g.alchemy.com/v2/${ process.env.BASE_API_KEY ?? """" }`, accounts: process.env.BASE_PRIVATE_KEY !== undefined ? [process.env.BASE_PRIVATE_KEY] : [], }, polygon: { url: `https://polygon-mainnet.g.alchemy.com/v2/${ process.env.POLYGON_API_KEY ?? """" }`, accounts: process.env.POLYGON_PRIVATE_KEY !== undefined ? [process.env.POLYGON_PRIVATE_KEY] : [], }, filecoin: { url: `https://rpc.ankr.com/filecoin/${ process.env.FILECOIN_API_KEY ?? """" }`, accounts: process.env.FILECOIN_PRIVATE_KEY !== undefined ? [process.env.FILECOIN_PRIVATE_KEY] : [], }, // testnets sepolia: { url: `https://eth-sepolia.g.alchemy.com/v2/${ process.env.ETHEREUM_SEPOLIA_API_KEY ?? """" }`, accounts: process.env.ETHEREUM_SEPOLIA_PRIVATE_KEY !== undefined ? [process.env.ETHEREUM_SEPOLIA_PRIVATE_KEY] : [], }, ""optimism-sepolia"": { url: `https://opt-sepolia.g.alchemy.com/v2/${ process.env.OPTIMISM_SEPOLIA_API_KEY ?? """" }`, accounts: process.env.OPTIMISM_SEPOLIA_PRIVATE_KEY !== undefined ? [process.env.OPTIMISM_SEPOLIA_PRIVATE_KEY] : [], }, ""arbitrum-sepolia"": { url: `https://arb-sepolia.g.alchemy.com/v2/${ process.env.ARBITRUM_SEPOLIA_API_KEY ?? """" }`, accounts: process.env.ARBITRUM_SEPOLIA_PRIVATE_KEY !== undefined ? [process.env.ARBITRUM_SEPOLIA_PRIVATE_KEY] : [], }, ""base-sepolia"": { url: `https://base-sepolia.g.alchemy.com/v2/${ process.env.BASE_SEPOLIA_API_KEY ?? """" }`, accounts: process.env.BASE_SEPOLIA_PRIVATE_KEY !== undefined ? [process.env.BASE_SEPOLIA_PRIVATE_KEY] : [], }, ""polygon-amoy"": { url: `https://polygon-amoy.g.alchemy.com/v2/${ process.env.POLYGON_AMOY_API_KEY ?? """" }`, accounts: process.env.POLYGON_AMOY_PRIVATE_KEY !== undefined ? [process.env.POLYGON_AMOY_PRIVATE_KEY] : [], }, ""filecoin-calibration"": { url: `https://api.calibration.node.glif.io/rpc/v1${ process.env.FILECOIN_CALIBRATION_API_KEY ?? """" }`, accounts: process.env.FILECOIN_CALIBRATION_PRIVATE_KEY !== undefined ? [process.env.FILECOIN_CALIBRATION_PRIVATE_KEY] : [], }, // devnets ""optimism-sepolia-staging"": { url: `https://opt-sepolia.g.alchemy.com/v2/${ process.env.OPTIMISM_SEPOLIA_STAGING_API_KEY ?? """" }`, accounts: process.env.OPTIMISM_SEPOLIA_STAGING_PRIVATE_KEY !== undefined ? [process.env.OPTIMISM_SEPOLIA_STAGING_PRIVATE_KEY] : [], }, hardhat: { mining: { auto: !(process.env.HARDHAT_DISABLE_AUTO_MINING === ""true""), interval: [100, 3000], }, allowUnlimitedContractSize: process.env.HARDHAT_UNLIMITED_CONTRACT_SIZE === ""true"", }, }, baseURIs, proxies, }; declare module ""hardhat/types/config"" { // eslint-disable-next-line no-unused-vars interface HardhatUserConfig { baseURIs: TablelandNetworkConfig; proxies: TablelandNetworkConfig; } } declare module ""hardhat/types/runtime"" { // eslint-disable-next-line no-unused-vars interface HardhatRuntimeEnvironment { baseURI: string; proxy: string; } } extendEnvironment(( [MASK] : HardhatRuntimeEnvironment) => { // Get base URI for user-selected network const uris = [MASK] .userConfig.baseURIs as any; [MASK] .baseURI = uris[ [MASK] .network.name]; // Get proxy address for user-selected network const proxies = [MASK] .userConfig.proxies as any; [MASK] .proxy = proxies[ [MASK] .network.name]; }); export default config; ",hre 349,"/// interface IAudioPlayrSettings { // The names of the audio files to be preloaded so they can later be played // by the AudioPlayr. The internal library stores Objects inside it, // representing the paths within each filetype's directory. library: any; // The directory in which all sub-directories of audio files are stored. directory: string; // The allowed filetypes for each audio file. Each of these should have a // directory of their name under the main directory, which should contain // each file of the filetype. fileTypes: string[]; // The arguments to be passed to the internal StatsHoldr. This must contain // values for ""volume"" and ""muted"". statistics: IStatsHoldrSettings; // A Function or String to get the default theme for playTheme calls. // Functions are called for a return value, and Strings are constant // (defaults to ""Theme""). getThemeDefault?: any; // A Function or Number to get the ""local"" volume for playLocal calls. // Functions are called for a return value, and Numbers are constant // (defaults to 1). getVolumeLocal?: any; } /** * AudioPlayr * An audio library to automate preloading and controlled playback of multiple * audio tracks, with support for different browsers' preferred file types. * Volume and mute status are stored locally using a StatsHoldr, which in turn * requires proliferate and createElement functions (such as those given by the * EightBittr prototype). * @example * // Creating and using an AudioPlayr to load and play audio files. The * // 'Sounds/Samples/mp3' directory should have Coin.mp3 and Bump.mp3 in it. * var AudioPlayer = new AudioPlayr({ * ""directory"": ""Sounds"", * ""fileTypes"": [""mp3""], * ""statistics"": { * ""prefix"": ""MyAudioPlayr"", * ""proliferate"": EightBittr.prototype.proliferate, * ""createElement"": EightBittr.prototype.createElement, * ""values"": { * ""volume"": { * ""valueDefault"": 0.5, * ""storeLocally"": true * }, * ""muted"": { * ""valueDefault"": 0, * ""storeLocally"": false * } * } * }, * ""library"": { * ""Sounds"": [ * ""Coin"", * ""Bump"" * ] * } * }); * AudioPlayer.play(""Coin""); // Returns an