ab-ecosystem-photo-detector
v0.1.0
Published
Node.js / TypeScript SDK for the Photo Detector API — event photo management with AI-powered face search
Downloads
45
Maintainers
Readme
ab-ecosystem-photo-detector
Node.js / TypeScript SDK for the Photo Detector API — event photo management with AI-powered face search.
- Typed end to end, generated from the API's own schemas
- Zero runtime dependencies (uses the built-in
fetch, Node >= 18) - Ships both ESM and CommonJS builds
- Typed errors, automatic retries with
Retry-Aftersupport, per-call timeouts andAbortSignal - One-call photo upload that handles the presign → S3 → confirm dance
Install
npm install ab-ecosystem-photo-detectorQuick start
import { PhotoDetector } from "ab-ecosystem-photo-detector";
const client = new PhotoDetector({
baseUrl: "https://your-api.example.com",
accessToken: process.env.PHOTO_DETECTOR_ACCESS_TOKEN,
});
const gallery = await client.galleries.create({ name: "Wedding 2025" });
const event = await client.events.create(gallery.id, {
name: "Ceremony",
location: "Mumbai",
event_date: new Date("2025-12-31T18:00:00Z"),
});
await client.photos.upload(gallery.id, ["./photo1.jpg", "./photo2.jpg"], {
subGalleryId: event.id,
});CommonJS works too:
const { PhotoDetector } = require("ab-ecosystem-photo-detector");baseUrl and accessToken fall back to PHOTO_DETECTOR_BASE_URL and
PHOTO_DETECTOR_ACCESS_TOKEN, so in a configured environment new PhotoDetector()
is enough.
Client options
| Option | Default | Notes |
|---|---|---|
| baseUrl | $PHOTO_DETECTOR_BASE_URL | Root URL of the backend. Required. |
| accessToken | $PHOTO_DETECTOR_ACCESS_TOKEN | SSO bearer token. A function is re-invoked per request, which suits rotating tokens. |
| guestToken | — | Guest JWT sent as X-Guest-Token. Individual public.* calls can override it. |
| timeout | 30000 | Per-request timeout in milliseconds. |
| maxRetries | 2 | Retries on 408, 429 and 5xx, plus network failures. |
| headers | — | Extra headers merged into every request. |
| fetch | global fetch | Override for tests, proxies or a custom agent. |
Every resource method takes an optional final argument for per-call
signal, timeout, maxRetries and headers:
const ac = new AbortController();
const photos = client.photos.list(galleryId, { limit: 100 }, { signal: ac.signal });
ac.abort();Authentication
There are two independent identities:
- Owner — an SSO bearer token, for everything under
client.galleries,client.photosand friends. - Guest — a JWT minted by OTP verification, for
client.public.getSelfie,uploadSelfieandsearchEvent. Valid for 30 days.
client.setAccessToken("new-token");
client.setGuestToken("guest-jwt");Galleries
await client.galleries.create({ name: "My Gallery", allow_global_search: false });
await client.galleries.list({ page: 1, limit: 20 }); // -> { data, total, page, limit, total_pages }
await client.galleries.get(galleryId);
await client.galleries.update(galleryId, { name: "New Name" });
await client.galleries.delete(galleryId);
const { cover_image } = await client.galleries.uploadCover(galleryId, "./cover.jpg");allow_global_search widens guest face search beyond a single event: a search
run on any gallery with the flag set also scans every other gallery of the
same owner that has it set.
Events
An event is a dated sub-collection of photos inside a gallery, and the unit the public pages are built around.
await client.events.create(galleryId, { name: "Party", location: "Delhi" });
await client.events.list(galleryId);
await client.events.get(galleryId, eventId);
await client.events.update(galleryId, eventId, { visibility: "public" });
await client.events.delete(galleryId, eventId);visibility controls what guests can reach:
| Value | Public page | Full photo list | Face search |
|---|---|---|---|
| public | yes | yes | yes |
| private | yes | no (403) | yes |
| draft | no (403) | no | no |
Photos
One call
upload() runs the whole flow — ask for presigned URLs, PUT each file straight
to storage, then confirm so the server queues face detection.
const photos = await client.photos.upload(galleryId, [
"./a.jpg",
{ data: buffer, filename: "b.jpg" },
], {
subGalleryId: eventId,
concurrency: 4,
onProgress: ({ completed, total }) => console.log(`${completed}/${total}`),
});Uploaded photos come back with status: "processing"; face detection finishes
in the background and sets face_count.
Anywhere the SDK takes a file you can pass a path, a Buffer, a Uint8Array, a
Blob, or { path } / { data } with an explicit filename and contentType.
Content type is inferred from the extension when you don't say. The API accepts
JPEG, PNG, WebP, BMP and TIFF.
Step by step
Useful when the bytes never pass through your process — hand the presigned URL to a browser and confirm once it reports success.
const { files } = await client.photos.presign(galleryId, [
{ filename: "photo1.jpg", content_type: "image/jpeg" },
], { subGalleryId: eventId });
// PUT the bytes to files[0].upload_url yourself. The URL is signed for both
// Content-Type and Cache-Control, so send exactly:
// Content-Type: image/jpeg
// Cache-Control: public, max-age=31536000, immutable
await client.photos.confirm(galleryId, [
{ filename: "photo1.jpg", key: files[0].key, size_bytes: 102400 },
], { subGalleryId: eventId });List and delete
await client.photos.list(galleryId, { page: 1, limit: 24, subGalleryId: eventId });
await client.photos.delete(photoId);Face search (owner)
const { results } = await client.search.search("./selfie.jpg", {
galleryId, // omit to search every gallery you own
threshold: 0.4, // 0.0–1.0
topK: 30, // 1–100
});
for (const match of results) {
console.log(match.photo_url, match.similarity);
}The largest face in the query image is the one searched for.
Guest flow (no owner token)
const guests = new PhotoDetector({ baseUrl: "https://your-api.example.com" });
const event = await guests.public.getEvent("my-event-slug");
await guests.public.sendOtp("my-event-slug", {
name: "John",
email: "[email protected]",
channel: "email", // or "whatsapp", which uses `phone`
});
const { guest_token } = await guests.public.verifyOtp("my-event-slug", {
name: "John",
code: "1234",
email: "[email protected]",
});
// Store the selfie once...
await guests.public.uploadSelfie("./selfie.jpg", { guestToken: guest_token });
// ...then search as often as you like without re-uploading.
const { results } = await guests.public.searchEvent(
"my-event-slug",
{ useStored: true },
{ guestToken: guest_token },
);Pass guestToken once on the constructor to skip it per call. OTP sends are
rate limited to 3 per identity per 15 minutes and codes expire after 5 minutes.
Public events also expose their full photo list without any search:
await guests.public.listPhotos("my-event-slug", { page: 1, limit: 24 });Themes
Styling for an event's public page. save() deep-merges, so you can send one
section at a time.
await client.themes.get(eventId);
await client.themes.save(eventId, {
template: "elegant",
colors: { bg_primary: "#1a1a2e", accent: "#e94560" },
branding: { custom_title: "Our Wedding", show_powered_by: false },
permissions: { allow_download: true },
});
await client.themes.delete(eventId);Analytics and guests
const { totals, daily } = await client.analytics.overview({ days: 30 });
console.log(totals.page_views, totals.searches, totals.search_success_rate);
await client.guests.list({ page: 1, limit: 20, search: "john" });Channels
// Check credentials against Meta without saving them
const check = await client.waChannels.verify({
phone_number_id: "123456",
waba_id: "789",
access_token: "EAA...",
});
if (!check.valid) throw new Error(check.error ?? "invalid credentials");
const channel = await client.waChannels.create({
phone_number_id: "123456",
waba_id: "789",
access_token: "EAA...",
});
await client.waChannels.list();
await client.waChannels.update(channel.id, { access_token: "new-token" });
await client.waChannels.delete(channel.id);
// Template definitions, each annotated with its live status per channel
const templates = await client.waChannels.templates();
await client.waChannels.syncTemplate(channel.id, "event_photo_link");
await client.waChannels.templateStatus(channel.id, "event_photo_link");Contacts and broadcasts
const result = await client.waBroadcasts.importContacts(eventId, [
{ phone: "+919876543210", first_name: "Rahul", last_name: "Sharma" },
]);
console.log(result.added, result.invalid, result.invalid_rows);
await client.waBroadcasts.listContacts(eventId);
const job = await client.waBroadcasts.create({
event_id: eventId,
channel_id: channel.id,
template_name: "event_photo_link",
});
// Poll for progress
const latest = await client.waBroadcasts.get(job.id);
console.log(latest.status, latest.sent, latest.failed, latest.total);
await client.waBroadcasts.cancel(job.id);Campaigns
A campaign saves a gallery/event/channel/template combination you can fire repeatedly.
const campaign = await client.campaigns.create({
name: "Wedding Invite",
gallery_id: galleryId,
event_id: eventId,
channel_id: channel.id,
template_name: "event_photo_link",
});
const { broadcast_id, total } = await client.campaigns.shoot(campaign.id);
const progress = await client.waBroadcasts.get(broadcast_id);shoot() throws ConflictError when a broadcast is already running for that event.
Custom domains
Requires the custom-domain subscription addon; without it these calls throw
ForbiddenError.
const domain = await client.customDomains.create("photos.mybrand.com");
console.log(`Point a CNAME at ${domain.cname_target}, then verify.`);
const { verified, message } = await client.customDomains.verify(domain.id);
await client.customDomains.list();
await client.customDomains.active(); // -> { domain: string | null }
await client.customDomains.delete(domain.id);Once a domain is verified and pointed at the API, requests arriving on it can list that owner's events with no slug and no token:
const branded = new PhotoDetector({ baseUrl: "https://photos.mybrand.com" });
const { events } = await branded.public.domainLanding();Errors
Every failure throws a subclass of PhotoDetectorError carrying status,
detail (the API's message, with FastAPI validation lists flattened into
something readable) and the parsed body.
import {
PhotoDetectorError,
NotFoundError,
AuthenticationError,
RateLimitError,
} from "ab-ecosystem-photo-detector";
try {
await client.galleries.get("nonexistent-id");
} catch (err) {
if (err instanceof NotFoundError) console.error(err.detail);
else if (err instanceof AuthenticationError) console.error("token expired");
else if (err instanceof RateLimitError) console.error(`retry in ${err.retryAfter}s`);
else if (err instanceof PhotoDetectorError) console.error(err.status, err.detail);
else throw err;
}| Error | Trigger |
|---|---|
| BadRequestError | 400 |
| AuthenticationError | 401 |
| ForbiddenError | 403 |
| NotFoundError | 404 |
| ConflictError | 409 |
| ValidationError | 422 |
| RateLimitError | 429 — exposes retryAfter |
| ServerError | 5xx |
| ConnectionError | network failure or caller abort |
| TimeoutError | request exceeded timeout |
408, 429 and 5xx responses are retried automatically up to maxRetries, with
exponential backoff that honours Retry-After. An abort you request yourself is
never retried.
Escape hatch
Anything the SDK doesn't wrap is still reachable with the typed transport, which applies the same auth, retries and error handling:
const data = await client.http.get<MyType>("/api/v1/some/new/endpoint", {
query: { page: 1 },
});Requirements
- Node.js >= 18 (for the built-in
fetch,FormDataandBlob)
License
MIT
