initial commit

This commit is contained in:
2025-07-04 14:40:10 +09:00
commit cff0d5d1c5
16 changed files with 4824 additions and 0 deletions

145
.gitignore vendored Normal file
View File

@@ -0,0 +1,145 @@
# Created by https://www.toptal.com/developers/gitignore/api/node
# Edit at https://www.toptal.com/developers/gitignore?templates=node
### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
### Node Patch ###
# Serverless Webpack directories
.webpack/
# Optional stylelint cache
# SvelteKit build / generate output
.svelte-kit
# End of https://www.toptal.com/developers/gitignore/api/node

1
.prettierrc Normal file
View File

@@ -0,0 +1 @@
{}

11
eslint.config.js Normal file
View File

@@ -0,0 +1,11 @@
import js from "@eslint/js";
import globals from "globals";
import tseslint from "typescript-eslint";
import { defineConfig } from "eslint/config";
export default defineConfig([
{ files: ["**/*.{js,mjs,cjs,ts,mts,cts}"], plugins: { js }, extends: ["js/recommended"] },
{ files: ["**/*.{js,mjs,cjs,ts,mts,cts}"], languageOptions: { globals: globals.browser } },
tseslint.configs.recommended,
]);

20
jest.config.js Normal file
View File

@@ -0,0 +1,20 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
export default {
preset: "ts-jest/presets/default-esm", // important for ESM
testEnvironment: "node",
testPathIgnorePatterns: ["/node_modules/", "/dist/"],
globals: {
"ts-jest": {
useESM: true, // enable ESM in ts-jest
tsconfig: "tsconfig.json",
},
},
extensionsToTreatAsEsm: [".ts"], // treat TypeScript files as ESM
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.js$": "$1", // fix import extensions in ESM
},
transform: {
"^.+\\.tsx?$": ["ts-jest", { useESM: true }],
},
testTimeout: 50000,
};

38
package.json Normal file
View File

@@ -0,0 +1,38 @@
{
"name": "tap-sdk-js",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "tsc",
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
},
"keywords": [],
"author": "minco",
"license": "ISC",
"packageManager": "pnpm@10.11.0",
"devDependencies": {
"@eslint/js": "^9.30.1",
"@types/got": "^9.6.12",
"@types/jest": "^30.0.0",
"@types/ws": "^8.18.1",
"eslint": "^9.30.1",
"globals": "^16.3.0",
"prettier": "3.6.2",
"ts-jest": "^29.4.0",
"ts-node": "^10.9.2",
"typescript": "^5.8.3",
"typescript-eslint": "^8.35.1"
},
"dependencies": {
"eventemitter3": "^5.0.1",
"got": "^14.4.7",
"jest": "^30.0.4",
"ws": "^8.18.3",
"zod": "^3.25.72"
},
"type": "module",
"engines": {
"node": ">=18"
}
}

4179
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

85
src/api/websocket.ts Normal file
View File

@@ -0,0 +1,85 @@
import { WebSocket } from "ws";
import { EventEmitter } from "eventemitter3";
export type WSEvent = {
open: () => any;
close: () => any;
error: (err: Error) => any;
connectionError: (err: Error) => any;
message: (content: string) => any;
};
export type WSState = {
socket: WebSocket | null;
connected: boolean;
retries: number;
emitter: EventEmitter<WSEvent>;
};
export type WSConfig = {
url: string;
backoffBaseMs: number;
};
export function createWebSocketManager(config: WSConfig) {
const backoffDelay = (retries: number, baseMs: number) =>
Math.min(5000, baseMs * 2 ** retries);
const state: WSState = {
socket: null,
connected: false,
retries: 0,
emitter: new EventEmitter(),
};
function connect() {
return new Promise<void>((resolve) => {
const socket = new WebSocket(config.url);
socket.on("open", () => {
state.socket = socket;
state.connected = true;
state.retries = 0;
state.emitter.emit("open");
resolve();
});
socket.on("message", (msg) => {
state.emitter.emit("message", msg.toString());
});
socket.on("error", (err) => {
if (state.connected) state.emitter.emit("error", err);
else state.emitter.emit("connectionError", err);
});
socket.on("close", () => {
state.emitter.emit("close");
state.connected = false;
});
});
}
function retry() {
setTimeout(
() => {
connect().catch(() => retry());
state.retries++;
},
backoffDelay(state.retries, config.backoffBaseMs),
);
}
async function start() {
await connect().catch(() => retry());
}
function send(message: string) {
if (state.socket) state.socket.send(message);
}
return {
connect: () => start(),
events: state.emitter,
send: (msg: string) => send(msg),
};
}

131
src/core/client.ts Normal file
View File

@@ -0,0 +1,131 @@
import { createEmitter } from "./events.js";
import { createWebSocketManager } from "../api/websocket.js";
import {
audioReqSchema,
AudioReq,
helloResSchema,
HelloRes,
} from "./schema.js";
import { AudioRequestHandle } from "./request.js";
import { StreamResolvable, intoReadable } from "../util/stream.js";
import { VERSION } from "../util/constant.js";
import "got";
import got from "got";
const ZAKO2_API = "https://zako.ac";
export interface ZakoTapConfig {
name: string;
token: string;
zakoEndpoint?: string;
backoffBaseMs?: number;
}
const defaultConfig = {
zakoEndpoint: ZAKO2_API,
backoffBaseMs: 5000,
};
export function createClient(userConfig: ZakoTapConfig) {
const config = { ...defaultConfig, ...userConfig };
const emitter = createEmitter();
function handleAudioRequest(data: AudioReq) {
if (data.ping) {
fetch(config.zakoEndpoint + `/data/${data.id}/ok`, {
method: "POST",
}).catch((e) => emitter.emit("error", e as Error));
} else {
async function respond(content: StreamResolvable) {
try {
const stream = intoReadable(content);
const httpStream = got.stream.post(
config.zakoEndpoint + `/data/${data.id}/ok`,
);
stream.pipe(httpStream);
} catch (e) {
emitter.emit("error", e as Error);
}
}
async function respondError(message: string) {
try {
await fetch(config.zakoEndpoint + `/data/${data.id}/err`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ message }),
});
} catch (e) {
emitter.emit("error", e as Error);
}
}
const req: AudioRequestHandle = {
data: data.data,
parameters: data.parameters,
respond,
respondError,
};
emitter.emit("request", req);
}
}
function handleHelloRes(data: HelloRes) {
if (!data.ok) return emitter.emit("error", new Error(data.message));
const major = data.version?.split(".")?.[0] ?? -1;
if (parseInt(major) != VERSION[0])
return emitter.emit(
"error",
new Error(
`Mismatching major version: Local(${VERSION[0]}), API(${major})`,
),
);
return emitter.emit("ready");
}
const socket = createWebSocketManager({
url: config.zakoEndpoint.replace("http", "ws") + "/gateway",
backoffBaseMs: config.backoffBaseMs,
});
socket.events.on("error", (err) => emitter.emit("error", err));
socket.events.on("connectionError", (err) =>
emitter.emit("connectionError", err),
);
socket.events.on("message", (content) => {
const data = JSON.parse(content);
if ("id" in data) {
const parsed = audioReqSchema.safeParse(data);
if (parsed.success) handleAudioRequest(parsed.data);
else emitter.emit("error", new Error("Invalid data: " + content));
} else if ("ok" in data) {
const parsed = helloResSchema.safeParse(data);
if (parsed.success) handleHelloRes(parsed.data);
else emitter.emit("error", new Error("Invalid data: " + content));
}
});
socket.events.on("open", () => {
socket.send(
JSON.stringify({
name: config.name,
token: config.token,
}),
);
});
return {
connect: () => socket.connect(),
events: emitter,
};
}

11
src/core/events.ts Normal file
View File

@@ -0,0 +1,11 @@
import { AudioRequestHandle } from "./request.js";
import { EventEmitter } from "eventemitter3";
export type TapEvents = {
ready: () => any;
request: (handle: AudioRequestHandle) => any;
error: (e: Error) => any;
connectionError: (e: Error) => any;
};
export const createEmitter = () => new EventEmitter<TapEvents>();

17
src/core/request.ts Normal file
View File

@@ -0,0 +1,17 @@
import { StreamResolvable } from "../util/stream.js";
export type AudioRequestPayload = {
data: string;
parameters: Record<string, string>;
};
export type AudioResponseFunction = (
content: StreamResolvable,
) => Promise<void>;
export type AudioResponseErrorFunction = (message: string) => Promise<void>;
export type AudioRequestHandle = AudioRequestPayload & {
respond: AudioResponseFunction;
respondError: AudioResponseErrorFunction;
};

17
src/core/schema.ts Normal file
View File

@@ -0,0 +1,17 @@
import { z } from "zod";
export const helloResSchema = z.object({
ok: z.boolean(),
version: z.string(),
message: z.string(),
});
export const audioReqSchema = z.object({
id: z.string(),
data: z.string(),
ping: z.boolean(),
parameters: z.record(z.string(), z.string()),
});
export type HelloRes = z.infer<typeof helloResSchema>;
export type AudioReq = z.infer<typeof audioReqSchema>;

1
src/index.ts Normal file
View File

@@ -0,0 +1 @@
export * from "./core/client.js";

1
src/util/constant.ts Normal file
View File

@@ -0,0 +1 @@
export const VERSION = [1, 0, 0];

34
src/util/stream.ts Normal file
View File

@@ -0,0 +1,34 @@
import { Readable } from "node:stream";
export type StreamResolvable = Buffer | Readable | ReadableStream<Uint8Array>;
export function intoReadable(input: StreamResolvable): Readable {
if (Buffer.isBuffer(input)) {
return Readable.from(input);
}
if (input instanceof Readable) {
return input;
}
if ("getReader" in input && typeof input.getReader === "function") {
const reader = input.getReader();
return new Readable({
async read() {
try {
const { done, value } = await reader.read();
if (done) {
this.push(null);
} else {
if (value) this.push(Buffer.from(value));
}
} catch (err) {
this.destroy(err as Error);
}
},
});
}
throw new TypeError("Unsupported stream type");
}

25
test/blah.test.ts Normal file
View File

@@ -0,0 +1,25 @@
import { createClient } from "../src/core/client.js";
describe("blah", () => {
test("works", async () => {
const client = createClient({
name: "test",
token: "6t4GCQywaLZlZsh1",
zakoEndpoint: "http://127.0.0.1:8081",
});
client.events.on("ready", () => {
console.log("ready");
});
client.events.on("connectionError", (e) => {
console.error(e);
});
client.events.on("error", (e) => console.error(e));
client.connect();
await new Promise((r) => setTimeout(r, 100000));
});
});

108
tsconfig.json Normal file
View File

@@ -0,0 +1,108 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "libReplacement": true, /* Enable lib replacement. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "node16" /* Specify what module code is generated. */,
// "rootDir": "./src" /* Specify the root folder within your source files. */,
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
"rootDirs": [
"src",
"test"
] /* Allow multiple folders to be treated as one when resolving modules. */,
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "noUncheckedSideEffectImports": true, /* Check side effect imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
"declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "outFile": "./", /* 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. */
"outDir": "./dist" /* Specify an output folder for all emitted files. */,
// "removeComments": true, /* Disable emitting comments. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* 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. */
// "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
// "erasableSyntaxOnly": true, /* Do not allow runtime constructs that are not part of ECMAScript. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
"noImplicitAny": false /* Enable error reporting for expressions and declarations with an implied 'any' type. */,
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}