Added behavior journal, adjusted layout, and added some colors
Deploy / deploy-prod (push) Skipped
Deploy / deploy-dev (push) Successful in 4m18s

This commit is contained in:
Corey Blais committed 2026-10-05 15:20:00 -04:00
1 parent b1b89ad334
commit 3237cd7601
31 files changed
+2135 -275

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { once } from 'node:events';
import test from 'node:test';
import express from 'express';
import SwaggerParser from '@apidevtools/swagger-parser';
import ts from 'typescript';
import { customerOpenApi } from './openapi.js';
import { mountApiDocs } from './router.js';
import { birdSchema, medicationSchema } from '../schemas.js';
const appSource = await readFile(new URL('../app.ts', import.meta.url), 'utf8');
const ast = ts.createSourceFile('app.ts', appSource, ts.ScriptTarget.Latest, true);
test('customer specification is valid OpenAPI and has unique operation IDs', async () => {
await SwaggerParser.validate(JSON.parse(JSON.stringify(customerOpenApi)));
const ids = Object.values(customerOpenApi.paths).flatMap((path) => Object.values(path!).map((operation) => operation.operationId));
assert.equal(new Set(ids).size, ids.length);
assert.deepEqual(customerOpenApi.servers, [{ url: '/api', description: 'This FlockPal instance' }]);
});
test('documented operations exactly match customer integration routes and permissions', () => {
const expected: string[] = [];
for (const statement of ast.statements) {
if (!ts.isExpressionStatement(statement) || !ts.isCallExpression(statement.expression)) continue;
const call = statement.expression;
if (!ts.isPropertyAccessExpression(call.expression) || call.expression.expression.getText(ast) !== 'app') continue;
const method = call.expression.name.text;
if (!['get', 'post', 'put', 'delete', 'patch'].includes(method)) continue;
const [pathArg, ...args] = call.arguments;
if (!pathArg || !ts.isStringLiteral(pathArg)) continue;
const middleware = args.filter(ts.isIdentifier).map((arg) => arg.text);
if (!middleware.includes('requireAuth') || middleware.includes('requireSessionAuth') || middleware.includes('requireAdmin')) continue;
const path = pathArg.text.replace(/^\/api/, '').replace(/:(\w+)/g, '{$1}');
expected.push(`${method} ${path}`);
const operation = (customerOpenApi.paths[path] as Record<string, any> | undefined)?.[method];
assert.ok(operation, `Missing ${method} ${path}`);
assert.deepEqual(operation.security, [{ IntegrationToken: [] }]);
if (middleware.includes('requireWriteAccess')) {
assert.match(operation.description, /read_write/);
assert.ok(operation.responses['402']);
assert.ok(operation.responses['403']);
}
const roleCall = args.find((arg) => ts.isCallExpression(arg) && arg.expression.getText(ast) === 'requireWorkspaceRole');
if (roleCall && ts.isCallExpression(roleCall)) {
for (const match of roleCall.getText(ast).matchAll(/'([^']+)'/g)) assert.ok(operation.description.includes(match[1]));
}
}
const actual = Object.entries(customerOpenApi.paths).flatMap(([path, item]) => Object.keys(item!).map((method) => `${method} ${path}`));
assert.deepEqual(actual.sort(), expected.sort());
assert.equal(actual.length, 35);
});
test('response models cover the actual serialized fields', () => {
const components = customerOpenApi.components!.schemas!;
const names: Record<string, string> = { normalizeWorkspace: 'workspace', normalizeWorkspaceMember: 'member', normalizeBird: 'bird', normalizeWeight: 'weight', normalizeVetVisit: 'vetVisit', normalizeMedication: 'medication', normalizeMedicationAdministration: 'administration', normalizeFlockNote: 'note', normalizeBirdTimelineEvent: 'timeline' };
for (const statement of ast.statements) {
if (!ts.isVariableStatement(statement)) continue;
for (const declaration of statement.declarationList.declarations) {
const model = names[declaration.name.getText(ast)];
if (!model) continue;
const fn = declaration.initializer;
assert.ok(fn && ts.isArrowFunction(fn) && ts.isParenthesizedExpression(fn.body));
const body = fn.body.expression;
assert.ok(ts.isObjectLiteralExpression(body));
const keys = body.properties.map((property) => property.name!.getText(ast));
const schema = components[model];
assert.ok(schema && !('$ref' in schema));
assert.deepEqual(Object.keys(schema.properties!).sort(), keys.sort(), model);
}
}
});
test('shared validators retain custom rules and document required request fields', () => {
assert.equal(birdSchema.safeParse({ name: 'Yoda', species: 'Parrot', motivators: 'one\ntwo\nthree\nfour' }).success, false);
assert.equal(medicationSchema.safeParse({ name: 'Medicine', dosage: '1 ml', frequency: 'once_daily', doseSchedule: [{ key: 'morning', label: 'Morning', time: '08:00' }], startDate: '2026-09-27', endDate: '2026-09-26' }).success, false);
const bird = customerOpenApi.components!.schemas!.BirdInput;
assert.ok(!('$ref' in bird));
assert.deepEqual(bird.required, ['name', 'species']);
});
test('Swagger UI, initialization, assets and specification are served locally with compatible CSP', async (t) => {
const app = express();
mountApiDocs(app);
const server = app.listen(0, '127.0.0.1');
await once(server, 'listening');
t.after(() => new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve())));
const address = server.address();
assert.ok(address && typeof address !== 'string');
const base = `http://127.0.0.1:${address.port}`;
const page = await fetch(`${base}/api/docs/`);
assert.equal(page.status, 200);
const html = await page.text();
assert.match(html, /FlockPal API Reference/);
const csp = page.headers.get('content-security-policy')!;
assert.match(csp, /script-src 'self'/);
assert.match(csp, /connect-src 'self'/);
assert.ok(!csp.includes('upgrade-insecure-requests'));
for (const asset of ['swagger-ui.css', 'swagger-ui-bundle.js', 'swagger-ui-standalone-preset.js', 'swagger-ui-init.js']) {
const response = await fetch(`${base}/api/docs/${asset}`);
assert.equal(response.status, 200, asset);
const content = await response.text();
assert.ok(content.length > 0);
if (asset === 'swagger-ui-init.js') {
assert.match(content, /\/api\/openapi.json/);
assert.match(content, /"persistAuthorization": false/);
assert.match(content, /"validatorUrl": null/);
}
}
const spec = await fetch(`${base}/api/openapi.json`);
assert.equal(spec.status, 200);
assert.match(spec.headers.get('content-type')!, /application\/json/);
assert.deepEqual(await spec.json(), customerOpenApi);
const redirect = await fetch(`${base}/api/docs`, { redirect: 'manual' });
assert.equal(redirect.status, 301);
assert.equal(redirect.headers.get('location'), '/api/docs/');
});
+134
View File
@@ -0,0 +1,134 @@
import { unassignedBirdMatchSchema, claimBirdSchema } from '../birdMembershipSchemas.js';
import { behaviorTypeSchema, behaviorOccurrenceSchema } from '../behaviorSchemas.js';
import { z } from 'zod';
import { extendZodWithOpenApi, OpenAPIRegistry, OpenApiGeneratorV3, type RouteConfig } from '@asteasolutions/zod-to-openapi';
import { birdSchema, workspaceMemberSchema, workspaceRoleSchema, flockNoteSchema, locationSearchSchema,
weightSchema, vetVisitSchema, medicationSchema, medicationAdministrationSchema } from '../schemas.js';
import * as responses from './responses.js';
extendZodWithOpenApi(z);
const registry = new OpenAPIRegistry();
registry.registerComponent('securitySchemes', 'IntegrationToken', {
type: 'http', scheme: 'bearer', bearerFormat: 'flpt_…',
description: 'Paste your integration token, without the Bearer prefix. Create it in FlockPal Settings → Integration tokens.',
});
const models = Object.fromEntries(Object.entries(responses).map(([name, schema]) => [name, registry.register(name.replace('Response', ''), schema)]));
const error = registry.register('Error', z.object({
error: z.string(), code: z.string().optional(),
details: z.object({ formErrors: z.array(z.string()), fieldErrors: z.record(z.array(z.string())) }).optional(),
}));
const json = (schema: z.ZodTypeAny, example?: unknown) => ({ 'application/json': { schema, ...(example ? { example } : {}) } });
const errors: Record<number, string> = {
400: 'Invalid request.', 401: 'Missing, expired, revoked, or invalid integration token.',
402: 'Workspace is read-only: subscription must be active/trialing, or rescue verification approved.',
403: 'Insufficient token scope or workspace role.', 404: 'Resource not found in this workspace, or cannot be changed.',
409: 'Conflict: duplicate band/tag ID, duplicate weight date, or memorialized bird is read-only.',
500: 'Internal server error.', 502: 'Location provider request failed.', 503: 'Location search is not configured.',
};
type Endpoint = {
method: 'get' | 'post' | 'put' | 'delete'; path: string; summary: string; tag: string;
response?: z.ZodTypeAny; body?: z.ZodTypeAny; example?: unknown; query?: z.AnyZodObject;
description?: string; status?: number; errors?: number[]; roles?: string[];
};
const careRoles = ['owner', 'assistant', 'caregiver'];
function endpoint(config: Endpoint) {
const write = config.method !== 'get';
const params = Object.fromEntries([...config.path.matchAll(/\{(\w+)\}/g)].map((match) => [match[1], z.string().uuid()]));
const responseMap: RouteConfig['responses'] = {
[config.status ?? (config.method === 'delete' ? 204 : config.method === 'post' ? 201 : 200)]: {
description: config.method === 'delete' ? 'Deleted successfully. No response body.' : 'Success.',
...(config.response ? { content: json(config.response) } : {}),
},
429: { description: 'Rate limit exceeded. General limit: 300 requests per 15 minutes per IP; location search additionally allows 40 per 15 minutes.',
headers: { 'Retry-After': { schema: { type: 'string' }, description: 'Seconds until retry.' } },
content: { 'text/html': { schema: { type: 'string' } }, 'application/json': { schema: error } } },
};
for (const status of new Set([401, 500, ...(write ? [402, 403] : []), ...(config.body || config.query ? [400] : []), ...(config.errors ?? [])])) {
responseMap[status] = { description: errors[status], content: json(error) };
}
registry.registerPath({
method: config.method, path: config.path, summary: config.summary, tags: [config.tag],
operationId: `${config.method}_${config.path.replace(/[{}]/g, '').replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_/, '')}`,
description: [config.description, write ? `Requires a read_write token and an active writable workspace. Allowed roles: ${(config.roles ?? careRoles).join(', ')}.` : 'Accepts read_only or read_write integration tokens.'].filter(Boolean).join('\n\n'),
security: [{ IntegrationToken: [] }],
request: {
...(Object.keys(params).length ? { params: z.object(params) } : {}),
...(config.query ? { query: config.query } : {}),
...(config.body ? { body: { required: true, content: json(config.body, config.example) } } : {}),
},
responses: responseMap,
});
}
const one = (name: string, model: z.ZodTypeAny) => z.object({ [name]: model });
const many = (name: string, model: z.ZodTypeAny) => one(name, z.array(model));
endpoint({ method: 'get', path: '/workspace', summary: 'Get the token’s workspace', tag: 'Workspace', response: one('workspace', models.workspaceResponse) });
endpoint({ method: 'get', path: '/workspace/members', summary: 'List workspace members', tag: 'Workspace', response: many('members', models.memberResponse) });
endpoint({ method: 'post', path: '/workspace/members', summary: 'Add or update a workspace member', tag: 'Workspace', body: registry.register('MemberInput', workspaceMemberSchema), response: one('member', models.memberResponse), roles: ['owner', 'assistant'] });
endpoint({ method: 'put', path: '/workspace/members/{memberId}', summary: 'Change a member’s role', tag: 'Workspace', body: z.object({ role: workspaceRoleSchema }), response: one('member', models.memberResponse), roles: ['owner', 'assistant'], errors: [404], description: 'Only the billing owner can promote collaborators to owner. Additional protections apply to changing your own or the billing owner’s membership.' });
endpoint({ method: 'delete', path: '/workspace/members/{memberId}', summary: 'Remove a workspace member', tag: 'Workspace', roles: ['owner', 'assistant'], errors: [404], description: 'Protected memberships cannot be removed.' });
endpoint({ method: 'get', path: '/notes', summary: 'List flock notes', tag: 'Notes', response: many('notes', models.noteResponse) });
endpoint({ method: 'post', path: '/notes', summary: 'Create a flock note', tag: 'Notes', body: registry.register('NoteInput', flockNoteSchema), response: one('note', models.noteResponse), errors: [404], example: { body: 'Enjoyed a new enrichment activity today.' } });
endpoint({ method: 'delete', path: '/notes/{noteId}', summary: 'Delete a flock note', tag: 'Notes', errors: [404] });
endpoint({ method: 'get', path: '/locations/search', summary: 'Search for a location', tag: 'Locations', query: locationSearchSchema, response: many('results', models.locationResponse), errors: [502, 503], description: 'Search cities, regions, and countries. Requires 3–120 characters; returns up to three matches. Additional rate limit: 40 requests per 15 minutes per IP.' });
endpoint({ method: 'get', path: '/birds/unassigned-match', summary: 'Check for an unassigned bird by band ID', tag: 'Birds', query: unassignedBirdMatchSchema, response: z.object({ available: z.boolean() }), errors: [403], description: 'Requires owner, assistant, or caregiver role. Returns only availability, not profile details. Matching ignores case and surrounding whitespace; partial and unknown IDs do not match.' });
endpoint({ method: 'post', path: '/birds/claim', summary: 'Add an unassigned bird with its existing history', tag: 'Birds', body: claimBirdSchema, response: z.object({ bird: models.birdResponse, historyImported: z.literal(true) }), status: 200, errors: [409], description: 'Requires confirmHistory: true. Atomically assigns the existing bird to the current flock, preserving its ID, profile, photo, and history. Existing profile details are used. Birds already in a flock cannot be claimed.' });
endpoint({ method: 'get', path: '/birds', summary: 'List active and memorialized birds', tag: 'Birds', response: z.object({ birds: z.array(models.birdResponse), memorializedBirds: z.array(models.birdResponse) }) });
const birdInput = registry.register('BirdInput', birdSchema);
const birdDescription = 'motivators and demotivators each allow up to three non-empty lines. hatchDay takes precedence over the legacy dateOfBirth field. photoDataUrl accepts an image data URL or HTTP(S) URL; returned photo links may expire.';
endpoint({ method: 'post', path: '/birds', summary: 'Create a bird', tag: 'Birds', body: birdInput, response: one('bird', models.birdResponse), errors: [409], description: birdDescription, example: { name: 'Yoda', species: 'African grey' } });
endpoint({ method: 'put', path: '/birds/{birdId}', summary: 'Update a bird', tag: 'Birds', body: birdInput, response: one('bird', models.birdResponse), errors: [404, 409], description: `Submit the full editable profile: omitted optional fields may be cleared or reset. ${birdDescription}` });
endpoint({ method: 'delete', path: '/birds/{birdId}', summary: 'Remove a bird from its flock', tag: 'Birds', errors: [404, 409], description: 'Unassigns the bird without deleting its profile, photo, or care history. Bird-specific notes follow the bird; flock-wide notes and workspace audit logs stay in the old flock. Public sharing is disabled and pending transfers are revoked. An exact band ID match can later bring the bird and its history into a flock.' });
endpoint({ method: 'get', path: '/birds/{birdId}/timeline', summary: 'List bird timeline events', tag: 'Birds', response: many('events', models.timelineResponse), errors: [404] });
for (const resource of [
{ path: 'weights', single: 'weight', plural: 'weights', id: 'weightId', tag: 'Weights', input: weightSchema, model: models.weightResponse },
{ path: 'vet-visits', single: 'vetVisit', plural: 'vetVisits', id: 'visitId', tag: 'Vet visits', input: vetVisitSchema, model: models.vetVisitResponse },
{ path: 'medications', single: 'medication', plural: 'medications', id: 'medicationId', tag: 'Medications', input: medicationSchema, model: models.medicationResponse },
]) {
const path = `/birds/{birdId}/${resource.path}`;
const body = registry.register(`${resource.single}Input`, resource.input);
const description = resource.path === 'medications' ? 'endDate must be on or after startDate. Supply 1–8 doseSchedule entries with unique application-defined keys; use a key as administrationSlot when recording a dose.' : undefined;
endpoint({ method: 'get', path, summary: `List ${resource.tag.toLowerCase()}`, tag: resource.tag, response: many(resource.plural, resource.model),
...(resource.path === 'weights' ? { query: z.object({ days: z.coerce.number().min(1).max(425).default(30) }), description: 'Lookback window in days; defaults to 30. Numeric values are clamped to 1–425. Returns an empty list when no matching records exist.' } : {}) });
endpoint({ method: 'post', path, summary: `Create ${resource.single === 'vetVisit' ? 'a vet visit' : `a ${resource.single}`}`, tag: resource.tag, body, response: one(resource.single, resource.model), errors: [404, 409], description,
...(resource.path === 'weights' ? { example: { weightGrams: 425, recordedOn: '2026-09-27', notes: 'Morning weight' } } : {}) });
endpoint({ method: 'put', path: `${path}/{${resource.id}}`, summary: `Update ${resource.single === 'vetVisit' ? 'a vet visit' : `a ${resource.single}`}`, tag: resource.tag, body, response: one(resource.single, resource.model), errors: [404, 409],
description: resource.path === 'weights' ? 'Only the three most recent weight records are editable. Older records return 404. One weight entry is allowed per bird per date.' : `Submit the full editable record; omitted optional fields may be reset. ${description ?? ''}` });
if (resource.path !== 'weights') endpoint({ method: 'delete', path: `${path}/{${resource.id}}`, summary: `Delete ${resource.single === 'vetVisit' ? 'a vet visit' : 'a medication'}`, tag: resource.tag, errors: [404, 409] });
}
endpoint({ method: 'get', path: '/birds/{birdId}/medication-administrations', summary: 'List medication administrations', tag: 'Medications', response: many('administrations', models.administrationResponse) });
endpoint({ method: 'post', path: '/birds/{birdId}/medications/{medicationId}/administrations', summary: 'Record or update a medication dose', tag: 'Medications', body: registry.register('AdministrationInput', medicationAdministrationSchema), response: one('administration', models.administrationResponse), errors: [404, 409], description: 'Creates or updates the record for this medication, date, and administrationSlot. Use a doseSchedule key for administrationSlot; it defaults to dose-1. Returns 201 for both creation and update.' });
const behaviorTypeResponse = registry.register('BehaviorType', z.object({
id: z.string().uuid(), name: z.string(), description: z.string().nullable(), createdAt: z.string().datetime(),
}));
const behaviorResponse = registry.register('BehaviorOccurrence', z.object({
id: z.string().uuid(), birdId: z.string().uuid(), behaviorTypeId: z.string().uuid(), behaviorName: z.string(),
occurredAt: z.string().datetime(), durationSeconds: z.number().nullable(), severity: z.number().int().min(1).max(5).nullable(),
notes: z.string().nullable(), createdAt: z.string().datetime(), updatedAt: z.string().datetime(),
}));
endpoint({ method: 'get', path: '/birds/{birdId}/behavior-types', summary: 'List available behavior types', tag: 'Behavior Journal', response: many('behaviorTypes', behaviorTypeResponse), errors: [400, 404], description: 'Includes common behaviors, flock custom behaviors, and behaviors in this bird’s transferred history.' });
endpoint({ method: 'post', path: '/birds/{birdId}/behavior-types', summary: 'Create a reusable flock behavior type', tag: 'Behavior Journal', body: behaviorTypeSchema, response: one('behaviorType', behaviorTypeResponse), errors: [404, 409], description: 'Names are unique within the flock, ignoring case. An existing type is returned for a duplicate name.' });
endpoint({ method: 'get', path: '/birds/{birdId}/behaviors', summary: 'List behavior occurrences in a date range', tag: 'Behavior Journal', response: many('occurrences', behaviorResponse), query: z.object({ from: z.string().datetime({ offset: true }), to: z.string().datetime({ offset: true }), behaviorTypeId: z.string().uuid().optional() }), errors: [404], description: 'From is inclusive; to is exclusive. The range must be positive and at most 32 days. Send local month boundaries with their UTC offsets or converted to UTC. Results are newest first; individual events are never aggregated.' });
endpoint({ method: 'post', path: '/birds/{birdId}/behaviors', summary: 'Record a behavior occurrence', tag: 'Behavior Journal', body: behaviorOccurrenceSchema, response: one('occurrence', behaviorResponse), errors: [404, 409], description: 'Duration is optional and measured in seconds. Intensity is optional, from 1 to 5. Occurrence timestamps require a time zone offset.' });
endpoint({ method: 'put', path: '/birds/{birdId}/behaviors/{occurrenceId}', summary: 'Edit a behavior occurrence', tag: 'Behavior Journal', body: behaviorOccurrenceSchema, response: one('occurrence', behaviorResponse), errors: [404, 409] });
endpoint({ method: 'delete', path: '/birds/{birdId}/behaviors/{occurrenceId}', summary: 'Delete a behavior occurrence', tag: 'Behavior Journal', errors: [400, 404, 409] });
export const customerOpenApi = new OpenApiGeneratorV3(registry.definitions).generateDocument({
openapi: '3.0.3',
info: { title: 'FlockPal Customer API', version: '0.1.0', description: `Connect your flock to scripts and automation tools such as n8n.
### Getting started
1. Sign in to FlockPal and open Settings → Integration tokens.
2. Create a read_only token for reading, or read_write for changes. Copy the secret when shown; it is only displayed once.
3. Click Authorize and paste the token (without the Bearer prefix). Requests send Authorization: Bearer flpt_….
Tokens are scoped to the workspace where they were created and use the creating user’s current membership permissions. Create separate tokens for other workspaces. Expired or revoked tokens return 401.
Writes require read_write scope, an allowed role, and an active/trialing subscription or approved rescue workspace. Memorialized birds are read-only. Try it out sends real requests to this FlockPal instance, including changes and deletions; authorization is not persisted across reloads.
This reference covers customer integration endpoints. Manage tokens, authentication, billing, transfers, and memorialization in the FlockPal application. Photo URLs returned by the API can be used directly and may expire.
The general rate limit is 300 requests per 15 minutes per IP; location search also has a 40-request limit. On 429, wait for Retry-After before retrying.` },
servers: [{ url: '/api', description: 'This FlockPal instance' }],
tags: ['Workspace', 'Birds', 'Weights', 'Vet visits', 'Medications', 'Notes', 'Locations', 'Behavior Journal'].map((name) => ({ name })),
});
+61
View File
@@ -0,0 +1,61 @@
import { z } from 'zod';
import { birdGenderSchema, workspaceRoleSchema } from '../schemas.js';
const id = z.string().uuid();
const text = z.string().nullable();
const date = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
const timestamp = z.string().datetime({ offset: true });
export const locationResponse = z.object({
label: text, city: text, region: text, country: text, countryCode: text,
latitude: z.number().nullable(), longitude: z.number().nullable(),
precision: z.enum(['city', 'region', 'country']).nullable(), verifiedAt: timestamp, provider: z.literal('mapbox').nullable(), providerPlaceId: text,
});
export const workspaceResponse = z.object({
id: z.number().int(), name: z.string(), workspaceType: z.enum(['standard', 'rescue']), billingEmail: text,
billingPlan: z.enum(['rescue_free', 'household_basic', 'household_plus', 'household_macaw', 'household_hyacinth_macaw']),
billingInterval: z.enum(['monthly', 'yearly']),
subscriptionStatus: z.enum(['active', 'trialing', 'past_due', 'canceled', 'unpaid', 'none']),
stripeCustomerId: text, stripeSubscriptionId: text,
rescueVerificationStatus: z.enum(['not_required', 'pending', 'approved', 'rejected']),
createdAt: timestamp, updatedAt: timestamp,
});
export const memberResponse = z.object({
id, workspaceId: z.number().int(), userId: id.nullable(), inviteEmail: z.string(), name: z.string(),
role: workspaceRoleSchema, acceptedAt: timestamp.nullable(), createdAt: timestamp,
});
export const birdResponse = z.object({
id, workspaceId: z.number().int(), name: z.string(), tagId: text, species: z.string(),
motivators: text, demotivators: text, favoriteSnack: text, locationLabel: text,
locationDetails: locationResponse.nullable(), vetClinicName: text, vetClinicAddress: text,
vetAccountNumber: text, vetDoctorName: text, gender: birdGenderSchema,
hatchDay: date.nullable(), dateOfBirth: date.nullable(), gotchaDay: date.nullable(), chartColor: z.string(),
photoDataUrl: text.describe('Photo URL or legacy data URL. Storage-backed URLs expire; refresh the bird list to obtain a new URL.'),
photoObjectKey: text, photoContentType: text, photoUpdatedAt: timestamp.nullable(),
notifyOnDob: z.boolean(), notifyOnGotchaDay: z.boolean(), publicProfileCode: text, publicProfileEnabled: z.boolean(),
memorializedAt: timestamp.nullable(), memorializedOn: date.nullable(), memorialNote: text,
notifyOnMemorialDay: z.boolean(), createdAt: timestamp,
latestWeightGrams: z.number().nullable(), latestRecordedOn: date.nullable(),
});
export const weightResponse = z.object({ id, birdId: id, weightGrams: z.number(), recordedOn: date, notes: text });
export const vetVisitResponse = z.object({ id, birdId: id, visitedOn: date, clinicName: z.string(), reason: z.string(), notes: text });
export const medicationResponse = z.object({
id, birdId: id, name: z.string(), dosage: z.string(),
frequency: z.enum(['once_daily', 'twice_daily', 'every_8_hours', 'every_6_hours', 'as_needed']),
doseSchedule: z.array(z.object({ key: z.string(), label: z.string(), time: z.string() })),
route: text, startDate: date, endDate: date.nullable(), notes: text, remindersEnabled: z.boolean(),
});
export const administrationResponse = z.object({
id, medicationId: id, birdId: id, administeredOn: date, administrationSlot: z.string(),
status: z.enum(['administered', 'missed']), notes: text, createdByUserId: id.nullable(), createdAt: timestamp,
});
export const noteResponse = z.object({
id, workspaceId: z.number().int(), birdId: id.nullable(), birdName: text, title: z.string(), body: z.string(),
createdByUserId: id.nullable(), createdByName: text, createdAt: timestamp, updatedAt: timestamp,
});
export const timelineResponse = z.object({
id, birdId: id, eventType: z.enum(['profile_created', 'transferred', 'location_updated', 'owner_changed', 'manual_note', 'removed_from_flock', 'joined_flock']),
fromWorkspaceId: z.number().int().nullable(), toWorkspaceId: z.number().int().nullable(),
fromWorkspaceName: text, toWorkspaceName: text, fromOwnerEmail: text, toOwnerEmail: text,
locationLabel: text, locationDetails: locationResponse.nullable(), note: text, eventDate: date,
createdByUserId: id.nullable(), createdAt: timestamp,
});
+24
View File
@@ -0,0 +1,24 @@
import type { Express } from 'express';
import helmet from 'helmet';
import swaggerUi from 'swagger-ui-express';
import { customerOpenApi } from './openapi.js';
// Mount before application middleware so docs do not consume API rate limits.
// Swagger assets and initialization are served locally; no external validator is used.
export function mountApiDocs(app: Express) {
app.get('/api/openapi.json', helmet(), (_req, res) => res.json(customerOpenApi));
app.use('/api/docs', helmet({
contentSecurityPolicy: { directives: {
'script-src': ["'self'"],
'connect-src': ["'self'"],
// Keep local HTTP development usable; production transport is handled by the proxy.
'upgrade-insecure-requests': null,
} },
}), swaggerUi.serve, swaggerUi.setup(undefined, {
customSiteTitle: 'FlockPal API Reference',
swaggerOptions: {
url: '/api/openapi.json', validatorUrl: null, persistAuthorization: false,
displayRequestDuration: true, docExpansion: 'none',
},
}));
}