Revert "Revert "Incorporate calckey-js into calckey repository (#9820)""

This reverts commit 8033492c7c.
This commit is contained in:
Kainoa Kanter 2023-04-07 17:44:27 -07:00
parent 8033492c7c
commit 621be91cdb
35 changed files with 22107 additions and 79 deletions

View file

@ -10,6 +10,7 @@ COPY package.json pnpm*.yaml ./
COPY packages/backend/package.json packages/backend/package.json
COPY packages/client/package.json packages/client/package.json
COPY packages/sw/package.json packages/sw/package.json
COPY packages/calckey-js/package.json packages/calckey-js/package.json
COPY packages/backend/native-utils/package.json packages/backend/native-utils/package.json
COPY packages/backend/native-utils/npm/linux-x64-musl/package.json packages/backend/native-utils/npm/linux-x64-musl/package.json
COPY packages/backend/native-utils/npm/linux-arm64-musl/package.json packages/backend/native-utils/npm/linux-arm64-musl/package.json
@ -43,6 +44,7 @@ COPY --from=build /calckey/node_modules /calckey/node_modules
COPY --from=build /calckey/packages/backend/node_modules /calckey/packages/backend/node_modules
COPY --from=build /calckey/packages/sw/node_modules /calckey/packages/sw/node_modules
COPY --from=build /calckey/packages/client/node_modules /calckey/packages/client/node_modules
COPY --from=build /calckey/packages/calckey-js/node_modules /calckey/packages/calckey-js/node_modules
# Copy the finished compiled files
COPY --from=build /calckey/built /calckey/built

View file

@ -40,7 +40,6 @@
"@bull-board/ui": "^4.10.2",
"@napi-rs/cli": "^2.15.0",
"@tensorflow/tfjs": "^3.21.0",
"calckey-js": "^0.0.22",
"js-yaml": "4.1.0",
"seedrandom": "^3.0.5"
},

View file

@ -49,7 +49,7 @@
"blurhash": "1.1.5",
"bull": "4.10.2",
"cacheable-lookup": "7.0.0",
"calckey-js": "^0.0.22",
"calckey-js": "workspace:*",
"cbor": "8.1.0",
"chalk": "5.2.0",
"chalk-template": "0.4.0",

View file

@ -0,0 +1,7 @@
root = true
[*]
indent_style = tab
indent_size = 2
charset = utf-8
insert_final_newline = true

View file

@ -0,0 +1,7 @@
node_modules
/built
/coverage
/.eslintrc.js
/jest.config.ts
/test
/test-d

View file

@ -0,0 +1,65 @@
module.exports = {
root: true,
parser: "@typescript-eslint/parser",
parserOptions: {
tsconfigRootDir: __dirname,
project: ["./tsconfig.json"],
},
plugins: ["@typescript-eslint"],
extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
rules: {
indent: [
"error",
"tab",
{
SwitchCase: 1,
MemberExpression: "off",
flatTernaryExpressions: true,
ArrayExpression: "first",
ObjectExpression: "first",
},
],
"eol-last": ["error", "always"],
semi: ["error", "always"],
quotes: ["error", "single"],
"comma-dangle": ["error", "always-multiline"],
"keyword-spacing": [
"error",
{
before: true,
after: true,
},
],
"key-spacing": [
"error",
{
beforeColon: false,
afterColon: true,
},
],
"space-infix-ops": ["error"],
"space-before-blocks": ["error", "always"],
"object-curly-spacing": ["error", "always"],
"nonblock-statement-body-position": ["error", "beside"],
eqeqeq: ["error", "always", { null: "ignore" }],
"no-multiple-empty-lines": ["error", { max: 1 }],
"no-multi-spaces": ["error"],
"no-var": ["error"],
"prefer-arrow-callback": ["error"],
"no-throw-literal": ["error"],
"no-param-reassign": ["warn"],
"no-constant-condition": ["warn"],
"no-empty-pattern": ["warn"],
"@typescript-eslint/no-unnecessary-condition": ["error"],
"@typescript-eslint/no-inferrable-types": ["warn"],
"@typescript-eslint/no-non-null-assertion": ["warn"],
"@typescript-eslint/explicit-function-return-type": ["warn"],
"@typescript-eslint/no-misused-promises": [
"error",
{
checksVoidReturn: false,
},
],
"@typescript-eslint/consistent-type-imports": "error",
},
};

113
packages/calckey-js/.gitignore vendored Normal file
View file

@ -0,0 +1,113 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-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/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# 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 variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# 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
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# App
temp
# built
# Yarn
.yarn/*
.pnp.cjs
.pnp.loader.mjs

View file

@ -0,0 +1,29 @@
# 0.0.14
- remove needless Object.freeze()
# 0.0.13
- expose ChannelConnection and Channels types
# 0.0.12
- fix a bug that cannot connect to streaming
# 0.0.11
- update user type
- add missing main stream types
# 0.0.10
- add consts
# 0.0.9
- add list of api permission
- Update Note type
# 0.0.8
- add type definition for `messagingMessage` event to main stream channel
- Update Note type
# 0.0.7
- Notificationsの型を修正
- MessagingMessageの型を修正
- UserLiteの型を修正
- apiでネイティブfetchを格納する際に無名関数でラップするように

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-2022 syuilo and other contributors
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.

View file

@ -0,0 +1,7 @@
# Calckey.js
Fork of Misskey.js for Calckey
https://www.npmjs.com/package/calckey-js
![Parody of the Javascript logo with "CK" instead of "JS"](https://codeberg.org/repo-avatars/80771-4d86135f67b9a460cdd1be9e91648e5f)

View file

@ -0,0 +1,364 @@
/**
* Config file for API Extractor. For more info, please visit: https://api-extractor.com
*/
{
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
/**
* Optionally specifies another JSON config file that this file extends from. This provides a way for
* standard settings to be shared across multiple projects.
*
* If the path starts with "./" or "../", the path is resolved relative to the folder of the file that contains
* the "extends" field. Otherwise, the first path segment is interpreted as an NPM package name, and will be
* resolved using NodeJS require().
*
* SUPPORTED TOKENS: none
* DEFAULT VALUE: ""
*/
// "extends": "./shared/api-extractor-base.json"
// "extends": "my-package/include/api-extractor-base.json"
/**
* Determines the "<projectFolder>" token that can be used with other config file settings. The project folder
* typically contains the tsconfig.json and package.json config files, but the path is user-defined.
*
* The path is resolved relative to the folder of the config file that contains the setting.
*
* The default value for "projectFolder" is the token "<lookup>", which means the folder is determined by traversing
* parent folders, starting from the folder containing api-extractor.json, and stopping at the first folder
* that contains a tsconfig.json file. If a tsconfig.json file cannot be found in this way, then an error
* will be reported.
*
* SUPPORTED TOKENS: <lookup>
* DEFAULT VALUE: "<lookup>"
*/
// "projectFolder": "..",
/**
* (REQUIRED) Specifies the .d.ts file to be used as the starting point for analysis. API Extractor
* analyzes the symbols exported by this module.
*
* The file extension must be ".d.ts" and not ".ts".
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
*/
"mainEntryPointFilePath": "<projectFolder>/built/index.d.ts",
/**
* A list of NPM package names whose exports should be treated as part of this package.
*
* For example, suppose that Webpack is used to generate a distributed bundle for the project "library1",
* and another NPM package "library2" is embedded in this bundle. Some types from library2 may become part
* of the exported API for library1, but by default API Extractor would generate a .d.ts rollup that explicitly
* imports library2. To avoid this, we can specify:
*
* "bundledPackages": [ "library2" ],
*
* This would direct API Extractor to embed those types directly in the .d.ts rollup, as if they had been
* local files for library1.
*/
"bundledPackages": [],
/**
* Determines how the TypeScript compiler engine will be invoked by API Extractor.
*/
"compiler": {
/**
* Specifies the path to the tsconfig.json file to be used by API Extractor when analyzing the project.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* Note: This setting will be ignored if "overrideTsconfig" is used.
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/tsconfig.json"
*/
// "tsconfigFilePath": "<projectFolder>/tsconfig.json",
/**
* Provides a compiler configuration that will be used instead of reading the tsconfig.json file from disk.
* The object must conform to the TypeScript tsconfig schema:
*
* http://json.schemastore.org/tsconfig
*
* If omitted, then the tsconfig.json file will be read from the "projectFolder".
*
* DEFAULT VALUE: no overrideTsconfig section
*/
// "overrideTsconfig": {
// . . .
// }
/**
* This option causes the compiler to be invoked with the --skipLibCheck option. This option is not recommended
* and may cause API Extractor to produce incomplete or incorrect declarations, but it may be required when
* dependencies contain declarations that are incompatible with the TypeScript engine that API Extractor uses
* for its analysis. Where possible, the underlying issue should be fixed rather than relying on skipLibCheck.
*
* DEFAULT VALUE: false
*/
// "skipLibCheck": true,
},
/**
* Configures how the API report file (*.api.md) will be generated.
*/
"apiReport": {
/**
* (REQUIRED) Whether to generate an API report.
*/
"enabled": true
/**
* The filename for the API report files. It will be combined with "reportFolder" or "reportTempFolder" to produce
* a full file path.
*
* The file extension should be ".api.md", and the string should not contain a path separator such as "\" or "/".
*
* SUPPORTED TOKENS: <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<unscopedPackageName>.api.md"
*/
// "reportFileName": "<unscopedPackageName>.api.md",
/**
* Specifies the folder where the API report file is written. The file name portion is determined by
* the "reportFileName" setting.
*
* The API report file is normally tracked by Git. Changes to it can be used to trigger a branch policy,
* e.g. for an API review.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/etc/"
*/
// "reportFolder": "<projectFolder>/etc/",
/**
* Specifies the folder where the temporary report file is written. The file name portion is determined by
* the "reportFileName" setting.
*
* After the temporary file is written to disk, it is compared with the file in the "reportFolder".
* If they are different, a production build will fail.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/temp/"
*/
// "reportTempFolder": "<projectFolder>/temp/"
},
/**
* Configures how the doc model file (*.api.json) will be generated.
*/
"docModel": {
/**
* (REQUIRED) Whether to generate a doc model file.
*/
"enabled": true
/**
* The output path for the doc model file. The file extension should be ".api.json".
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/temp/<unscopedPackageName>.api.json"
*/
// "apiJsonFilePath": "<projectFolder>/temp/<unscopedPackageName>.api.json"
},
/**
* Configures how the .d.ts rollup file will be generated.
*/
"dtsRollup": {
/**
* (REQUIRED) Whether to generate the .d.ts rollup file.
*/
"enabled": false
/**
* Specifies the output path for a .d.ts rollup file to be generated without any trimming.
* This file will include all declarations that are exported by the main entry point.
*
* If the path is an empty string, then this file will not be written.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/dist/<unscopedPackageName>.d.ts"
*/
// "untrimmedFilePath": "<projectFolder>/dist/<unscopedPackageName>.d.ts",
/**
* Specifies the output path for a .d.ts rollup file to be generated with trimming for a "beta" release.
* This file will include only declarations that are marked as "@public" or "@beta".
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: ""
*/
// "betaTrimmedFilePath": "<projectFolder>/dist/<unscopedPackageName>-beta.d.ts",
/**
* Specifies the output path for a .d.ts rollup file to be generated with trimming for a "public" release.
* This file will include only declarations that are marked as "@public".
*
* If the path is an empty string, then this file will not be written.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: ""
*/
// "publicTrimmedFilePath": "<projectFolder>/dist/<unscopedPackageName>-public.d.ts",
/**
* When a declaration is trimmed, by default it will be replaced by a code comment such as
* "Excluded from this release type: exampleMember". Set "omitTrimmingComments" to true to remove the
* declaration completely.
*
* DEFAULT VALUE: false
*/
// "omitTrimmingComments": true
},
/**
* Configures how the tsdoc-metadata.json file will be generated.
*/
"tsdocMetadata": {
/**
* Whether to generate the tsdoc-metadata.json file.
*
* DEFAULT VALUE: true
*/
// "enabled": true,
/**
* Specifies where the TSDoc metadata file should be written.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* The default value is "<lookup>", which causes the path to be automatically inferred from the "tsdocMetadata",
* "typings" or "main" fields of the project's package.json. If none of these fields are set, the lookup
* falls back to "tsdoc-metadata.json" in the package folder.
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<lookup>"
*/
// "tsdocMetadataFilePath": "<projectFolder>/dist/tsdoc-metadata.json"
},
/**
* Specifies what type of newlines API Extractor should use when writing output files. By default, the output files
* will be written with Windows-style newlines. To use POSIX-style newlines, specify "lf" instead.
* To use the OS's default newline kind, specify "os".
*
* DEFAULT VALUE: "crlf"
*/
// "newlineKind": "crlf",
/**
* Configures how API Extractor reports error and warning messages produced during analysis.
*
* There are three sources of messages: compiler messages, API Extractor messages, and TSDoc messages.
*/
"messages": {
/**
* Configures handling of diagnostic messages reported by the TypeScript compiler engine while analyzing
* the input .d.ts files.
*
* TypeScript message identifiers start with "TS" followed by an integer. For example: "TS2551"
*
* DEFAULT VALUE: A single "default" entry with logLevel=warning.
*/
"compilerMessageReporting": {
/**
* Configures the default routing for messages that don't match an explicit rule in this table.
*/
"default": {
/**
* Specifies whether the message should be written to the the tool's output log. Note that
* the "addToApiReportFile" property may supersede this option.
*
* Possible values: "error", "warning", "none"
*
* Errors cause the build to fail and return a nonzero exit code. Warnings cause a production build fail
* and return a nonzero exit code. For a non-production build (e.g. when "api-extractor run" includes
* the "--local" option), the warning is displayed but the build will not fail.
*
* DEFAULT VALUE: "warning"
*/
"logLevel": "warning"
/**
* When addToApiReportFile is true: If API Extractor is configured to write an API report file (.api.md),
* then the message will be written inside that file; otherwise, the message is instead logged according to
* the "logLevel" option.
*
* DEFAULT VALUE: false
*/
// "addToApiReportFile": false
}
// "TS2551": {
// "logLevel": "warning",
// "addToApiReportFile": true
// },
//
// . . .
},
/**
* Configures handling of messages reported by API Extractor during its analysis.
*
* API Extractor message identifiers start with "ae-". For example: "ae-extra-release-tag"
*
* DEFAULT VALUE: See api-extractor-defaults.json for the complete table of extractorMessageReporting mappings
*/
"extractorMessageReporting": {
"default": {
"logLevel": "none"
// "addToApiReportFile": false
}
// "ae-extra-release-tag": {
// "logLevel": "warning",
// "addToApiReportFile": true
// },
//
// . . .
},
/**
* Configures handling of messages reported by the TSDoc parser when analyzing code comments.
*
* TSDoc message identifiers start with "tsdoc-". For example: "tsdoc-link-tag-unescaped-text"
*
* DEFAULT VALUE: A single "default" entry with logLevel=warning.
*/
"tsdocMessageReporting": {
"default": {
"logLevel": "warning"
// "addToApiReportFile": false
}
// "tsdoc-link-tag-unescaped-text": {
// "logLevel": "warning",
// "addToApiReportFile": true
// },
//
// . . .
}
}
}

View file

@ -0,0 +1,2 @@
codecov:
token: d55e1270-f20a-4727-aa05-2bd57793315a

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,195 @@
/*
* For a detailed explanation regarding each configuration property and type check, visit:
* https://jestjs.io/docs/en/configuration.html
*/
export default {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "C:\\Users\\ai\\AppData\\Local\\Temp\\jest",
// Automatically clear mock calls and instances between every test
// clearMocks: false,
// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "json",
// "jsx",
// "ts",
// "tsx",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state between every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state between every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
roots: ["<rootDir>"],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: "node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
testMatch: [
"**/__tests__/**/*.[jt]s?(x)",
"**/?(*.)+(spec|test).[tj]s?(x)",
"<rootDir>/test/**/*",
],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jasmine2",
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",
// A map from regular expressions to paths to transformers
transform: {
"^.+\\.(ts|tsx)$": "ts-jest",
},
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "\\\\node_modules\\\\",
// "\\.pnp\\.[^\\\\]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};

10662
packages/calckey-js/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,47 @@
{
"name": "calckey-js",
"version": "0.0.22",
"description": "Calckey SDK for JavaScript",
"main": "./built/index.js",
"types": "./built/index.d.ts",
"scripts": {
"build": "tsc",
"tsd": "tsd",
"api": "pnpm api-extractor run --local --verbose",
"api-prod": "pnpm api-extractor run --verbose",
"eslint": "eslint . --ext .js,.jsx,.ts,.tsx",
"typecheck": "tsc --noEmit",
"lint": "pnpm typecheck && pnpm eslint",
"jest": "jest --coverage --detectOpenHandles",
"test": "pnpm jest && pnpm tsd"
},
"repository": {
"type": "git",
"url": "https://codeberg.org/calckey/calckey.js"
},
"devDependencies": {
"@microsoft/api-extractor": "^7.19.3",
"@types/jest": "^27.4.0",
"@types/node": "17.0.5",
"@typescript-eslint/eslint-plugin": "5.8.1",
"@typescript-eslint/parser": "5.8.1",
"eslint": "8.6.0",
"jest": "^27.4.5",
"jest-fetch-mock": "^3.0.3",
"jest-websocket-mock": "^2.2.1",
"mock-socket": "^9.0.8",
"ts-jest": "^27.1.2",
"ts-node": "10.4.0",
"tsd": "^0.19.1",
"typescript": "4.5.4"
},
"files": [
"built"
],
"dependencies": {
"autobind-decorator": "^2.4.0",
"eventemitter3": "^4.0.7",
"reconnecting-websocket": "^4.4.0",
"semver": "^7.3.8"
}
}

View file

@ -0,0 +1,14 @@
export type Acct = {
username: string;
host: string | null;
};
export function parse(acct: string): Acct {
if (acct.startsWith("@")) acct = acct.substr(1);
const split = acct.split("@", 2);
return { username: split[0], host: split[1] || null };
}
export function toString(acct: Acct): string {
return acct.host == null ? acct.username : `${acct.username}@${acct.host}`;
}

View file

@ -0,0 +1,127 @@
import { Endpoints } from "./api.types";
const MK_API_ERROR = Symbol();
export type APIError = {
id: string;
code: string;
message: string;
kind: "client" | "server";
info: Record<string, any>;
};
export function isAPIError(reason: any): reason is APIError {
return reason[MK_API_ERROR] === true;
}
export type FetchLike = (
input: string,
init?: {
method?: string;
body?: string;
credentials?: RequestCredentials;
cache?: RequestCache;
},
) => Promise<{
status: number;
json(): Promise<any>;
}>;
type IsNeverType<T> = [T] extends [never] ? true : false;
type StrictExtract<Union, Cond> = Cond extends Union ? Union : never;
type IsCaseMatched<
E extends keyof Endpoints,
P extends Endpoints[E]["req"],
C extends number,
> = IsNeverType<
StrictExtract<Endpoints[E]["res"]["$switch"]["$cases"][C], [P, any]>
> extends false
? true
: false;
type GetCaseResult<
E extends keyof Endpoints,
P extends Endpoints[E]["req"],
C extends number,
> = StrictExtract<Endpoints[E]["res"]["$switch"]["$cases"][C], [P, any]>[1];
export class APIClient {
public origin: string;
public credential: string | null | undefined;
public fetch: FetchLike;
constructor(opts: {
origin: APIClient["origin"];
credential?: APIClient["credential"];
fetch?: APIClient["fetch"] | null | undefined;
}) {
this.origin = opts.origin;
this.credential = opts.credential;
// ネイティブ関数をそのまま変数に代入して使おうとするとChromiumではIllegal invocationエラーが発生するため、
// 環境で実装されているfetchを使う場合は無名関数でラップして使用する
this.fetch = opts.fetch || ((...args) => fetch(...args));
}
public request<E extends keyof Endpoints, P extends Endpoints[E]["req"]>(
endpoint: E,
params: P = {} as P,
credential?: string | null | undefined,
): Promise<
Endpoints[E]["res"] extends {
$switch: { $cases: [any, any][]; $default: any };
}
? IsCaseMatched<E, P, 0> extends true
? GetCaseResult<E, P, 0>
: IsCaseMatched<E, P, 1> extends true
? GetCaseResult<E, P, 1>
: IsCaseMatched<E, P, 2> extends true
? GetCaseResult<E, P, 2>
: IsCaseMatched<E, P, 3> extends true
? GetCaseResult<E, P, 3>
: IsCaseMatched<E, P, 4> extends true
? GetCaseResult<E, P, 4>
: IsCaseMatched<E, P, 5> extends true
? GetCaseResult<E, P, 5>
: IsCaseMatched<E, P, 6> extends true
? GetCaseResult<E, P, 6>
: IsCaseMatched<E, P, 7> extends true
? GetCaseResult<E, P, 7>
: IsCaseMatched<E, P, 8> extends true
? GetCaseResult<E, P, 8>
: IsCaseMatched<E, P, 9> extends true
? GetCaseResult<E, P, 9>
: Endpoints[E]["res"]["$switch"]["$default"]
: Endpoints[E]["res"]
> {
const promise = new Promise((resolve, reject) => {
this.fetch(`${this.origin}/api/${endpoint}`, {
method: "POST",
body: JSON.stringify({
...params,
i: credential !== undefined ? credential : this.credential,
}),
credentials: "omit",
cache: "no-cache",
})
.then(async (res) => {
const body = res.status === 204 ? null : await res.json();
if (res.status === 200) {
resolve(body);
} else if (res.status === 204) {
resolve(null);
} else {
reject({
[MK_API_ERROR]: true,
...body.error,
});
}
})
.catch(reject);
});
return promise as any;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,60 @@
export const notificationTypes = [
"follow",
"mention",
"reply",
"renote",
"quote",
"reaction",
"pollVote",
"pollEnded",
"receiveFollowRequest",
"followRequestAccepted",
"groupInvited",
"app",
] as const;
export const noteVisibilities = [
"public",
"home",
"followers",
"specified",
] as const;
export const mutedNoteReasons = ["word", "manual", "spam", "other"] as const;
export const ffVisibility = ["public", "followers", "private"] as const;
export const permissions = [
"read:account",
"write:account",
"read:blocks",
"write:blocks",
"read:drive",
"write:drive",
"read:favorites",
"write:favorites",
"read:following",
"write:following",
"read:messaging",
"write:messaging",
"read:mutes",
"write:mutes",
"write:notes",
"read:notifications",
"write:notifications",
"read:reactions",
"write:reactions",
"write:votes",
"read:pages",
"write:pages",
"write:page-likes",
"read:page-likes",
"read:user-groups",
"write:user-groups",
"read:channels",
"write:channels",
"read:gallery",
"write:gallery",
"read:gallery-likes",
"write:gallery-likes",
];

View file

@ -0,0 +1,490 @@
export type ID = string;
export type DateString = string;
type TODO = Record<string, any>;
// NOTE: 極力この型を使うのは避け、UserLite か UserDetailed か明示するように
export type User = UserLite | UserDetailed;
export type UserLite = {
id: ID;
username: string;
host: string | null;
name: string;
onlineStatus: "online" | "active" | "offline" | "unknown";
avatarUrl: string;
avatarBlurhash: string;
alsoKnownAs: string[];
movedToUri: any;
emojis: {
name: string;
url: string;
}[];
instance?: {
name: Instance["name"];
softwareName: Instance["softwareName"];
softwareVersion: Instance["softwareVersion"];
iconUrl: Instance["iconUrl"];
faviconUrl: Instance["faviconUrl"];
themeColor: Instance["themeColor"];
};
};
export type UserDetailed = UserLite & {
bannerBlurhash: string | null;
bannerColor: string | null;
bannerUrl: string | null;
birthday: string | null;
createdAt: DateString;
description: string | null;
ffVisibility: "public" | "followers" | "private";
fields: { name: string; value: string }[];
followersCount: number;
followingCount: number;
hasPendingFollowRequestFromYou: boolean;
hasPendingFollowRequestToYou: boolean;
isAdmin: boolean;
isBlocked: boolean;
isBlocking: boolean;
isBot: boolean;
isCat: boolean;
isFollowed: boolean;
isFollowing: boolean;
isLocked: boolean;
isModerator: boolean;
isMuted: boolean;
isSilenced: boolean;
isSuspended: boolean;
lang: string | null;
lastFetchedAt?: DateString;
location: string | null;
notesCount: number;
pinnedNoteIds: ID[];
pinnedNotes: Note[];
pinnedPage: Page | null;
pinnedPageId: string | null;
publicReactions: boolean;
securityKeys: boolean;
twoFactorEnabled: boolean;
updatedAt: DateString | null;
uri: string | null;
url: string | null;
};
export type UserGroup = TODO;
export type UserList = {
id: ID;
createdAt: DateString;
name: string;
userIds: User["id"][];
};
export type MeDetailed = UserDetailed & {
avatarId: DriveFile["id"];
bannerId: DriveFile["id"];
autoAcceptFollowed: boolean;
alwaysMarkNsfw: boolean;
carefulBot: boolean;
emailNotificationTypes: string[];
hasPendingReceivedFollowRequest: boolean;
hasUnreadAnnouncement: boolean;
hasUnreadAntenna: boolean;
hasUnreadChannel: boolean;
hasUnreadMentions: boolean;
hasUnreadMessagingMessage: boolean;
hasUnreadNotification: boolean;
hasUnreadSpecifiedNotes: boolean;
hideOnlineStatus: boolean;
injectFeaturedNote: boolean;
integrations: Record<string, any>;
isDeleted: boolean;
isExplorable: boolean;
mutedWords: string[][];
mutingNotificationTypes: string[];
noCrawle: boolean;
receiveAnnouncementEmail: boolean;
usePasswordLessLogin: boolean;
[other: string]: any;
};
export type DriveFile = {
id: ID;
createdAt: DateString;
isSensitive: boolean;
name: string;
thumbnailUrl: string;
url: string;
type: string;
size: number;
md5: string;
blurhash: string;
comment: string | null;
properties: Record<string, any>;
};
export type DriveFolder = TODO;
export type GalleryPost = TODO;
export type Note = {
id: ID;
createdAt: DateString;
text: string | null;
cw: string | null;
user: User;
userId: User["id"];
reply?: Note;
replyId: Note["id"];
renote?: Note;
renoteId: Note["id"];
files: DriveFile[];
fileIds: DriveFile["id"][];
visibility: "public" | "home" | "followers" | "specified";
visibleUserIds?: User["id"][];
localOnly?: boolean;
myReaction?: string;
reactions: Record<string, number>;
renoteCount: number;
repliesCount: number;
poll?: {
expiresAt: DateString | null;
multiple: boolean;
choices: {
isVoted: boolean;
text: string;
votes: number;
}[];
};
emojis: {
name: string;
url: string;
}[];
uri?: string;
url?: string;
isHidden?: boolean;
};
export type NoteReaction = {
id: ID;
createdAt: DateString;
user: UserLite;
type: string;
};
export type Notification = {
id: ID;
createdAt: DateString;
isRead: boolean;
} & (
| {
type: "reaction";
reaction: string;
user: User;
userId: User["id"];
note: Note;
}
| {
type: "reply";
user: User;
userId: User["id"];
note: Note;
}
| {
type: "renote";
user: User;
userId: User["id"];
note: Note;
}
| {
type: "quote";
user: User;
userId: User["id"];
note: Note;
}
| {
type: "mention";
user: User;
userId: User["id"];
note: Note;
}
| {
type: "pollVote";
user: User;
userId: User["id"];
note: Note;
}
| {
type: "follow";
user: User;
userId: User["id"];
}
| {
type: "followRequestAccepted";
user: User;
userId: User["id"];
}
| {
type: "receiveFollowRequest";
user: User;
userId: User["id"];
}
| {
type: "groupInvited";
invitation: UserGroup;
user: User;
userId: User["id"];
}
| {
type: "app";
header?: string | null;
body: string;
icon?: string | null;
}
);
export type MessagingMessage = {
id: ID;
createdAt: DateString;
file: DriveFile | null;
fileId: DriveFile["id"] | null;
isRead: boolean;
reads: User["id"][];
text: string | null;
user: User;
userId: User["id"];
recipient?: User | null;
recipientId: User["id"] | null;
group?: UserGroup | null;
groupId: UserGroup["id"] | null;
};
export type CustomEmoji = {
id: string;
name: string;
url: string;
category: string;
aliases: string[];
};
export type LiteInstanceMetadata = {
maintainerName: string | null;
maintainerEmail: string | null;
version: string;
name: string | null;
uri: string;
description: string | null;
tosUrl: string | null;
disableRegistration: boolean;
disableLocalTimeline: boolean;
disableRecommendedTimeline: boolean;
disableGlobalTimeline: boolean;
driveCapacityPerLocalUserMb: number;
driveCapacityPerRemoteUserMb: number;
enableHcaptcha: boolean;
hcaptchaSiteKey: string | null;
enableRecaptcha: boolean;
recaptchaSiteKey: string | null;
swPublickey: string | null;
maxNoteTextLength: number;
enableEmail: boolean;
enableTwitterIntegration: boolean;
enableGithubIntegration: boolean;
enableDiscordIntegration: boolean;
enableServiceWorker: boolean;
emojis: CustomEmoji[];
ads: {
id: ID;
ratio: number;
place: string;
url: string;
imageUrl: string;
}[];
};
export type DetailedInstanceMetadata = LiteInstanceMetadata & {
features: Record<string, any>;
};
export type InstanceMetadata = LiteInstanceMetadata | DetailedInstanceMetadata;
export type ServerInfo = {
machine: string;
cpu: {
model: string;
cores: number;
};
mem: {
total: number;
};
fs: {
total: number;
used: number;
};
};
export type Stats = {
notesCount: number;
originalNotesCount: number;
usersCount: number;
originalUsersCount: number;
instances: number;
driveUsageLocal: number;
driveUsageRemote: number;
};
export type Page = {
id: ID;
createdAt: DateString;
updatedAt: DateString;
userId: User["id"];
user: User;
content: Record<string, any>[];
variables: Record<string, any>[];
title: string;
name: string;
summary: string | null;
hideTitleWhenPinned: boolean;
alignCenter: boolean;
font: string;
script: string;
eyeCatchingImageId: DriveFile["id"] | null;
eyeCatchingImage: DriveFile | null;
attachedFiles: any;
likedCount: number;
isLiked?: boolean;
};
export type PageEvent = {
pageId: Page["id"];
event: string;
var: any;
userId: User["id"];
user: User;
};
export type Announcement = {
id: ID;
createdAt: DateString;
updatedAt: DateString | null;
text: string;
title: string;
imageUrl: string | null;
isRead?: boolean;
};
export type Antenna = {
id: ID;
createdAt: DateString;
name: string;
keywords: string[][]; // TODO
excludeKeywords: string[][]; // TODO
src: "home" | "all" | "users" | "list" | "group" | "instances";
userListId: ID | null; // TODO
userGroupId: ID | null; // TODO
users: string[]; // TODO
instances: string[];
caseSensitive: boolean;
notify: boolean;
withReplies: boolean;
withFile: boolean;
hasUnreadNote: boolean;
};
export type App = TODO;
export type AuthSession = {
id: ID;
app: App;
token: string;
};
export type Ad = TODO;
export type Clip = TODO;
export type NoteFavorite = {
id: ID;
createdAt: DateString;
noteId: Note["id"];
note: Note;
};
export type FollowRequest = {
id: ID;
follower: User;
followee: User;
};
export type Channel = {
id: ID;
// TODO
};
export type Following = {
id: ID;
createdAt: DateString;
followerId: User["id"];
followeeId: User["id"];
};
export type FollowingFolloweePopulated = Following & {
followee: UserDetailed;
};
export type FollowingFollowerPopulated = Following & {
follower: UserDetailed;
};
export type Blocking = {
id: ID;
createdAt: DateString;
blockeeId: User["id"];
blockee: UserDetailed;
};
export type Instance = {
id: ID;
caughtAt: DateString;
host: string;
usersCount: number;
notesCount: number;
followingCount: number;
followersCount: number;
driveUsage: number;
driveFiles: number;
latestRequestSentAt: DateString | null;
latestStatus: number | null;
latestRequestReceivedAt: DateString | null;
lastCommunicatedAt: DateString;
isNotResponding: boolean;
isSuspended: boolean;
softwareName: string | null;
softwareVersion: string | null;
openRegistrations: boolean | null;
name: string | null;
description: string | null;
maintainerName: string | null;
maintainerEmail: string | null;
iconUrl: string | null;
faviconUrl: string | null;
themeColor: string | null;
infoUpdatedAt: DateString | null;
};
export type Signin = {
id: ID;
createdAt: DateString;
ip: string;
headers: Record<string, any>;
success: boolean;
};
export type UserSorting =
| "+follower"
| "-follower"
| "+createdAt"
| "-createdAt"
| "+updatedAt"
| "-updatedAt";
export type OriginType = "combined" | "local" | "remote";

View file

@ -0,0 +1,20 @@
import { Endpoints } from "./api.types";
import Stream, { Connection } from "./streaming";
import { Channels } from "./streaming.types";
import { Acct } from "./acct";
import * as consts from "./consts";
export { Endpoints, Stream, Connection as ChannelConnection, Channels, Acct };
export const permissions = consts.permissions;
export const notificationTypes = consts.notificationTypes;
export const noteVisibilities = consts.noteVisibilities;
export const mutedNoteReasons = consts.mutedNoteReasons;
export const ffVisibility = consts.ffVisibility;
// api extractor not supported yet
//export * as api from './api';
//export * as entities from './entities';
import * as api from "./api";
import * as entities from "./entities";
export { api, entities };

View file

@ -0,0 +1,393 @@
import autobind from "autobind-decorator";
import { EventEmitter } from "eventemitter3";
import ReconnectingWebsocket from "reconnecting-websocket";
import { BroadcastEvents, Channels } from "./streaming.types";
export function urlQuery(
obj: Record<string, string | number | boolean | undefined>,
): string {
const params = Object.entries(obj)
.filter(([, v]) => (Array.isArray(v) ? v.length : v !== undefined))
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
.reduce(
(a, [k, v]) => ((a[k] = v!), a),
{} as Record<string, string | number | boolean>,
);
return Object.entries(params)
.map((e) => `${e[0]}=${encodeURIComponent(e[1])}`)
.join("&");
}
type AnyOf<T extends Record<any, any>> = T[keyof T];
type StreamEvents = {
_connected_: void;
_disconnected_: void;
} & BroadcastEvents;
/**
* Misskey stream connection
*/
export default class Stream extends EventEmitter<StreamEvents> {
private stream: ReconnectingWebsocket;
public state: "initializing" | "reconnecting" | "connected" = "initializing";
private sharedConnectionPools: Pool[] = [];
private sharedConnections: SharedConnection[] = [];
private nonSharedConnections: NonSharedConnection[] = [];
private idCounter = 0;
constructor(
origin: string,
user: { token: string } | null,
options?: {
WebSocket?: any;
},
) {
super();
options = options || {};
const query = urlQuery({
i: user?.token,
// To prevent cache of an HTML such as error screen
_t: Date.now(),
});
const wsOrigin = origin
.replace("http://", "ws://")
.replace("https://", "wss://");
this.stream = new ReconnectingWebsocket(
`${wsOrigin}/streaming?${query}`,
"",
{
minReconnectionDelay: 1, // https://github.com/pladaria/reconnecting-websocket/issues/91
WebSocket: options.WebSocket,
},
);
this.stream.addEventListener("open", this.onOpen);
this.stream.addEventListener("close", this.onClose);
this.stream.addEventListener("message", this.onMessage);
}
@autobind
private genId(): string {
return (++this.idCounter).toString();
}
@autobind
public useChannel<C extends keyof Channels>(
channel: C,
params?: Channels[C]["params"],
name?: string,
): Connection<Channels[C]> {
if (params) {
return this.connectToChannel(channel, params);
} else {
return this.useSharedConnection(channel, name);
}
}
@autobind
private useSharedConnection<C extends keyof Channels>(
channel: C,
name?: string,
): SharedConnection<Channels[C]> {
let pool = this.sharedConnectionPools.find((p) => p.channel === channel);
if (pool == null) {
pool = new Pool(this, channel, this.genId());
this.sharedConnectionPools.push(pool);
}
const connection = new SharedConnection(this, channel, pool, name);
this.sharedConnections.push(connection);
return connection;
}
@autobind
public removeSharedConnection(connection: SharedConnection): void {
this.sharedConnections = this.sharedConnections.filter(
(c) => c !== connection,
);
}
@autobind
public removeSharedConnectionPool(pool: Pool): void {
this.sharedConnectionPools = this.sharedConnectionPools.filter(
(p) => p !== pool,
);
}
@autobind
private connectToChannel<C extends keyof Channels>(
channel: C,
params: Channels[C]["params"],
): NonSharedConnection<Channels[C]> {
const connection = new NonSharedConnection(
this,
channel,
this.genId(),
params,
);
this.nonSharedConnections.push(connection);
return connection;
}
@autobind
public disconnectToChannel(connection: NonSharedConnection): void {
this.nonSharedConnections = this.nonSharedConnections.filter(
(c) => c !== connection,
);
}
/**
* Callback of when open connection
*/
@autobind
private onOpen(): void {
const isReconnect = this.state === "reconnecting";
this.state = "connected";
this.emit("_connected_");
// チャンネル再接続
if (isReconnect) {
for (const p of this.sharedConnectionPools) p.connect();
for (const c of this.nonSharedConnections) c.connect();
}
}
/**
* Callback of when close connection
*/
@autobind
private onClose(): void {
if (this.state === "connected") {
this.state = "reconnecting";
this.emit("_disconnected_");
}
}
/**
* Callback of when received a message from connection
*/
@autobind
private onMessage(message: { data: string }): void {
const { type, body } = JSON.parse(message.data);
if (type === "channel") {
const id = body.id;
let connections: Connection[];
connections = this.sharedConnections.filter((c) => c.id === id);
if (connections.length === 0) {
const found = this.nonSharedConnections.find((c) => c.id === id);
if (found) {
connections = [found];
}
}
for (const c of connections) {
c.emit(body.type, body.body);
c.inCount++;
}
} else {
this.emit(type, body);
}
}
/**
* Send a message to connection
*/
@autobind
public send(typeOrPayload: any, payload?: any): void {
const data =
payload === undefined
? typeOrPayload
: {
type: typeOrPayload,
body: payload,
};
this.stream.send(JSON.stringify(data));
}
/**
* Close this connection
*/
@autobind
public close(): void {
this.stream.close();
}
}
// TODO: これらのクラスを Stream クラスの内部クラスにすれば余計なメンバをpublicにしないで済むかも
// もしくは @internal を使う? https://www.typescriptlang.org/tsconfig#stripInternal
class Pool {
public channel: string;
public id: string;
protected stream: Stream;
public users = 0;
private disposeTimerId: any;
private isConnected = false;
constructor(stream: Stream, channel: string, id: string) {
this.channel = channel;
this.stream = stream;
this.id = id;
this.stream.on("_disconnected_", this.onStreamDisconnected);
}
@autobind
private onStreamDisconnected(): void {
this.isConnected = false;
}
@autobind
public inc(): void {
if (this.users === 0 && !this.isConnected) {
this.connect();
}
this.users++;
// タイマー解除
if (this.disposeTimerId) {
clearTimeout(this.disposeTimerId);
this.disposeTimerId = null;
}
}
@autobind
public dec(): void {
this.users--;
// そのコネクションの利用者が誰もいなくなったら
if (this.users === 0) {
// また直ぐに再利用される可能性があるので、一定時間待ち、
// 新たな利用者が現れなければコネクションを切断する
this.disposeTimerId = setTimeout(() => {
this.disconnect();
}, 3000);
}
}
@autobind
public connect(): void {
if (this.isConnected) return;
this.isConnected = true;
this.stream.send("connect", {
channel: this.channel,
id: this.id,
});
}
@autobind
private disconnect(): void {
this.stream.off("_disconnected_", this.onStreamDisconnected);
this.stream.send("disconnect", { id: this.id });
this.stream.removeSharedConnectionPool(this);
}
}
export abstract class Connection<
Channel extends AnyOf<Channels> = any,
> extends EventEmitter<Channel["events"]> {
public channel: string;
protected stream: Stream;
public abstract id: string;
public name?: string; // for debug
public inCount = 0; // for debug
public outCount = 0; // for debug
constructor(stream: Stream, channel: string, name?: string) {
super();
this.stream = stream;
this.channel = channel;
this.name = name;
}
@autobind
public send<T extends keyof Channel["receives"]>(
type: T,
body: Channel["receives"][T],
): void {
this.stream.send("ch", {
id: this.id,
type: type,
body: body,
});
this.outCount++;
}
public abstract dispose(): void;
}
class SharedConnection<
Channel extends AnyOf<Channels> = any,
> extends Connection<Channel> {
private pool: Pool;
public get id(): string {
return this.pool.id;
}
constructor(stream: Stream, channel: string, pool: Pool, name?: string) {
super(stream, channel, name);
this.pool = pool;
this.pool.inc();
}
@autobind
public dispose(): void {
this.pool.dec();
this.removeAllListeners();
this.stream.removeSharedConnection(this);
}
}
class NonSharedConnection<
Channel extends AnyOf<Channels> = any,
> extends Connection<Channel> {
public id: string;
protected params: Channel["params"];
constructor(
stream: Stream,
channel: string,
id: string,
params: Channel["params"],
) {
super(stream, channel);
this.params = params;
this.id = id;
this.connect();
}
@autobind
public connect(): void {
this.stream.send("connect", {
channel: this.channel,
id: this.id,
params: this.params,
});
}
@autobind
public dispose(): void {
this.removeAllListeners();
this.stream.send("disconnect", { id: this.id });
this.stream.disconnectToChannel(this);
}
}

View file

@ -0,0 +1,181 @@
import {
Antenna,
CustomEmoji,
DriveFile,
MeDetailed,
MessagingMessage,
Note,
Notification,
PageEvent,
User,
UserGroup,
} from "./entities";
type FIXME = any;
export type Channels = {
main: {
params: null;
events: {
notification: (payload: Notification) => void;
mention: (payload: Note) => void;
reply: (payload: Note) => void;
renote: (payload: Note) => void;
follow: (payload: User) => void; // 自分が他人をフォローしたとき
followed: (payload: User) => void; // 他人が自分をフォローしたとき
unfollow: (payload: User) => void; // 自分が他人をフォロー解除したとき
meUpdated: (payload: MeDetailed) => void;
pageEvent: (payload: PageEvent) => void;
urlUploadFinished: (payload: { marker: string; file: DriveFile }) => void;
readAllNotifications: () => void;
unreadNotification: (payload: Notification) => void;
unreadMention: (payload: Note["id"]) => void;
readAllUnreadMentions: () => void;
unreadSpecifiedNote: (payload: Note["id"]) => void;
readAllUnreadSpecifiedNotes: () => void;
readAllMessagingMessages: () => void;
messagingMessage: (payload: MessagingMessage) => void;
unreadMessagingMessage: (payload: MessagingMessage) => void;
readAllAntennas: () => void;
unreadAntenna: (payload: Antenna) => void;
readAllAnnouncements: () => void;
readAllChannels: () => void;
unreadChannel: (payload: Note["id"]) => void;
myTokenRegenerated: () => void;
reversiNoInvites: () => void;
reversiInvited: (payload: FIXME) => void;
signin: (payload: FIXME) => void;
registryUpdated: (payload: {
scope?: string[];
key: string;
value: any | null;
}) => void;
driveFileCreated: (payload: DriveFile) => void;
readAntenna: (payload: Antenna) => void;
};
receives: null;
};
homeTimeline: {
params: null;
events: {
note: (payload: Note) => void;
};
receives: null;
};
localTimeline: {
params: null;
events: {
note: (payload: Note) => void;
};
receives: null;
};
hybridTimeline: {
params: null;
events: {
note: (payload: Note) => void;
};
receives: null;
};
recommendedTimeline: {
params: null;
events: {
note: (payload: Note) => void;
};
receives: null;
};
globalTimeline: {
params: null;
events: {
note: (payload: Note) => void;
};
receives: null;
};
messaging: {
params: {
otherparty?: User["id"] | null;
group?: UserGroup["id"] | null;
};
events: {
message: (payload: MessagingMessage) => void;
deleted: (payload: MessagingMessage["id"]) => void;
read: (payload: MessagingMessage["id"][]) => void;
typers: (payload: User[]) => void;
};
receives: {
read: {
id: MessagingMessage["id"];
};
};
};
serverStats: {
params: null;
events: {
stats: (payload: FIXME) => void;
};
receives: {
requestLog: {
id: string | number;
length: number;
};
};
};
queueStats: {
params: null;
events: {
stats: (payload: FIXME) => void;
};
receives: {
requestLog: {
id: string | number;
length: number;
};
};
};
};
export type NoteUpdatedEvent =
| {
id: Note["id"];
type: "reacted";
body: {
reaction: string;
userId: User["id"];
};
}
| {
id: Note["id"];
type: "unreacted";
body: {
reaction: string;
userId: User["id"];
};
}
| {
id: Note["id"];
type: "deleted";
body: {
deletedAt: string;
};
}
| {
id: Note["id"];
type: "pollVoted";
body: {
choice: number;
userId: User["id"];
};
}
| {
id: Note["id"];
type: "replied";
body: {
id: Note["id"];
};
};
export type BroadcastEvents = {
noteUpdated: (payload: NoteUpdatedEvent) => void;
emojiAdded: (payload: {
emoji: CustomEmoji;
}) => void;
};

View file

@ -0,0 +1,48 @@
import { expectType } from "tsd";
import * as Misskey from "../src";
describe("API", () => {
test("success", async () => {
const cli = new Misskey.api.APIClient({
origin: "https://misskey.test",
credential: "TOKEN",
});
const res = await cli.request("meta", { detail: true });
expectType<Misskey.entities.DetailedInstanceMetadata>(res);
});
test("conditional respose type (meta)", async () => {
const cli = new Misskey.api.APIClient({
origin: "https://misskey.test",
credential: "TOKEN",
});
const res = await cli.request("meta", { detail: true });
expectType<Misskey.entities.DetailedInstanceMetadata>(res);
const res2 = await cli.request("meta", { detail: false });
expectType<Misskey.entities.LiteInstanceMetadata>(res2);
const res3 = await cli.request("meta", {});
expectType<Misskey.entities.LiteInstanceMetadata>(res3);
const res4 = await cli.request("meta", { detail: true as boolean });
expectType<
| Misskey.entities.LiteInstanceMetadata
| Misskey.entities.DetailedInstanceMetadata
>(res4);
});
test("conditional respose type (users/show)", async () => {
const cli = new Misskey.api.APIClient({
origin: "https://misskey.test",
credential: "TOKEN",
});
const res = await cli.request("users/show", { userId: "xxxxxxxx" });
expectType<Misskey.entities.UserDetailed>(res);
const res2 = await cli.request("users/show", { userIds: ["xxxxxxxx"] });
expectType<Misskey.entities.UserDetailed[]>(res2);
});
});

View file

@ -0,0 +1,32 @@
import { expectType } from "tsd";
import * as Misskey from "../src";
describe("Streaming", () => {
test("emit type", async () => {
const stream = new Misskey.Stream("https://misskey.test", {
token: "TOKEN",
});
const mainChannel = stream.useChannel("main");
mainChannel.on("notification", (notification) => {
expectType<Misskey.entities.Notification>(notification);
});
});
test("params type", async () => {
const stream = new Misskey.Stream("https://misskey.test", {
token: "TOKEN",
});
// TODO: 「stream.useChannel の第二引数として受け入れる型が
// {
// otherparty?: User['id'] | null;
// group?: UserGroup['id'] | null;
// }
// になっている」というテストを行いたいけどtsdでの書き方がわからない
const messagingChannel = stream.useChannel("messaging", {
otherparty: "aaa",
});
messagingChannel.on("message", (message) => {
expectType<Misskey.entities.MessagingMessage>(message);
});
});
});

View file

@ -0,0 +1,222 @@
import { APIClient, isAPIError } from "../src/api";
import { enableFetchMocks } from "jest-fetch-mock";
enableFetchMocks();
function getFetchCall(call: any[]) {
const { body, method } = call[1];
if (body != null && typeof body != "string") {
throw new Error("invalid body");
}
return {
url: call[0],
method: method,
body: JSON.parse(body as any),
};
}
describe("API", () => {
test("success", async () => {
fetchMock.resetMocks();
fetchMock.mockResponse(async (req) => {
const body = await req.json();
if (req.method == "POST" && req.url == "https://misskey.test/api/i") {
if (body.i === "TOKEN") {
return JSON.stringify({ id: "foo" });
} else {
return { status: 400 };
}
} else {
return { status: 404 };
}
});
const cli = new APIClient({
origin: "https://misskey.test",
credential: "TOKEN",
});
const res = await cli.request("i");
expect(res).toEqual({
id: "foo",
});
expect(getFetchCall(fetchMock.mock.calls[0])).toEqual({
url: "https://misskey.test/api/i",
method: "POST",
body: { i: "TOKEN" },
});
});
test("with params", async () => {
fetchMock.resetMocks();
fetchMock.mockResponse(async (req) => {
const body = await req.json();
if (
req.method == "POST" &&
req.url == "https://misskey.test/api/notes/show"
) {
if (body.i === "TOKEN" && body.noteId === "aaaaa") {
return JSON.stringify({ id: "foo" });
} else {
return { status: 400 };
}
} else {
return { status: 404 };
}
});
const cli = new APIClient({
origin: "https://misskey.test",
credential: "TOKEN",
});
const res = await cli.request("notes/show", { noteId: "aaaaa" });
expect(res).toEqual({
id: "foo",
});
expect(getFetchCall(fetchMock.mock.calls[0])).toEqual({
url: "https://misskey.test/api/notes/show",
method: "POST",
body: { i: "TOKEN", noteId: "aaaaa" },
});
});
test("204 No Content で null が返る", async () => {
fetchMock.resetMocks();
fetchMock.mockResponse(async (req) => {
if (
req.method == "POST" &&
req.url == "https://misskey.test/api/reset-password"
) {
return { status: 204 };
} else {
return { status: 404 };
}
});
const cli = new APIClient({
origin: "https://misskey.test",
credential: "TOKEN",
});
const res = await cli.request("reset-password", {
token: "aaa",
password: "aaa",
});
expect(res).toEqual(null);
expect(getFetchCall(fetchMock.mock.calls[0])).toEqual({
url: "https://misskey.test/api/reset-password",
method: "POST",
body: { i: "TOKEN", token: "aaa", password: "aaa" },
});
});
test("インスタンスの credential が指定されていても引数で credential が null ならば null としてリクエストされる", async () => {
fetchMock.resetMocks();
fetchMock.mockResponse(async (req) => {
const body = await req.json();
if (req.method == "POST" && req.url == "https://misskey.test/api/i") {
if (typeof body.i === "string") {
return JSON.stringify({ id: "foo" });
} else {
return {
status: 401,
body: JSON.stringify({
error: {
message: "Credential required.",
code: "CREDENTIAL_REQUIRED",
id: "1384574d-a912-4b81-8601-c7b1c4085df1",
},
}),
};
}
} else {
return { status: 404 };
}
});
try {
const cli = new APIClient({
origin: "https://misskey.test",
credential: "TOKEN",
});
await cli.request("i", {}, null);
} catch (e) {
expect(isAPIError(e)).toEqual(true);
}
});
test("api error", async () => {
fetchMock.resetMocks();
fetchMock.mockResponse(async (req) => {
return {
status: 500,
body: JSON.stringify({
error: {
message:
"Internal error occurred. Please contact us if the error persists.",
code: "INTERNAL_ERROR",
id: "5d37dbcb-891e-41ca-a3d6-e690c97775ac",
kind: "server",
},
}),
};
});
try {
const cli = new APIClient({
origin: "https://misskey.test",
credential: "TOKEN",
});
await cli.request("i");
} catch (e: any) {
expect(isAPIError(e)).toEqual(true);
expect(e.id).toEqual("5d37dbcb-891e-41ca-a3d6-e690c97775ac");
}
});
test("network error", async () => {
fetchMock.resetMocks();
fetchMock.mockAbort();
try {
const cli = new APIClient({
origin: "https://misskey.test",
credential: "TOKEN",
});
await cli.request("i");
} catch (e) {
expect(isAPIError(e)).toEqual(false);
}
});
test("json parse error", async () => {
fetchMock.resetMocks();
fetchMock.mockResponse(async (req) => {
return {
status: 500,
body: "<html>I AM NOT JSON</html>",
};
});
try {
const cli = new APIClient({
origin: "https://misskey.test",
credential: "TOKEN",
});
await cli.request("i");
} catch (e) {
expect(isAPIError(e)).toEqual(false);
}
});
});

View file

@ -0,0 +1,181 @@
import WS from "jest-websocket-mock";
import Stream from "../src/streaming";
describe("Streaming", () => {
test("useChannel", async () => {
const server = new WS("wss://misskey.test/streaming");
const stream = new Stream("https://misskey.test", { token: "TOKEN" });
const mainChannelReceived: any[] = [];
const main = stream.useChannel("main");
main.on("meUpdated", (payload) => {
mainChannelReceived.push(payload);
});
const ws = await server.connected;
expect(new URLSearchParams(new URL(ws.url).search).get("i")).toEqual(
"TOKEN",
);
const msg = JSON.parse((await server.nextMessage) as string);
const mainChannelId = msg.body.id;
expect(msg.type).toEqual("connect");
expect(msg.body.channel).toEqual("main");
expect(mainChannelId != null).toEqual(true);
server.send(
JSON.stringify({
type: "channel",
body: {
id: mainChannelId,
type: "meUpdated",
body: {
id: "foo",
},
},
}),
);
expect(mainChannelReceived[0]).toEqual({
id: "foo",
});
stream.close();
server.close();
});
test("useChannel with parameters", async () => {
const server = new WS("wss://misskey.test/streaming");
const stream = new Stream("https://misskey.test", { token: "TOKEN" });
const messagingChannelReceived: any[] = [];
const messaging = stream.useChannel("messaging", { otherparty: "aaa" });
messaging.on("message", (payload) => {
messagingChannelReceived.push(payload);
});
const ws = await server.connected;
expect(new URLSearchParams(new URL(ws.url).search).get("i")).toEqual(
"TOKEN",
);
const msg = JSON.parse((await server.nextMessage) as string);
const messagingChannelId = msg.body.id;
expect(msg.type).toEqual("connect");
expect(msg.body.channel).toEqual("messaging");
expect(msg.body.params).toEqual({ otherparty: "aaa" });
expect(messagingChannelId != null).toEqual(true);
server.send(
JSON.stringify({
type: "channel",
body: {
id: messagingChannelId,
type: "message",
body: {
id: "foo",
},
},
}),
);
expect(messagingChannelReceived[0]).toEqual({
id: "foo",
});
stream.close();
server.close();
});
test("ちゃんとチャンネルごとにidが異なる", async () => {
const server = new WS("wss://misskey.test/streaming");
const stream = new Stream("https://misskey.test", { token: "TOKEN" });
stream.useChannel("messaging", { otherparty: "aaa" });
stream.useChannel("messaging", { otherparty: "bbb" });
const ws = await server.connected;
expect(new URLSearchParams(new URL(ws.url).search).get("i")).toEqual(
"TOKEN",
);
const msg = JSON.parse((await server.nextMessage) as string);
const messagingChannelId = msg.body.id;
const msg2 = JSON.parse((await server.nextMessage) as string);
const messagingChannelId2 = msg2.body.id;
expect(messagingChannelId != null).toEqual(true);
expect(messagingChannelId2 != null).toEqual(true);
expect(messagingChannelId).not.toEqual(messagingChannelId2);
stream.close();
server.close();
});
test("Connection#send", async () => {
const server = new WS("wss://misskey.test/streaming");
const stream = new Stream("https://misskey.test", { token: "TOKEN" });
const messaging = stream.useChannel("messaging", { otherparty: "aaa" });
messaging.send("read", { id: "aaa" });
const ws = await server.connected;
expect(new URLSearchParams(new URL(ws.url).search).get("i")).toEqual(
"TOKEN",
);
const connectMsg = JSON.parse((await server.nextMessage) as string);
const channelId = connectMsg.body.id;
const msg = JSON.parse((await server.nextMessage) as string);
expect(msg.type).toEqual("ch");
expect(msg.body.id).toEqual(channelId);
expect(msg.body.type).toEqual("read");
expect(msg.body.body).toEqual({ id: "aaa" });
stream.close();
server.close();
});
test("Connection#dispose", async () => {
const server = new WS("wss://misskey.test/streaming");
const stream = new Stream("https://misskey.test", { token: "TOKEN" });
const mainChannelReceived: any[] = [];
const main = stream.useChannel("main");
main.on("meUpdated", (payload) => {
mainChannelReceived.push(payload);
});
const ws = await server.connected;
expect(new URLSearchParams(new URL(ws.url).search).get("i")).toEqual(
"TOKEN",
);
const msg = JSON.parse((await server.nextMessage) as string);
const mainChannelId = msg.body.id;
expect(msg.type).toEqual("connect");
expect(msg.body.channel).toEqual("main");
expect(mainChannelId != null).toEqual(true);
main.dispose();
server.send(
JSON.stringify({
type: "channel",
body: {
id: mainChannelId,
type: "meUpdated",
body: {
id: "foo",
},
},
}),
);
expect(mainChannelReceived.length).toEqual(0);
stream.close();
server.close();
});
// TODO: SharedConnection#dispose して一定時間経ったら disconnect メッセージがサーバーに送られてくるかのテスト
// TODO: チャンネル接続が使いまわされるかのテスト
});

View file

@ -0,0 +1,25 @@
{
"$schema": "http://json.schemastore.org/tsconfig",
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"outDir": "./built/",
"removeComments": true,
"strict": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"experimentalDecorators": true,
"noImplicitReturns": true,
"esModuleInterop": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"test/**/*"
]
}

View file

@ -33,7 +33,7 @@
"blurhash": "1.1.5",
"broadcast-channel": "4.19.1",
"browser-image-resizer": "https://github.com/misskey-dev/browser-image-resizer.git",
"calckey-js": "^0.0.22",
"calckey-js": "workspace:*",
"chart.js": "4.1.1",
"chartjs-adapter-date-fns": "2.0.1",
"chartjs-chart-matrix": "^2.0.1",

View file

@ -87,6 +87,9 @@ export default defineConfig(({ command, mode }) => {
emptyOutDir: false,
sourcemap: process.env.NODE_ENV === "development",
reportCompressedSize: false,
commonjsOptions: {
include: [/calckey-js/, /node_modules/],
},
},
optimizeDeps: {
auto: true,

View file

@ -13,7 +13,7 @@
"@swc/cli": "^0.1.59",
"@swc/core": "^1.3.26",
"@swc/core-android-arm64": "1.3.11",
"calckey-js": "^0.0.22",
"calckey-js": "workspace:*",
"idb-keyval": "^6.2.0",
"swc-loader": "^0.2.3",
"webpack": "^5.75.0",

File diff suppressed because it is too large Load diff

View file

@ -2,3 +2,4 @@ packages:
- 'packages/backend'
- 'packages/client'
- 'packages/sw'
- 'packages/calckey-js'