### Install and Import SDK Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Clone the repository, install dependencies, and import the Locket class. This setup is for local development before potential npm publishing. ```bash git clone cd locket-api npm install ``` ```typescript import { Locket } from "./src"; ``` -------------------------------- ### Locket API Quick Start Example Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Demonstrates the basic workflow of signing in, fetching friends' latest moments, and reacting to a moment using the Locket API. ```typescript import { Locket, LocketError, type GetLatestMomentsResponse, type ReactToMomentResponse, } from "locket-api"; const locket = new Locket(); // 1) Sign in await locket.signInWithEmail("you@example.com", "password"); // 2) Browse your friends' latest moments const friends: string[] = await locket.listFriends(); const feed: GetLatestMomentsResponse = await locket.getLatestMoments(friends); // 3) React to the first one with any text (emoji or plain text) const moment = feed.result.data[0]; if (moment) { const res: ReactToMomentResponse = await locket.react(moment.canonical_uid, "Nice!"); if (res.result.status !== 200) { console.warn("react failed:", res.result.errors); } } ``` -------------------------------- ### Clone and Install Locket API SDK Source: https://github.com/jumpogpo/locket-api/blob/main/packages/locket-api/README.md Clone the repository and install dependencies to set up the SDK locally. This includes installing runtime and development dependencies. ```bash git clone cd locket-api npm install ``` -------------------------------- ### Development and Build Commands Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Common commands for installing dependencies, running the development server, building the project, and type checking. ```bash npm install # runtime + dev deps (axios is the only runtime dep) npm run dev # tsx watch examples/playground.ts (hot reload) npm start # tsx examples/playground.ts (one-shot) npm run build # emits ./dist (CJS + .d.ts) npm run build:watch # tsc --watch npm run typecheck # tsc --noEmit ``` -------------------------------- ### Import Locket Class in TypeScript Source: https://github.com/jumpogpo/locket-api/blob/main/packages/locket-api/README.md Import the Locket class from the local SDK path after installation. This allows you to start using the SDK in your TypeScript project. ```typescript import { Locket } from "./src"; ``` -------------------------------- ### Get Account Info Source: https://github.com/jumpogpo/locket-api/blob/main/packages/locket-api/README.md Retrieves account information for the authenticated user. A shorthand `getMe()` is available for the primary user. ```APIDOC ## getAccountInfo(idToken?) ### Description Retrieves account information for the authenticated user. A shorthand `getMe()` is available for the primary user. ### Method POST ### Endpoint `https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo` ### Parameters #### Request Body - **idToken** (string) - Optional - The ID token. If not provided, the stored ID token is used. ### Request Example ```ts const info = await locket.getAccountInfo(); info.users[0]?.localId; info.users[0]?.customAttributes; // e.g. '{"revenueCatEntitlements":["Gold"]}' const me = await locket.getMe(); me?.localId; me?.email; me?.phoneNumber; me?.lastRefreshAt; ``` ### Response #### Success Response (200) - **users** (array) - An array of user objects. - **localId** (string) - The user's unique identifier. - **customAttributes** (string) - Custom attributes associated with the user. ### Failure Throws `LocketError` (HTTP 400, `INVALID_ID_TOKEN`). ``` -------------------------------- ### ReactToMomentResponse Structure Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Example response structures for `reactToMoment`. Status 200 indicates success. Status 401 indicates insufficient access. ```json // status: 200 → success { result: { data: ["S5OkJabkyqK47v34YQRw"], status: 200 } } // status: 401 → not your friend / not signed in { result: { errors: ["You don't have access to this moment"], status: 401, }, } ``` -------------------------------- ### Get Account Information Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Retrieves account information using the ID token. The `getMe()` shorthand provides direct access to the first user's details. ```typescript const info = await locket.getAccountInfo(); info.users[0]?.localId; info.users[0]?.customAttributes; // e.g. '{"revenueCatEntitlements":["Gold"]}' ``` ```typescript const me = await locket.getMe(); me?.localId; me?.email; me?.phoneNumber; me?.lastRefreshAt; ``` -------------------------------- ### GetMomentViewsResponse Structure Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Example response structures for `getMomentViews`. Status 200 indicates success. Status 404 means the moment does not exist, and 401 means you are not the owner. ```json // status: 200 { result: { data: { moment_views: [/* MomentView[] */], count: 0 }, status: 200 } } // status: 404 → moment_uid does not exist { result: { errors: ["Moment not found"], status: 404 } } // status: 401 → the moment exists but you are not its owner { result: { errors: ["User does not have access to this moment"], status: 401 } } ``` -------------------------------- ### GetLatestMomentsResponse Structure Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Example response structures for `getLatestMoments`. Status 200 indicates new moments, while status 304 means no new moments since the provided `syncToken`. ```json // status: 200 → new moments are in result.data { result: { data: [{ canonical_uid: "0Xu4LoJHqArMknW6pisT", // use this for react / delete user: "5gGjaYuwU3Uw0qUMqVBTK5tMKy82", date: { _seconds: 1779795374, _nanoseconds: 712000000 }, md5: "a6949936ec4f0052847abf8afc63b339", thumbnail_url: "https://firebasestorage.googleapis.com/.../thumb.webp", // image_url / video_url / caption / overlays / reactions when present }], missed_moments_count: 0, sync_token: "0Xu4LoJHqArMknW6pisT", status: 200, }, } // status: 304 → nothing new since the sync_token { result: { data: [], status: 304 } } ``` -------------------------------- ### Auth: getSession / setSession / isAuthenticated / signOut Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Provides methods for managing the user's session state in memory, including getting, setting, checking authentication status, and signing out. ```APIDOC ## getSession() ## setSession(s) ## isAuthenticated() ## signOut() ### Description Manages the user's session state. These operations are performed in-memory. ### Method Various (In-memory operations) ### Endpoint (in-memory) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **setSession**: Requires a session object `s`. ``` -------------------------------- ### Get Moment Views Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Retrieve the list of users who viewed one of your moments. This feature requires Locket Gold. The SDK does not enforce subscription tiers. ```typescript const res = await locket.getMomentViews("QmNChcRmMwIZaMixQnG8"); ``` -------------------------------- ### DeleteMomentResponse Structure Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Example response for `deleteMoment`. Success is indicated by the presence of the `moment_uid` in `result.data`. Failures are reported in `result.errors`. ```json // Success — note: no `status` field { result: { data: ["mKPhGseit5sdWTotqoIr"] } } // Failure { result: { errors: ["..."], status: 401 } } ``` -------------------------------- ### Get Moment Views Response Structure Source: https://github.com/jumpogpo/locket-api/blob/main/packages/locket-api/README.md A successful response (status 200) contains `moment_views` and `count`. Failures include a 404 if the moment doesn't exist or 401 if you are not the owner. ```json { result: { data: { moment_views: [/* MomentView[] */], count: 0 }, status: 200 } } ``` ```json { result: { errors: ["Moment not found"], status: 404 } } ``` ```json { result: { errors: ["User does not have access to this moment"], status: 401 } } ``` -------------------------------- ### Initialize Locket Client with Options Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Configure the Locket client with session details, timeouts, custom user agents, default headers, authentication parameters, and friend-related settings. ```typescript new Locket({ session: { idToken, refreshToken }, // restore a previous session timeout: 20_000, // axios timeout in ms (default 30s) userAgent: "MyApp/1.0", // overrides default iOS UA defaultHeaders: { "x-app": "myapp" }, // attached to every request auth: { firebaseApiKey: "AIza...", // override Locket's public key iosBundleId: "com.example.MyApp", clientType: "CLIENT_TYPE_ANDROID", // default is CLIENT_TYPE_IOS }, friends: { projectId: "locket-4252a", // Firestore project id }, }); ``` -------------------------------- ### Get Latest Moments Source: https://github.com/jumpogpo/locket-api/blob/main/packages/locket-api/README.md Retrieve the latest moments from friends or specific users. Supports pagination and exclusions. Use `lastFetch` to get moments since a specific time and `syncToken` for incremental updates. ```typescript const feed = await locket.getLatestMoments(); ``` ```typescript const feed = await locket.getLatestMoments(["FRIEND_UID_1"], { excludedUsers: ["BLOCKED_UID"], lastFetch: Date.now() - 24 * 60 * 60 * 1000, syncToken: "psSVRI9EWZ5sNMLu9PzQ", shouldCountMissedMoments: true, }); ``` -------------------------------- ### Project File Structure Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Overview of the Locket API project's directory and file organization. ```bash src/ ├── index.ts # public entry ├── locket.ts # Locket — the single class users interact with ├── http.ts # axios wrapper + auth interceptor ├── session.ts # in-memory SessionStore ├── errors.ts # LocketError ├── utils.ts # int64 + JWT decoder ├── constants.ts ├── modules/ # internal — one file per endpoint group │ ├── auth.ts │ ├── moments.ts │ ├── users.ts │ └── friends.ts └── types/ ├── auth.ts ├── moment.ts ├── user.ts └── common.ts ``` -------------------------------- ### Authentication Methods Source: https://github.com/jumpogpo/locket-api/blob/main/packages/locket-api/README.md Methods for signing in and managing user sessions. ```APIDOC ## signInWithEmail ### Description Signs in a user using their email and password. ### Method POST ### Endpoint /verifyPassword (Google IDT) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **email** (string) - Required - User's email address. - **password** (string) - Required - User's password. ### Request Example ```json { "email": "you@example.com", "password": "password" } ``` ### Response #### Success Response (200) Details of the authenticated user session. #### Response Example ```json { "result": { "status": 200, "data": { ... } } } ``` ``` ```APIDOC ## signInWithPhone ### Description Signs in a user using their phone number and password. ### Method POST ### Endpoint /signInWithPhonePassword + /verifyCustomToken (Google IDT) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **phone** (string) - Required - User's phone number. - **password** (string) - Required - User's password. ### Request Example ```json { "phone": "+1234567890", "password": "password" } ``` ### Response #### Success Response (200) Details of the authenticated user session. #### Response Example ```json { "result": { "status": 200, "data": { ... } } } ``` ``` ```APIDOC ## signInWithPhonePassword ### Description Authenticates a user with their phone number and password. ### Method POST ### Endpoint /signInWithPhonePassword ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **phone** (string) - Required - User's phone number. - **password** (string) - Required - User's password. ### Request Example ```json { "phone": "+1234567890", "password": "password" } ``` ### Response #### Success Response (200) Authentication token and user information. #### Response Example ```json { "result": { "status": 200, "data": { ... } } } ``` ``` ```APIDOC ## exchangeCustomToken ### Description Exchanges a custom authentication token for a Google ID token. ### Method POST ### Endpoint /verifyCustomToken (Google IDT) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **customToken** (string) - Required - The custom token to exchange. ### Request Example ```json { "customToken": "your_custom_token" } ``` ### Response #### Success Response (200) Google ID token and related information. #### Response Example ```json { "result": { "status": 200, "data": { ... } } } ``` ``` ```APIDOC ## refreshToken ### Description Refreshes an existing authentication token. ### Method POST ### Endpoint /securetoken/v1/token ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **refreshToken** (string) - Optional - The refresh token to use. ### Request Example ```json { "refreshToken": "your_refresh_token" } ``` ### Response #### Success Response (200) New access token and refresh token. #### Response Example ```json { "result": { "status": 200, "data": { ... } } } ``` ``` ```APIDOC ## getAccountInfo ### Description Retrieves account information for the authenticated user. ### Method POST ### Endpoint /getAccountInfo (Google IDT) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **idToken** (string) - Optional - The ID token for authentication. ### Request Example ```json { "idToken": "your_id_token" } ``` ### Response #### Success Response (200) Detailed account information. #### Response Example ```json { "result": { "status": 200, "data": { ... } } } ``` ``` ```APIDOC ## getMe ### Description Retrieves the current authenticated user's information. ### Method POST ### Endpoint /getAccountInfo (Google IDT) ### Parameters None ### Response #### Success Response (200) Information about the current user. #### Response Example ```json { "result": { "status": 200, "data": { ... } } } ``` ``` ```APIDOC ## getSession ### Description Retrieves the current in-memory session data. ### Method (in-memory) ### Endpoint (in-memory) ### Parameters None ### Response #### Success Response In-memory session object. #### Response Example ```json { "session": { ... } } ``` ``` ```APIDOC ## setSession ### Description Sets the current in-memory session data. ### Method (in-memory) ### Endpoint (in-memory) ### Parameters #### Request Body - **s** (object) - Required - The session object to set. ### Request Example ```json { "session": { ... } } ``` ### Response None ``` ```APIDOC ## isAuthenticated ### Description Checks if the user is currently authenticated. ### Method (in-memory) ### Endpoint (in-memory) ### Parameters None ### Response #### Success Response Boolean indicating authentication status. #### Response Example ```json { "isAuthenticated": true } ``` ``` ```APIDOC ## signOut ### Description Logs the user out and clears the session. ### Method (in-memory) ### Endpoint (in-memory) ### Parameters None ### Response None ``` -------------------------------- ### getMe Source: https://github.com/jumpogpo/locket-api/blob/main/README.md A shorthand for retrieving the first user's information from the result of `getAccountInfo()`. ```APIDOC ## getMe() ### Description A shorthand for retrieving the first user's information from the result of `getAccountInfo()`. ### Method POST (internally calls `getAccountInfo`) ### Endpoint (See `getAccountInfo` for the underlying endpoint) ### Request Example ```ts const me = await locket.getMe(); me?.localId; me?.email; me?.phoneNumber; me?.lastRefreshAt; ``` ### Response #### Success Response (200) - Returns the first user object from the `getAccountInfo` response, or null if no user is found. - **localId** (string) - User's unique ID. - **email** (string) - User's email address. - **phoneNumber** (string) - User's phone number. - **lastRefreshAt** (string) - Timestamp of the last refresh. ### Failure - Throws `LocketError` if `getAccountInfo` fails. ``` -------------------------------- ### signInWithEmail Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Authenticates a user with email and password. This performs a single HTTP call to verify the password and populates the session. ```APIDOC ## signInWithEmail(email, password) ### Description Authenticates a user with email and password. This performs a single HTTP call to verify the password and populates the session. ### Method POST ### Endpoint https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ### Request Example ```ts const res = await locket.signInWithEmail("you@example.com", "password"); ``` ### Response #### Success Response (200) - **EmailSignInResponse** (object) - Contains user information and tokens upon successful sign-in. - **kind** (string) - "identitytoolkit#VerifyPasswordResponse" - **localId** (string) - User ID. - **email** (string) - User's email. - **displayName** (string) - User's display name. - **idToken** (string) - Bearer token with 1-hour TTL. - **refreshToken** (string) - Refresh token. - **profilePicture** (string) - URL to the user's profile picture. - **registered** (boolean) - Indicates if the user is registered. - **expiresIn** (string) - Duration in seconds for which the `idToken` is valid (e.g., "3600"). ### Response Example ```json { "kind": "identitytoolkit#VerifyPasswordResponse", "localId": "4YUPPNLIobR0ieQnH1V8DU7ZCVq1", "email": "you@example.com", "displayName": "Chokun ㅤ", "idToken": "eyJhbGciOi…", "refreshToken": "AMf-vBxq…", "profilePicture": "https://firebasestorage.googleapis.com/.../profile_pic.webp", "registered": true, "expiresIn": "3600" } ``` ### Failure - Throws `LocketError` (HTTP 400, e.g. `INVALID_PASSWORD`, `EMAIL_NOT_FOUND`). ``` -------------------------------- ### User Methods Source: https://github.com/jumpogpo/locket-api/blob/main/packages/locket-api/README.md Methods for fetching user information. ```APIDOC ## fetchUser ### Description Fetches detailed information about a specific user. ### Method POST ### Endpoint /fetchUserV2 ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **userUid** (string) - Required - The unique identifier of the user to fetch. ### Request Example ```json { "userUid": "user123" } ``` ### Response #### Success Response (200) Detailed information about the specified user. #### Response Example ```json { "result": { "status": 200, "data": { ... } } } ``` ``` -------------------------------- ### Get Latest Moments Response Structure Source: https://github.com/jumpogpo/locket-api/blob/main/packages/locket-api/README.md The response for `getLatestMoments` indicates new moments in `result.data` with a status of 200, or no new moments with a status of 304. ```json { result: { data: [{ canonical_uid: "0Xu4LoJHqArMknW6pisT", // use this for react / delete user: "5gGjaYuwU3Uw0qUMqVBTK5tMKy82", date: { _seconds: 1779795374, _nanoseconds: 712000000 }, md5: "a6949936ec4f0052847abf8afc63b339", thumbnail_url: "https://firebasestorage.googleapis.com/.../thumb.webp", // image_url / video_url / caption / overlays / reactions when present }], missed_moments_count: 0, sync_token: "0Xu4LoJHqArMknW6pisT", status: 200, }, } ``` ```json { result: { data: [], status: 304 } } ``` -------------------------------- ### Sign In with Email Source: https://github.com/jumpogpo/locket-api/blob/main/packages/locket-api/README.md Authenticates a user using their email and password. This is a single HTTP call that populates the session. ```APIDOC ## signInWithEmail(email, password) ### Description Authenticates a user using their email and password. This is a single HTTP call that populates the session. ### Method POST ### Endpoint `https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword` ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ### Request Example ```ts const res = await locket.signInWithEmail("you@example.com", "password"); ``` ### Response #### Success Response (200) - **kind** (string) - Indicates the type of response. - **localId** (string) - The user's unique identifier. - **email** (string) - The user's email address. - **displayName** (string) - The user's display name. - **idToken** (string) - The authentication token (1-hour TTL). - **refreshToken** (string) - The token used to refresh the session. - **profilePicture** (string) - URL to the user's profile picture. - **registered** (boolean) - Indicates if the user is registered. - **expiresIn** (string) - The duration in seconds for which the ID token is valid. #### Response Example ```json { "kind": "identitytoolkit#VerifyPasswordResponse", "localId": "4YUPPNLIobR0ieQnH1V8DU7ZCVq1", "email": "you@example.com", "displayName": "Chokun ㅤ", "idToken": "eyJhbGciOi…", "refreshToken": "AMf-vBxq…", "profilePicture": "https://firebasestorage.googleapis.com/.../profile_pic.webp", "registered": true, "expiresIn": "3600" } ``` ### Failure Throws `LocketError` (HTTP 400, e.g. `INVALID_PASSWORD`, `EMAIL_NOT_FOUND`). ``` -------------------------------- ### Session helpers Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Provides utility functions for managing the user's authentication session. ```APIDOC ## Session Helpers ### Description Provides utility functions for managing the user's authentication session. ### Methods - **`isAuthenticated()`**: Returns `true` if the user is authenticated, `false` otherwise. - **`getSession()`**: Returns the current `AuthSession` object or `null` if not authenticated. - **`setSession({ idToken, refreshToken })`**: Sets the user's session with the provided tokens. - **`signOut()`**: Clears the current user session. ### `AuthSession` Shape ```ts { idToken: string; refreshToken: string; expiresIn?: string; // "3600" expiresAt?: number; // Date.now() + expiresIn*1000 — computed for you uid?: string; } ``` ### Auto-refresh Pattern Example ```ts async function ensureFresh(locket: Locket) { const s = locket.getSession(); if (!s) throw new Error("Not signed in"); // Refresh if the token will expire in less than 60 seconds if (s.expiresAt && s.expiresAt - Date.now() < 60_000) { await locket.refreshToken(); } } ``` ``` -------------------------------- ### Email Sign-In with Password Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Performs an email and password sign-in using a single HTTP call. Populates the session upon successful authentication. ```typescript const res = await locket.signInWithEmail("you@example.com", "password"); ``` ```json { kind: "identitytoolkit#VerifyPasswordResponse", localId: "4YUPPNLIobR0ieQnH1V8DU7ZCVq1", // uid email: "you@example.com", displayName: "Chokun ㅤ", idToken: "eyJhbGciOi…", // Bearer token (1 h TTL) refreshToken: "AMf-vBxq…", profilePicture: "https://firebasestorage.googleapis.com/.../profile_pic.webp", registered: true, expiresIn: "3600", } ``` -------------------------------- ### Moments Methods Source: https://github.com/jumpogpo/locket-api/blob/main/packages/locket-api/README.md Methods for retrieving and interacting with user moments. ```APIDOC ## getLatestMoments ### Description Retrieves the latest moments from a list of users. ### Method POST ### Endpoint /getLatestMomentV2 ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **users** (array) - Optional - A list of user IDs to fetch moments from. - **options** (object) - Optional - Additional options for fetching moments. ### Request Example ```json { "users": ["user1", "user2"], "options": { "limit": 10 } } ``` ### Response #### Success Response (200) A list of the latest moments. #### Response Example ```json { "result": { "status": 200, "data": [ { "canonical_uid": "moment123", "content": "Hello!", "timestamp": "2023-10-27T10:00:00Z" } ] } } ``` ``` ```APIDOC ## react ### Description Adds a reaction to a specific moment. ### Method POST ### Endpoint /reactToMoment ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **momentUid** (string) - Required - The unique identifier of the moment. - **reaction** (string) - Required - The reaction text or emoji. ### Request Example ```json { "momentUid": "moment123", "reaction": "👍" } ``` ### Response #### Success Response (200) Status of the reaction operation. #### Response Example ```json { "result": { "status": 200, "errors": [] } } ``` ``` ```APIDOC ## deleteMoment ### Description Deletes a specific moment. ### Method POST ### Endpoint /deleteMomentV2 ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **momentUid** (string) - Required - The unique identifier of the moment to delete. - **ownerUid** (string) - Required - The unique identifier of the moment's owner. - **deleteGlobally** (boolean) - Optional - Whether to delete the moment globally. ### Request Example ```json { "momentUid": "moment123", "ownerUid": "user456", "deleteGlobally": false } ``` ### Response #### Success Response (200) Status of the delete operation. #### Response Example ```json { "result": { "status": 200 } } ``` ``` ```APIDOC ## getMomentViews ### Description Retrieves the view count for a specific moment. Requires Locket Gold. ### Method POST ### Endpoint /getMomentViews ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **momentUid** (string) - Required - The unique identifier of the moment. ### Request Example ```json { "momentUid": "moment123" } ``` ### Response #### Success Response (200) Information about the moment's views. #### Response Example ```json { "result": { "status": 200, "data": { "views": 100 } } } ``` ``` -------------------------------- ### Sign In with Phone Source: https://github.com/jumpogpo/locket-api/blob/main/packages/locket-api/README.md Authenticates a user using their phone number and password. This involves two underlying API calls and returns both raw bodies. ```APIDOC ## signInWithPhone(phone, password) ### Description Authenticates a user using their phone number and password. This involves two underlying API calls and returns both raw bodies. The session is populated, and the `uid` is extracted from the resulting JWT. ### Method POST (two calls) ### Endpoint 1. `https://api.locketcamera.com/signInWithPhonePassword` 2. `https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken` ### Parameters #### Request Body - **phone** (string) - Required - The user's phone number. - **password** (string) - Required - The user's password. ### Request Example ```ts const { phone, identity } = await locket.signInWithPhone("+66xxxxxxxxx", "password"); phone.result.token; // raw Firebase custom token identity.idToken; // Bearer token identity.refreshToken; identity.expiresIn; identity.isNewUser; ``` ### Response #### Success Response (200) Returns an object containing results from both underlying calls: - **phone.result.token** (string) - The raw Firebase custom token. - **identity.idToken** (string) - The authentication token. - **identity.refreshToken** (string) - The token used to refresh the session. - **identity.expiresIn** (string) - The duration in seconds for which the ID token is valid. - **identity.isNewUser** (boolean) - Indicates if the user is new. ### Failure Locket responds HTTP 200 with `phone.result.status !== 200` and no `token`. The SDK throws `LocketError` with the original body attached. ``` -------------------------------- ### Configure Locket Constructor Options Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Override default SDK values by passing configuration options to the Locket constructor. This includes setting the User-Agent, Firebase API key, and Firestore project ID. ```javascript new Locket({ userAgent }) new Locket({ auth: { iosBundleId } }) new Locket({ auth: { firebaseApiKey } }) new Locket({ friends: { projectId } }) new Locket({ auth: { clientType } }) ``` -------------------------------- ### react Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Allows a user to react to a specific moment with any string, such as an emoji or text. ```APIDOC ## POST /reactToMoment ### Description Allows a user to react to a specific moment with any string, such as an emoji or text. ### Method POST ### Endpoint https://api.locketcamera.com/reactToMoment ### Parameters #### Path Parameters - **momentUid** (string) - Required - The unique identifier of the moment to react to. - **reaction** (string) - Required - The reaction content (emoji or text). ### Response #### Success Response (200) - **result.data** (array) - An array containing the `momentUid` if the reaction was successful. - **result.status** (number) - The status code (200 for success). #### Error Response (401) - **result.errors** (array) - An array of error messages (e.g., "You don't have access to this moment"). - **result.status** (number) - The status code (401 for unauthorized). ### Request Example ```json { "momentUid": "S5OkJabkyqK47v34YQRw", "reaction": "😮" } ``` ### Response Example ```json { "result": { "data": ["S5OkJabkyqK47v34YQRw"], "status": 200 } } ``` ``` -------------------------------- ### Friends: listFriends Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Lists the UIDs of a user's friends. An optional user UID can be provided to list friends for another user. Uses GET /firestore … /users/{uid}/friends. ```APIDOC ## listFriends(userUid?) ### Description Retrieves a list of UIDs representing the friends of a user. ### Method GET ### Endpoint /firestore … /users/{uid}/friends ### Parameters #### Path Parameters - **userUid** (string) - Optional - The UID of the user whose friends to list. Defaults to the current user if not provided. ``` -------------------------------- ### Session Management Helpers Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Provides utility functions for checking authentication status, retrieving, setting, and clearing the current session. ```typescript locket.isAuthenticated(); locket.getSession(); // AuthSession | null locket.setSession({ idToken, refreshToken }); locket.signOut(); ``` ```typescript { idToken: string; refreshToken: string; expiresIn?: string; // "3600" expiresAt?: number; // Date.now() + expiresIn*1000 — computed for you uid?: string; } ``` -------------------------------- ### Import Locket API Types Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Import various types for authentication, moments, users, friends, and SDK options to strongly type your application's interactions with the Locket API. ```typescript import type { // Auth AuthSession, EmailSignInResponse, PhoneSignInResponse, PhoneSignInResult, VerifyCustomTokenResponse, RefreshTokenResponse, GetAccountInfoResponse, AccountInfoUser, ProviderUserInfo, LocketJwtPayload, // Moments Moment, FirestoreTimestamp, GetLatestMomentsResponse, ReactToMomentResponse, DeleteMomentResponse, GetMomentViewsResponse, MomentView, // Users & friends LocketUser, FetchUserResponse, Friend, FriendDocument, FriendDocumentFields, FirestoreListResponse, // SDK LocketOptions, GetLatestMomentsOptions, } from "locket-api"; ``` -------------------------------- ### signInWithPhone Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Authenticates a user with a phone number and password. This involves two underlying calls and returns both raw bodies, populating the session. ```APIDOC ## signInWithPhone(phone, password) ### Description Authenticates a user with a phone number and password. This involves two underlying calls: `signInWithPhonePassword` and `verifyCustomToken`. It returns both raw bodies and populates the session. ### Method POST (two calls) ### Endpoint 1. `https://api.locketcamera.com/signInWithPhonePassword` 2. `https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken` ### Parameters #### Request Body - **phone** (string) - Required - The user's phone number. - **password** (string) - Required - The user's password. ### Request Example ```ts const { phone, identity } = await locket.signInWithPhone("+66xxxxxxxxx", "password"); phone.result.token; // raw Firebase custom token identity.idToken; // Bearer token identity.refreshToken; identity.expiresIn; identity.isNewUser; ``` ### Response #### Success Response (200) - Returns an object containing raw bodies from both underlying calls. - **phone.result.token** (string) - Raw Firebase custom token. - **identity.idToken** (string) - Bearer token. - **identity.refreshToken** (string) - Refresh token. - **identity.expiresIn** (string) - Duration in seconds for which the `idToken` is valid (e.g., "3600"). - **identity.isNewUser** (boolean) - Indicates if the user is new. ### Failure - Locket responds HTTP 200 with `phone.result.status !== 200` and no `token`. - The SDK throws `LocketError` with the original body attached. ``` -------------------------------- ### Auth: signInWithEmail Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Signs in a user with their email and password. This method corresponds to the Google Identity Toolkit (IDT) POST /verifyPassword endpoint. ```APIDOC ## signInWithEmail(email, password) ### Description Authenticates a user using their email address and password. ### Method POST ### Endpoint /verifyPassword (Google IDT) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ``` -------------------------------- ### Friends Methods Source: https://github.com/jumpogpo/locket-api/blob/main/packages/locket-api/README.md Methods for managing and retrieving friend lists. ```APIDOC ## listFriends ### Description Retrieves a list of friends for a given user. ### Method GET ### Endpoint /firestore … /users/{uid}/friends ### Parameters #### Path Parameters None #### Query Parameters - **userUid** (string) - Optional - The user ID for whom to list friends. Defaults to the current user. ### Response #### Success Response (200) A list of friend user IDs. #### Response Example ```json { "friends": ["friend1", "friend2"] } ``` ``` ```APIDOC ## listFriendsDetailed ### Description Retrieves a detailed list of friends, with parsed Date objects. ### Method GET ### Endpoint /firestore … /users/{uid}/friends ### Parameters #### Path Parameters None #### Query Parameters - **userUid** (string) - Optional - The user ID for whom to list friends. Defaults to the current user. ### Response #### Success Response (200) A detailed list of friends, including relationship metadata. #### Response Example ```json { "friends": [ { "uid": "friend1", "added_at": "2023-10-27T10:00:00Z" } ] } ``` ``` ```APIDOC ## listFriendsRaw ### Description Retrieves the raw Firestore documents for the friends list. ### Method GET ### Endpoint /firestore … /users/{uid}/friends ### Parameters #### Path Parameters None #### Query Parameters - **userUid** (string) - Optional - The user ID for whom to list friends. Defaults to the current user. ### Response #### Success Response (200) Raw Firestore documents representing the friends list. #### Response Example ```json { "documents": [ { ... } ] } ``` ``` -------------------------------- ### Moments: react Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Allows a user to react to a specific moment with text or an emoji. This uses the POST /reactToMoment endpoint. ```APIDOC ## react(momentUid, reaction) ### Description Adds a reaction (text or emoji) to a specified moment. ### Method POST ### Endpoint /reactToMoment ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **momentUid** (string) - Required - The unique identifier of the moment to react to. - **reaction** (string) - Required - The reaction text or emoji to apply. ``` -------------------------------- ### Handle Locket API Errors Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Demonstrates how to catch and differentiate between HTTP-level LocketErrors and body-level errors returned by Locket SDK methods. Ensure to import Locket and LocketError. ```typescript import { Locket, LocketError } from "locket-api"; const locket = new Locket(); try { await locket.signInWithEmail("you@example.com", "password"); } catch (err) { if (err instanceof LocketError) { // HTTP-level failure console.error(err.status, err.code, err.message, err.response); } else { throw err; } } // Body-level failure — no throw const res = await locket.fetchUser("some-uid"); if (res.result.status !== 200) { console.warn("fetchUser failed:", res.result.errors); } ``` -------------------------------- ### Moments: getLatestMoments Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Retrieves the latest moments from a list of users, with optional configuration. This corresponds to the POST /getLatestMomentV2 endpoint. ```APIDOC ## getLatestMoments(users?, options?) ### Description Fetches the most recent moments posted by a specified list of users. ### Method POST ### Endpoint /getLatestMomentV2 ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **users** (string[]) - Optional - An array of user UIDs to fetch moments from. - **options** (object) - Optional - Configuration options for fetching moments. ``` -------------------------------- ### Auth: signInWithPhonePassword Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Signs in a user directly with their phone number and password. ```APIDOC ## signInWithPhonePassword(phone, password) ### Description Authenticates a user directly using their phone number and password. ### Method POST ### Endpoint /signInWithPhonePassword ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **phone** (string) - Required - The user's phone number. - **password** (string) - Required - The user's password. ``` -------------------------------- ### Low-Level Phone Password Sign-In Source: https://github.com/jumpogpo/locket-api/blob/main/README.md This is a low-level function for the first part of the phone sign-in flow. It only returns the raw response body and does not interact with the session. ```typescript const res = await locket.signInWithPhonePassword("+66xxxxxxxxx", "password"); res.result.token; // present on success res.result.status; // 200 on success, 400 on bad credentials ``` -------------------------------- ### getLatestMoments Source: https://github.com/jumpogpo/locket-api/blob/main/README.md Fetches the latest moments for the authenticated user. Can be filtered by specific users and options like last fetch time and sync token. ```APIDOC ## GET /getLatestMomentV2 ### Description Fetches the latest moments for the authenticated user. Can be filtered by specific users and options like last fetch time and sync token. ### Method POST ### Endpoint https://api.locketcamera.com/getLatestMomentV2 ### Parameters #### Query Parameters - **users** (string[]) - Optional - A list of user UIDs to fetch moments from. - **options** (object) - Optional - Additional options for fetching moments. - **excludedUsers** (string[]) - A list of user UIDs to exclude from the results. - **lastFetch** (number) - Timestamp of the last fetch to retrieve new moments. - **syncToken** (string) - Token to sync moments from a specific point. - **shouldCountMissedMoments** (boolean) - Whether to count missed moments. ### Response #### Success Response (200) - **result.data** (array) - An array of moment objects. - **canonical_uid** (string) - Unique identifier for the moment. - **user** (string) - The UID of the user who posted the moment. - **date** (object) - Timestamp of the moment. - **md5** (string) - MD5 hash of the moment. - **thumbnail_url** (string) - URL for the moment's thumbnail. - **result.missed_moments_count** (number) - The count of missed moments. - **result.sync_token** (string) - A token for the next sync. - **result.status** (number) - The status code (200 for success). #### Success Response (304) - **result.data** (array) - An empty array if no new moments are available. - **result.status** (number) - The status code (304 for no changes). ### Request Example ```json { "users": ["FRIEND_UID_1"], "options": { "excludedUsers": ["BLOCKED_UID"], "lastFetch": 1678886400000, "syncToken": "psSVRI9EWZ5sNMLu9PzQ", "shouldCountMissedMoments": true } } ``` ### Response Example ```json { "result": { "data": [ { "canonical_uid": "0Xu4LoJHqArMknW6pisT", "user": "5gGjaYuwU3Uw0qUMqVBTK5tMKy82", "date": { "_seconds": 1779795374, "_nanoseconds": 712000000 }, "md5": "a6949936ec4f0052847abf8afc63b339", "thumbnail_url": "https://firebasestorage.googleapis.com/.../thumb.webp" } ], "missed_moments_count": 0, "sync_token": "0Xu4LoJHqArMknW6pisT", "status": 200 } } ``` ```