Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Убраны window #157

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,14 @@ export default [
}),
typescript({ outDir: 'esm', declaration: false, declarationMap: false, module: 'esnext' }),
...common.plugins,
copy({
targets: [
{
src: 'src/assistantSdk/voice/recognizers/asr/*.d.ts',
dest: 'dist/assistantSdk/voice/recognizers/asr',
},
],
}),
],
},
{
Expand Down
7 changes: 3 additions & 4 deletions src/assistantSdk/assistant.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
/* eslint-disable camelcase */
import { ActionCommand } from '@salutejs/scenario';
import Long from 'long';

import { createNanoEvents } from '../nanoevents';
import {
Expand Down Expand Up @@ -70,7 +69,7 @@ const promiseTimeout = <T>(promise: Promise<T>, timeout: number): Promise<T> =>
return Promise.race([
promise.then((v) => {
if (timeoutId) {
window.clearTimeout(timeoutId);
clearTimeout(timeoutId);
}
return v;
}),
Expand Down Expand Up @@ -314,7 +313,7 @@ export const createAssistant = ({

/** отправляет ответ на запрос доступа к местоположению и пр. меты */
const sendMetaForPermissionRequest = async (
requestMessageId: number | Long,
requestMessageId: number,
appInfo: AppInfo,
items: PermissionType[],
) => {
Expand Down Expand Up @@ -405,7 +404,7 @@ export const createAssistant = ({
const { command } = items[i];

if (typeof command !== 'undefined') {
window.setTimeout(() => emit('command', command));
setTimeout(() => emit('command', command));

if (command.type === 'start_music_recognition') {
voice.shazam();
Expand Down
10 changes: 4 additions & 6 deletions src/assistantSdk/client/client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import Long from 'long';

import { createNanoEvents } from '../../nanoevents';
import {
SystemMessageDataType,
Expand Down Expand Up @@ -35,7 +33,7 @@ export const createClient = (
const { on, emit } = createNanoEvents<ClientEvents>();

/** ждет ответ бека и возвращает данные из этого ответа */
const waitForAnswer = (messageId: number | Long): Promise<SystemMessageDataType> =>
const waitForAnswer = (messageId: number): Promise<SystemMessageDataType> =>
new Promise((resolve) => {
const off = on('systemMessage', (systemMessageData, originalMessage) => {
if (
Expand All @@ -50,7 +48,7 @@ export const createClient = (
});

/** отправляет произвольный systemMessage, не подкладывает мету */
const sendData = (data: Record<string, unknown>, messageName = '', meta?: MetaStringified): number | Long => {
const sendData = (data: Record<string, unknown>, messageName = '', meta?: MetaStringified): number => {
const messageId = protocol.getMessageId();

protocol.sendSystemMessage(
Expand Down Expand Up @@ -109,7 +107,7 @@ export const createClient = (
appInfo: AppInfo,
messageName = 'SERVER_ACTION',
mode?: AssistantServerActionMode,
): Promise<number | Long | undefined> => {
): Promise<number | undefined> => {
const messageId = protocol.getMessageId();

// мету и server_action отправляем в одном systemMessage
Expand Down Expand Up @@ -144,7 +142,7 @@ export const createClient = (
isSsml = false,
shouldSendDisableDubbing?: boolean,
additionalMeta?: AdditionalMeta,
): Promise<number | Long | undefined> => {
): Promise<number | undefined> => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А почему long убрал? из protobuf кажется он приходит

if (text.trim() === '') {
return undefined;
}
Expand Down
11 changes: 7 additions & 4 deletions src/assistantSdk/client/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,11 +275,11 @@ export const createProtocol = (

status = 'connected';

window.clearTimeout(clearReadyTimer);
clearTimeout(clearReadyTimer);

/// считаем коннект = ready, если по истечении таймаута сокет не был разорван
/// т.к бек может разрывать сокет, если с settings что-то не так
clearReadyTimer = window.setTimeout(() => {
clearReadyTimer = setTimeout(() => {
if (status !== 'connected') {
return;
}
Expand All @@ -294,7 +294,7 @@ export const createProtocol = (
status = 'ready';

emit('ready');
}, 250);
}, 250) as unknown as number;

logger?.({ type: 'init', params: { ...configuration, ...currentSettings } });
}),
Expand Down Expand Up @@ -343,7 +343,10 @@ export const createProtocol = (
},
init: () => {
// в отличии от reconnect не обрывает коннект если он в порядке
if (status === 'ready' && window.navigator.onLine) {
if (
(status === 'ready' && typeof window !== 'undefined' && window.navigator.onLine) ||
typeof window === 'undefined'
) {
return Promise.resolve();
}

Expand Down
23 changes: 14 additions & 9 deletions src/assistantSdk/client/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,24 @@ export const createTransport = ({ createWS = defaultWSCreator, checkCertUrl }: C
const { on, emit } = createNanoEvents<TransportEvents>();

let hasCert = !checkCertUrl;
let retryTimeoutId = -1;
let retryTimeoutId: unknown = -1;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

почему не number

let retries = 0;
let status: 'closed' | 'closing' | 'connecting' | 'open' = 'closed';
let webSocket: WebSocket;
let stopped = true;

const checkCert = (checkUrl: string) =>
new Promise<boolean>((resolve) => {
const checkCert = (checkUrl: string) => {
if (typeof window === 'undefined') {
return Promise.resolve(true);
}

return new Promise<boolean>((resolve) => {
window
.fetch(checkUrl)
.then(() => resolve(true))
.catch(() => resolve(false));
});
};

const close = () => {
stopped = true;
Expand All @@ -46,7 +51,7 @@ export const createTransport = ({ createWS = defaultWSCreator, checkCertUrl }: C
status = 'connecting';
emit('connecting');

if (!hasCert && window.navigator.onLine) {
if ((!hasCert && typeof window !== 'undefined' && window.navigator.onLine) || typeof window === 'undefined') {
const okay = await checkCert(checkCertUrl!);

if (!okay) {
Expand All @@ -70,7 +75,7 @@ export const createTransport = ({ createWS = defaultWSCreator, checkCertUrl }: C
return;
}

window.clearTimeout(retryTimeoutId);
clearTimeout(retryTimeoutId as number);

retries = 0;

Expand All @@ -90,10 +95,10 @@ export const createTransport = ({ createWS = defaultWSCreator, checkCertUrl }: C

// пробуем переподключаться, если возникла ошибка при коннекте
if (!webSocket || (webSocket.readyState === 3 && !stopped)) {
window.clearTimeout(retryTimeoutId);
clearTimeout(retryTimeoutId as number);

if (retries < 2) {
retryTimeoutId = window.setTimeout(() => {
retryTimeoutId = setTimeout(() => {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
open(url);

Expand Down Expand Up @@ -129,7 +134,7 @@ export const createTransport = ({ createWS = defaultWSCreator, checkCertUrl }: C
return;
}

window.setTimeout(() => reconnect(url));
setTimeout(() => reconnect(url));

close();
};
Expand All @@ -141,7 +146,7 @@ export const createTransport = ({ createWS = defaultWSCreator, checkCertUrl }: C
return {
close,
get isOnline() {
return window.navigator.onLine;
return (typeof window !== 'undefined' && window.navigator.onLine) || typeof window === 'undefined';
},
on,
open,
Expand Down
6 changes: 2 additions & 4 deletions src/assistantSdk/meta.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
/* eslint-disable camelcase */
import Long from 'long';

import { AppInfo, Meta, PermissionStatus, PermissionType, SystemMessageDataType } from '../typings';

export type Permission = Record<PermissionType, PermissionStatus>;
Expand All @@ -13,7 +11,7 @@ export type CommandResponse = Required<Pick<SystemMessageDataType, 'app_info'>>
};
server_action: {
action_id: 'command_response';
request_message_id: number | Long;
request_message_id: number;
command_response: {
request_permissions?: {
permissions: Array<{
Expand Down Expand Up @@ -56,7 +54,7 @@ export const getTime = (): Meta['time'] => ({
});

export const getAnswerForRequestPermissions = async (
requestMessageId: number | Long,
requestMessageId: number,
appInfo: AppInfo,
items: PermissionType[],
): Promise<CommandResponse> => {
Expand Down
13 changes: 7 additions & 6 deletions src/assistantSdk/voice/audioContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,17 @@ export const isAudioSupported = typeof window !== 'undefined' && (window.AudioCo
* @returns AudioContext
*/
export const createAudioContext = (options?: AudioContextOptions): AudioContext => {
if (window.AudioContext) {
return new AudioContext(options);
if (!isAudioSupported) {
throw new Error('Audio not supported');
}

if (window.webkitAudioContext) {
// eslint-disable-next-line new-cap
return new window.webkitAudioContext();
if (window.AudioContext) {
return new AudioContext(options);
}

throw new Error('Audio not supported');
// @ts-ignore
// eslint-disable-next-line new-cap
return new window.webkitAudioContext();
};

interface ContextEvents {
Expand Down
2 changes: 1 addition & 1 deletion src/assistantSdk/voice/listener/navigatorAudioProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export const createNavigatorAudioProvider = (cb: (buffer: ArrayBuffer, last: boo
return createAudioRecorder(stream, cb);
})
.catch((err) => {
if (window.location.protocol === 'http:') {
if (typeof window !== 'undefined' && window.location.protocol === 'http:') {
throw new Error('Audio is supported only on a secure connection');
}

Expand Down
2 changes: 1 addition & 1 deletion src/assistantSdk/voice/voice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ export const createVoice = (

// гипотезы распознавания речи
subscriptions.push(
speechRecognizer.on('hypotesis', (text: string, isLast: boolean, mid: number | Long) => {
speechRecognizer.on('hypotesis', (text: string, isLast: boolean, mid: number) => {
emit({
asr: {
text: listener.status === 'listen' && !settings.current.disableListening ? text : '',
Expand Down
5 changes: 2 additions & 3 deletions src/typings.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import Long from 'long';
import {
Action,
ActionCommand,
Expand Down Expand Up @@ -484,7 +483,7 @@ export type SystemMessageDataType = {
};

export interface OriginalMessageType {
messageId: number | Long;
messageId: number;
last: number;
messageName: string;
token?: string | null;
Expand All @@ -503,7 +502,7 @@ export interface OriginalMessageType {
systemMessage?: {
data?: string | null;
} | null;
timestamp?: number | Long | null;
timestamp?: number | null;
meta?: { [k: string]: string } | null;
}

Expand Down
Loading