Collaboration-facing API documentation aligned with the current frontend codebase
Language: English | 中文
This document describes the actual API organization inside project/src/api in the frontend repository. It is not meant to be a complete backend endpoint catalog.
Use this file when you are adding frontend features, extending API modules, or building a new standalone page or sub-application inside this repo.
Frontend API code lives under project/src/api/ and is currently split into a shared authentication layer, the main-site business layer, a VillagesML-specific layer, and a small logging layer:
project/src/api/
├── auth/ # login, register, session, token, HTTP client
├── main/
│ ├── core/ # core search and phonology analysis
│ ├── geo/ # locations, regions, coordinates
│ ├── sql/ # SQL querying and mutations
│ ├── tools/ # merge / check / jyut2ipa / praat
│ └── user/ # user custom data and custom regions
├── villagesML/ # natural-village analysis APIs
├── logs/ # visit and usage stats
└── index.js # global aggregated export surface
For most pages and components, prefer importing from @/api instead of reaching into deep files from view code.
import {
searchChars,
getLocations,
loginUser,
ensureAuthenticated,
getSpatialHotspots
} from '@/api'project/src/api/index.js is the repository-wide import surface. Main-site pages, VillagesML workspace modules, and future standalone modules should normally consume APIs from there.
Typical consumers:
- view pages
- business components
- composables
- workspace modules
These sub-entries still exist and are useful when you are organizing API code itself:
project/src/api/auth/index.jsproject/src/api/main/core/index.jsproject/src/api/main/geo/index.jsproject/src/api/main/sql/index.jsproject/src/api/main/tools/index.jsproject/src/api/main/user/index.jsproject/src/api/villagesML/index.js
Use them when you are developing or reorganizing API layers, or when a subsystem intentionally stays self-contained.
Requests are normalized through api() in project/src/api/auth/httpClient.js. That layer builds URLs from WEB_BASE and already handles:
- auth token injection
- token refresh
- timeout and network failures
- normalized HTTP errors
- rate-limit notices
Component code should not assemble https://.../api/... strings directly.
Authentication and session management live in project/src/api/auth/.
auth.js: session bootstrap and helper re-exportsactions.js: login, register, profile updates, logout, leaderboardhttpClient.js: shared request client and error normalizationsession.js: refresh flow, auth bootstrap, online-time reportingtokenStorage.js: token and user-cache persistencevalidation.js: auth form validation helpers
import {
loginUser,
registerUser,
logoutUser,
updateUsername,
updatePassword,
getLeaderboard,
bootstrapAuthSession,
ensureAuthenticated,
waitForAuthReady,
reportOnlineTime,
getUserRole,
validateEmail,
validateUsername,
validatePassword,
validatePasswordMatch
} from '@/api'- Login, registration, and profile screens should call
loginUser,registerUser,updateUsername, andupdatePassworddirectly - Protected features should reuse the existing auth/session flow instead of recreating local token checks
- If a new sub-app requires authentication, reuse
src/api/authand the existing route/page guard approach rather than building another auth client
import { ensureAuthenticated, loginUser } from '@/api'
await ensureAuthenticated()
await loginUser({
username: 'demo',
password: 'secret'
})project/src/api/main/ powers the main site and shared query pages. It is currently split into five areas.
Core phonology, comparison, and matrix analysis APIs.
Common exports:
searchCharssearchZhongGusearchYinWeisearchTonesgetCharListgetFeatureCountsgetFeatureStatsgetPhonologyMatrixgetPhonologyClassificationMatrixqueryPhonologypostPhoPieByValuepostPhoPieByStatuscompareCharscompareZhongGucompareTones
Location, region, and coordinate helpers.
Common exports:
getLocationsgetLocationDetailgetLocationPartitionsbatchMatchgetPartitionsgetRegionsgetCoordinates
SQL querying, mutations, and tree-loading helpers.
Common exports:
sqlQuerydistinctQuerygetTableColumnsqueryCountmutateSingleRowbatchMutatebatchReplacePreviewbatchReplaceExecutelazyLoadTreeloadFullTree
APIs for the main-site tools, currently split by tool:
merge.js: table mergecheck.js: table validation/checkingjyut2ipa.js: Jyutping-to-IPA conversionPraat.js: Praat acoustic analysis
Common exports:
uploadReferenceuploadFilesexecuteMergegetMergeProgressdownloadMergeuploadCheckFileanalyzeFilegetToneStatsgetTableDataupdateRowbatchDeleteexecuteBatchOperationdownloadCheckResultuploadJyutFileprocessJyut2IpagetJyut2IpaProgressdownloadJyut2IpaResultpraatusePraatApi
Main-site user-owned custom data and custom-region APIs.
This area is currently split across:
custom-data.jscustom.jscustom-regions.js
Common exports:
getAllCustomDataeditCustomDatabatchCreateCustomDatabatchDeleteCustomDatagetCustomDatagetCustomFeaturesubmitCustomFormdeleteCustomFormgetCustomRegionscreateOrUpdateCustomRegiondeleteCustomRegion
project/src/api/villagesML/ is the dedicated API layer for the natural-village ML workspace. It is already clearly separated from the main-site API surface and should be treated as the reference pattern for future standalone analytical sub-apps.
villages.js: village search and single-village detailcharacters.js: frequency, tendency, embeddings, significanceclustering.js: clustering jobs, status, cacheclusteringTypes.js: algorithm-specific clustering entry pointssemantic.js: semantic networksemanticCategories.js: semantic categories and subcategoriessemanticLabels.js: semantic labels and combination patternssemanticComposition.js: composition statistics and PMIspatial.js: hotspots, spatial clustering, integrationngrams.js: n-gram analysispatterns.js: structural patternsregional.js: regional aggregates and vector comparisonscompute.js: feature extraction and subset comparisonmetadata.js: table and database metadataregionSimilarity.js: region similarity
import {
searchVillages,
getGlobalCharFrequency,
runClustering,
getSemanticNetwork,
getSpatialHotspots,
getRegionSimilarityMatrix,
extractFeatures,
aggregateFeatures
} from '@/api'VillagesML shows the preferred pattern when a sub-application has:
- a clear product boundary
- its own route space
- many dedicated analytical APIs
In that situation, APIs should live under project/src/api/<ModuleName>/ instead of being folded back into project/src/api/main/.
Current exports:
getTodayVisitsgetTotalVisitsgetVisitHistory
project/src/api/index.js also forwards URL helpers from project/src/utils/urlParams.js:
decodeParamsbuildQueryUrlcopyCurrentUrlgetUrlSegmentValue
These are not HTTP APIs, but they are intentionally exposed through the same import surface because multiple query/share flows reuse them.
The frontend API layer already encodes a consistent request contract. New APIs should follow it.
api() normalizes failures into Error objects with additional fields such as:
kindstatusdatadetailheadersrawText
Callers should prefer consuming this normalized error shape instead of rebuilding response parsing in view code.
The request layer proactively checks whether the token is expired or close to expiring, and refreshes when needed. Protected APIs should rely on this shared flow rather than duplicating refresh logic.
The shared client already handles:
- request timeout aborts
- JSON / text / blob response parsing
- 429 notice payload construction
New APIs should build on that client rather than using ad hoc fetch calls inside components.
- Main-site shared query/tool/geo/sql/user features:
project/src/api/main/ - Auth, token, session work:
project/src/api/auth/ VillagesML-specific functionality:project/src/api/villagesML/- New standalone sub-app:
project/src/api/<ModuleName>/
If a new module is login-protected, reuse:
project/src/api/auth/- the existing session/token flow
- the current route or page guard approach
Do not clone a second token storage or refresh system for one module.
- If the API is only temporary or module-internal, it can stay inside its own entry
- If it becomes a stable cross-page or cross-subsystem dependency, add it to
project/src/api/index.js - Before exporting globally, check for naming collisions
API functions currently use camelCase naming, for example:
getSpatialHotspotsgetRegionSimilarityMatrixbatchCompareRegionalVectorscreateOrUpdateCustomRegion
New functions should follow the same style.
import { searchChars, getLocations } from '@/api'
const locations = await getLocations()
const rows = await searchChars({
chars: '你好',
locations: ['廣州'],
regions: [],
region_mode: 'full'
})import { ensureAuthenticated, waitForAuthReady } from '@/api'
await waitForAuthReady()
await ensureAuthenticated()import {
getSemanticNetwork,
getSpatialHotspots,
getRegionSimilarityPair
} from '@/api'
const network = await getSemanticNetwork(params)
const hotspots = await getSpatialHotspots(params)
const pair = await getRegionSimilarityPair(params)- Overall project structure: README.md and ARCHITECTURE.md
VillagesMLmodule docs:docs/VillagesML/- Collaboration rules for adding a new standalone page/app: CONTRIBUTING.md
If a future module such as PhoneticToolbox is added, its APIs should generally live under project/src/api/PhoneticToolbox/, reuse the existing auth layer, and only be promoted into the global @/api surface when that sharing is intentional.