Merge dev into feat/native-apps

Brings the native apps branch up to dev (NestJS-only server, MikroORM
repositories, tracked sessions, per-domain locales, the lint ratchets) and
ports its new code onto that architecture:

- server: /api/auth/native moves onto injected services. The session is
  minted by the auth domain's new LoginSessionService (login bookkeeping and
  SessionsService.issue in one transaction), the one-time codes live behind a
  NativeHandoffStore port with a capped in-memory implementation that drops
  expired codes on write instead of running a timer, both routes declare
  response contracts, and the exchange answers { success: true }. Unit and
  e2e suites run on createTestModule and the ORM factories.
- shared: native strings for az, et, sk and th, native wired into every
  locale, the address placeholder as a full URL.
- client: the account and export changes go into dev's shared hooks
  (useAccountSettings, useTripExport), the native server card is a
  desktop/phone pair on useNativeServer, the hand-off call moves out of the
  page hook into native/, best-effort native failures go through
  reportError instead of the console, and the address screen is known to
  knip and lint:i18n-keys.
- package-lock.json regenerated on Linux.
This commit is contained in:
Maurice
2026-10-25 17:04:15 +01:00
11842 changed files with 1361077 additions and 180501 deletions
+9
View File
@@ -1,4 +1,6 @@
import {
asLlmVision,
LLM_VISION_MODES,
adminUserCreateRequestSchema,
adminUserUpdateRequestSchema,
adminPermissionsRequestSchema,
@@ -106,6 +108,13 @@ describe('adminAddonUpdateRequestSchema', () => {
});
});
describe('asLlmVision', () => {
it('keeps the three modes and reads anything else as auto', () => {
for (const mode of LLM_VISION_MODES) expect(asLlmVision(mode)).toBe(mode);
for (const other of [undefined, null, '', 'ON', true, false, 1]) expect(asLlmVision(other)).toBe('auto');
});
});
describe('adminCollabFeaturesRequestSchema', () => {
it('accepts a single computed key', () => {
expect(adminCollabFeaturesRequestSchema.safeParse({ chat: false }).success).toBe(true);
+60
View File
@@ -54,6 +54,28 @@ export const adminFeatureToggleRequestSchema = z.object({
});
export type AdminFeatureToggleRequest = z.infer<typeof adminFeatureToggleRequestSchema>;
/** What a feature toggle answers: the flag as it is stored now. */
export const adminFeatureToggleResponseSchema = z.object({
enabled: z.boolean(),
});
export type AdminFeatureToggleResponse = z.infer<typeof adminFeatureToggleResponseSchema>;
/**
* PUT /api/admin/google-quota (#1582): the most Google API calls TREK may make
* in one UTC day. Null or 0 removes the ceiling.
*/
export const googleQuotaUpdateRequestSchema = z.object({
daily_limit: z.number().int().min(0).max(10_000_000).nullable(),
});
export type GoogleQuotaUpdateRequest = z.infer<typeof googleQuotaUpdateRequestSchema>;
/** The ceiling as stored, today's count, and whether Google is paused until tomorrow. */
export interface GoogleQuotaStatus {
daily_limit: number | null;
used_today: number;
exhausted: boolean;
}
// Shared by all six packing-template create/update routes. `name` is optional so
// the service's 'Name is required' / 'Category name is required' / 'Item name is
// required' 400s stay the contract, and so the update routes keep treating a
@@ -80,6 +102,30 @@ export const adminAddonUpdateRequestSchema = z.object({
});
export type AdminAddonUpdateRequest = z.infer<typeof adminAddonUpdateRequestSchema>;
/**
* Whether the AI Parsing model is handed a photo, stored as `vision` on that
* addon's config. `auto` asks a local Ollama server what the model can do and
* means no for a cloud provider; `on` and `off` are the admin's word.
*/
export const LLM_VISION_MODES = ['auto', 'on', 'off'] as const;
export type LlmVision = (typeof LLM_VISION_MODES)[number];
/**
* The photos handed to a model that reads images. HEIC is not here: no provider
* TREK talks to reads it, and a browser picking from the camera roll hands over
* a JPEG anyway.
*/
export const LLM_PHOTO_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.webp'] as const;
/** GET /api/llm/capabilities: what the caller's AI model can be handed. */
export const llmCapabilitiesResponseSchema = z.object({ images: z.boolean() });
export type LlmCapabilitiesResponse = z.infer<typeof llmCapabilitiesResponseSchema>;
/** A stored or submitted value as a mode; anything else, a missing value included, is `auto`. */
export function asLlmVision(value: unknown): LlmVision {
return (LLM_VISION_MODES as readonly unknown[]).includes(value) ? (value as LlmVision) : 'auto';
}
// Fully partial — the client PUTs one computed key at a time.
export const adminCollabFeaturesRequestSchema = z.object({
chat: z.boolean().optional(),
@@ -95,6 +141,20 @@ export type AdminCollabFeaturesRequest = z.infer<typeof adminCollabFeaturesReque
export const adminNotificationPreferencesRequestSchema = z.record(z.string(), z.record(z.string(), z.boolean()));
export type AdminNotificationPreferencesRequest = z.infer<typeof adminNotificationPreferencesRequestSchema>;
/**
* What a user's notification cell starts as, set by the admin for the whole
* instance (#1536): `on` (the default), `off` (the user may still turn it on)
* or `blocked` (off for everyone, and the user cannot turn it on).
*/
export const NOTIFICATION_DEFAULTS = ['on', 'off', 'blocked'] as const;
export type NotificationDefault = (typeof NOTIFICATION_DEFAULTS)[number];
/** PUT /api/admin/notification-preferences/defaults: event → channel → default. Cells left out keep theirs. */
export const notificationDefaultsUpdateRequestSchema = z.object({
defaults: z.record(z.string().max(64), z.record(z.string().max(64), z.enum(NOTIFICATION_DEFAULTS))),
});
export type NotificationDefaultsUpdateRequest = z.infer<typeof notificationDefaultsUpdateRequestSchema>;
// Heterogeneous values, and `null` is meaningful — SettingsService treats it as
// "reset to the built-in default". z.record also rejects arrays and null bodies,
// preserving the route's object-only guard.
+168
View File
@@ -0,0 +1,168 @@
import {
aiAdminSettingsSchema,
aiApiKeyConnectRequestSchema,
aiChatgptFinishRequestSchema,
aiInstanceConnectionRequestSchema,
aiModelInfoSchema,
aiOpenrouterStartRequestSchema,
aiPrivacyAckRequestSchema,
aiRetentionSchema,
aiStatusResponseSchema,
} from './ai-connections.schema';
import { describe, expect, it } from 'vitest';
describe('aiRetentionSchema', () => {
it('keeps chats for a number of days, or forever as its own mode', () => {
expect(aiRetentionSchema.safeParse({ mode: 'days', days: 90 }).success).toBe(true);
expect(aiRetentionSchema.safeParse({ mode: 'forever' }).success).toBe(true);
});
it('has no sentinel day count', () => {
expect(aiRetentionSchema.safeParse({ mode: 'days', days: 0 }).success).toBe(false);
expect(aiRetentionSchema.safeParse({ mode: 'days', days: -1 }).success).toBe(false);
expect(aiRetentionSchema.safeParse({ mode: 'days', days: 3651 }).success).toBe(false);
});
});
describe('aiApiKeyConnectRequestSchema', () => {
it('takes a key for a cloud provider', () => {
expect(aiApiKeyConnectRequestSchema.safeParse({ kind: 'anthropic', apiKey: 'sk-ant-api03-abcdef' }).success).toBe(
true,
);
});
it('never lets a user connect ChatGPT by key or a server of their own', () => {
expect(aiApiKeyConnectRequestSchema.safeParse({ kind: 'chatgpt', apiKey: 'abcdefghij' }).success).toBe(false);
expect(aiApiKeyConnectRequestSchema.safeParse({ kind: 'custom', apiKey: 'abcdefghij' }).success).toBe(false);
expect(
aiApiKeyConnectRequestSchema.safeParse({ kind: 'openai', apiKey: 'sk-abcdefgh', baseUrl: 'http://10.0.0.2' })
.success,
).toBe(false);
});
it('refuses a key too short to be one', () => {
expect(aiApiKeyConnectRequestSchema.safeParse({ kind: 'gemini', apiKey: 'AIza' }).success).toBe(false);
});
});
describe('aiInstanceConnectionRequestSchema', () => {
it('takes an own server with a base URL and a model, the key optional', () => {
expect(
aiInstanceConnectionRequestSchema.safeParse({
kind: 'custom',
baseUrl: 'http://ollama:11434/v1',
model: 'qwen3:8b',
}).success,
).toBe(true);
expect(
aiInstanceConnectionRequestSchema.safeParse({ kind: 'custom', baseUrl: 'http://ollama:11434' }).success,
).toBe(false);
});
it('refuses a base URL that is not http(s)', () => {
expect(
aiInstanceConnectionRequestSchema.safeParse({ kind: 'custom', baseUrl: 'javascript:alert(1)', model: 'm' })
.success,
).toBe(false);
expect(
aiInstanceConnectionRequestSchema.safeParse({ kind: 'custom', baseUrl: 'file:///etc/passwd', model: 'm' })
.success,
).toBe(false);
});
it('gives a cloud key no base URL to redirect it to', () => {
expect(aiInstanceConnectionRequestSchema.safeParse({ kind: 'openrouter', apiKey: 'sk-or-v1-abc' }).success).toBe(
true,
);
expect(
aiInstanceConnectionRequestSchema.safeParse({
kind: 'anthropic',
apiKey: 'sk-ant-api03-abcdef',
baseUrl: 'https://evil.example',
}).success,
).toBe(false);
});
it('never shares a ChatGPT plan as the instance connection', () => {
expect(aiInstanceConnectionRequestSchema.safeParse({ kind: 'chatgpt', apiKey: 'abcdefghij' }).success).toBe(false);
});
});
describe('aiChatgptFinishRequestSchema', () => {
it('needs the flow id it was started with', () => {
const pastedUrl = 'http://127.0.0.1:1455/auth/callback?code=c&state=s';
expect(
aiChatgptFinishRequestSchema.safeParse({ flowId: '0d6c1f0e-2c3b-4a5d-8e9f-1a2b3c4d5e6f', pastedUrl }).success,
).toBe(true);
expect(aiChatgptFinishRequestSchema.safeParse({ flowId: 'flow-1', pastedUrl }).success).toBe(false);
});
});
describe('aiOpenrouterStartRequestSchema', () => {
it('takes only the scope, never a callback address', () => {
expect(aiOpenrouterStartRequestSchema.safeParse({ scope: 'user' }).success).toBe(true);
expect(
aiOpenrouterStartRequestSchema.safeParse({ scope: 'user', callbackUrl: 'https://evil.example' }).success,
).toBe(false);
});
});
describe('aiAdminSettingsSchema', () => {
it('takes the policy, the daily limit and the retention', () => {
expect(
aiAdminSettingsSchema.safeParse({
policy: 'instance_or_user',
dailyTurns: 50,
retention: { mode: 'days', days: 90 },
}).success,
).toBe(true);
expect(
aiAdminSettingsSchema.safeParse({ policy: 'instance', dailyTurns: 0, retention: { mode: 'forever' } }).success,
).toBe(false);
});
});
describe('aiStatusResponseSchema', () => {
it('describes a user on the instance connection with a quota', () => {
expect(
aiStatusResponseSchema.safeParse({
available: true,
policy: 'instance_or_user',
canConnectOwn: true,
effective: {
source: 'instance',
kind: 'anthropic',
model: 'claude-sonnet-4-5',
host: 'api.anthropic.com',
paidBy: 'instance',
},
own: null,
instance: { kind: 'anthropic', model: 'claude-sonnet-4-5', host: 'api.anthropic.com' },
quota: { used: 3, limit: 50 },
privacyAcked: false,
retention: { mode: 'days', days: 90 },
openrouterOAuth: true,
}).success,
).toBe(true);
});
});
describe('the Studio page image', () => {
it('AIVIS-001: a model may say whether it reads images, and a list that cannot say leaves it out', () => {
expect(aiModelInfoSchema.parse({ id: 'm', label: 'm', supportsTools: true, supportsImages: false })).toEqual({
id: 'm',
label: 'm',
supportsTools: true,
supportsImages: false,
});
expect(aiModelInfoSchema.safeParse({ id: 'm', label: 'm', supportsTools: true }).success).toBe(true);
});
it('AIVIS-002: the acknowledgement of page images is its own scope; no other scope exists', () => {
const ack = { kind: 'anthropic', host: 'api.anthropic.com' };
expect(aiPrivacyAckRequestSchema.safeParse(ack).success).toBe(true);
expect(aiPrivacyAckRequestSchema.safeParse({ ...ack, scope: 'studio_images' }).success).toBe(true);
expect(aiPrivacyAckRequestSchema.safeParse({ ...ack, scope: 'everything' }).success).toBe(false);
});
});
+226
View File
@@ -0,0 +1,226 @@
import { z } from 'zod';
/**
* AI connections contract for /api/ai (a user's own provider) and /api/admin/ai
* (the connection the instance provides for everyone, plus the assistant's
* admin settings).
*
* A connection is a provider kind, a model and a sealed credential. The
* credential never leaves the server: every view carries a `hint` (the last
* characters of a key, or the e-mail of a ChatGPT account) instead. Two kinds
* are bound to one side: `chatgpt` is a personal plan and never shared as the
* instance connection, `custom` reaches an arbitrary base URL and is admin-only
* (#1772). The server and the database both refuse the other combination.
*/
export const aiConnectionKindSchema = z.enum(['anthropic', 'openai', 'gemini', 'openrouter', 'chatgpt', 'custom']);
export type AiConnectionKind = z.infer<typeof aiConnectionKindSchema>;
/** The kinds a pasted API key can belong to. */
export const aiApiKeyKindSchema = z.enum(['anthropic', 'openai', 'gemini', 'openrouter']);
export type AiApiKeyKind = z.infer<typeof aiApiKeyKindSchema>;
/**
* Who provides the connection: `instance` only the admin's, `instance_or_user`
* the admin's unless a user connects their own, `user` everyone their own.
*/
export const aiPolicySchema = z.enum(['instance', 'instance_or_user', 'user']);
export type AiPolicy = z.infer<typeof aiPolicySchema>;
/** How long assistant chats are kept. Keeping them forever is its own mode, not a day count. */
export const aiRetentionSchema = z.discriminatedUnion('mode', [
z.object({ mode: z.literal('days'), days: z.number().int().min(1).max(3650) }),
z.object({ mode: z.literal('forever') }),
]);
export type AiRetention = z.infer<typeof aiRetentionSchema>;
export const aiConnectionScopeSchema = z.enum(['instance', 'user']);
export type AiConnectionScope = z.infer<typeof aiConnectionScopeSchema>;
export const aiConnectionStatusSchema = z.enum(['ok', 'needs_reauth', 'signed_out', 'error']);
export type AiConnectionStatus = z.infer<typeof aiConnectionStatusSchema>;
/** One model a connection offers. Only models that can call tools are listed for the assistant. */
export const aiModelInfoSchema = z.object({
id: z.string(),
label: z.string(),
supportsTools: z.boolean(),
free: z.boolean().optional(),
// The one a new connection starts on: the newest stable model of a capable line. Listed first.
recommended: z.boolean().optional(),
// Whether the model reads images (the Studio assistant's page image); left out where the list cannot say.
supportsImages: z.boolean().optional(),
});
export type AiModelInfo = z.infer<typeof aiModelInfoSchema>;
/** A stored connection as the client sees it, without its credential. */
export const aiConnectionViewSchema = z.object({
scope: aiConnectionScopeSchema,
kind: aiConnectionKindSchema,
model: z.string(),
// "…a1b2" for a key, the account e-mail for ChatGPT; never the secret itself.
hint: z.string().nullable(),
status: aiConnectionStatusSchema,
// The provider host the conversation goes to, named in the privacy notice.
host: z.string(),
});
export type AiConnectionView = z.infer<typeof aiConnectionViewSchema>;
// ── User: /api/ai ───────────────────────────────────────────────────────────
/** GET /api/ai/status: whether the assistant can run for this user, and on whose connection. */
export const aiStatusResponseSchema = z.object({
// False whenever no usable connection exists under the policy (fail-closed).
available: z.boolean(),
policy: aiPolicySchema,
// policy !== 'instance' and not the demo user.
canConnectOwn: z.boolean(),
effective: z
.object({
source: aiConnectionScopeSchema,
kind: aiConnectionKindSchema,
model: z.string(),
host: z.string(),
paidBy: aiConnectionScopeSchema,
})
.nullable(),
own: aiConnectionViewSchema.nullable(),
instance: z.object({ kind: aiConnectionKindSchema, model: z.string(), host: z.string() }).nullable(),
// Today's turns against the daily limit, only while the instance pays.
quota: z.object({ used: z.number().int(), limit: z.number().int() }).nullable(),
// Whether the user acknowledged that the effective kind@host receives their data.
privacyAcked: z.boolean(),
// Whether the user also let kind@host receive images of their Studio pages, with their own photos on them.
studioImagesAcked: z.boolean().optional(),
// Whether the model the effective connection runs on reads images (its name says so and no provider refused one for
// it since the server started), so a Studio page can go as a picture.
studioImages: z.boolean().optional(),
retention: aiRetentionSchema,
// OpenRouter's OAuth needs an https callback; without one the client offers the key field instead.
openrouterOAuth: z.boolean(),
});
export type AiStatusResponse = z.infer<typeof aiStatusResponseSchema>;
/** PUT /api/ai/connection: saving tests the key against the provider's model list first. */
export const aiApiKeyConnectRequestSchema = z
.object({
kind: aiApiKeyKindSchema,
apiKey: z.string().min(8).max(400),
model: z.string().max(200).optional(),
})
.strict();
export type AiApiKeyConnectRequest = z.infer<typeof aiApiKeyConnectRequestSchema>;
/** PATCH /api/ai/connection/model */
export const aiModelUpdateRequestSchema = z.object({ model: z.string().min(1).max(200) }).strict();
export type AiModelUpdateRequest = z.infer<typeof aiModelUpdateRequestSchema>;
/** POST /api/ai/connect/chatgpt/finish: the loopback address the browser landed on after sign-in. */
export const aiChatgptFinishRequestSchema = z
.object({
flowId: z.uuid(),
pastedUrl: z.string().max(4096),
})
.strict();
export type AiChatgptFinishRequest = z.infer<typeof aiChatgptFinishRequestSchema>;
/** POST /api/ai/connect/openrouter/start and /api/admin/ai/connect/openrouter/start */
export const aiOpenrouterStartRequestSchema = z.object({ scope: aiConnectionScopeSchema }).strict();
export type AiOpenrouterStartRequest = z.infer<typeof aiOpenrouterStartRequestSchema>;
/** POST /api/ai/connect/openrouter/finish */
export const aiOpenrouterFinishRequestSchema = z
.object({
flowId: z.uuid(),
code: z.string().min(1).max(512),
})
.strict();
export type AiOpenrouterFinishRequest = z.infer<typeof aiOpenrouterFinishRequestSchema>;
/** The answer of every connect/<provider>/start: where to send the browser, and the flow to finish. */
export const aiAuthStartResponseSchema = z.object({
flowId: z.uuid(),
authorizeUrl: z.url(),
expiresAt: z.string(),
});
export type AiAuthStartResponse = z.infer<typeof aiAuthStartResponseSchema>;
/** GET /api/ai/models, GET /api/admin/ai/models */
export const aiModelListResponseSchema = z.object({ models: z.array(aiModelInfoSchema) });
export type AiModelListResponse = z.infer<typeof aiModelListResponseSchema>;
/**
* POST /api/ai/privacy-ack: the user saw that kind@host receives their
* messages, or (`scope: 'studio_images'`) also images of their Studio pages.
*/
export const aiPrivacyAckRequestSchema = z
.object({
kind: aiConnectionKindSchema,
host: z.string().max(253),
scope: z.enum(['studio_images']).optional(),
})
.strict();
export type AiPrivacyAckRequest = z.infer<typeof aiPrivacyAckRequestSchema>;
// ── Admin: /api/admin/ai ────────────────────────────────────────────────────
// z.url() alone would accept javascript: and file:.
const httpUrl = z.url({ protocol: /^https?$/ });
const instanceApiKeyConnection = <K extends AiApiKeyKind>(kind: K) =>
z
.object({
kind: z.literal(kind),
apiKey: z.string().min(8).max(400),
model: z.string().max(200).optional(),
})
.strict();
/** PUT /api/admin/ai/connection: a cloud key, or an OpenAI-compatible server of the admin's own. */
export const aiInstanceConnectionRequestSchema = z.discriminatedUnion('kind', [
z
.object({
kind: z.literal('custom'),
baseUrl: httpUrl.max(500),
apiKey: z.string().max(400).optional(),
model: z.string().min(1).max(200),
})
.strict(),
instanceApiKeyConnection('anthropic'),
instanceApiKeyConnection('openai'),
instanceApiKeyConnection('gemini'),
instanceApiKeyConnection('openrouter'),
]);
export type AiInstanceConnectionRequest = z.infer<typeof aiInstanceConnectionRequestSchema>;
/** What the AI parsing addon is configured with, offered to prefill the instance connection. */
export const aiParsingPrefillSchema = z.object({
kind: aiConnectionKindSchema,
baseUrl: z.string().nullable(),
model: z.string(),
});
export type AiParsingPrefill = z.infer<typeof aiParsingPrefillSchema>;
/** GET /api/admin/ai/connection */
export const aiAdminConnectionResponseSchema = z.object({
connection: aiConnectionViewSchema.extend({ baseUrl: z.string().nullable() }).nullable(),
// Only while no instance connection exists and AI parsing is configured.
prefill: aiParsingPrefillSchema.nullable(),
});
export type AiAdminConnectionResponse = z.infer<typeof aiAdminConnectionResponseSchema>;
/** GET and PUT /api/admin/ai/settings */
export const aiAdminSettingsSchema = z
.object({
policy: aiPolicySchema,
dailyTurns: z.number().int().min(1).max(10000),
retention: aiRetentionSchema,
/**
* Whether the assistant may search the web, through the provider's own
* search (ChatGPT, Anthropic, OpenRouter); left out by older clients, it
* stays on.
*/
webSearch: z.boolean().default(true),
})
.strict();
export type AiAdminSettings = z.infer<typeof aiAdminSettingsSchema>;
@@ -3,11 +3,47 @@ import {
assignmentEndDayRequestSchema,
assignmentMoveRequestSchema,
assignmentParticipantsRequestSchema,
assignmentSchema,
assignmentTransportRequestSchema,
} from './assignment.schema';
import { describe, it, expect } from 'vitest';
describe('assignment Tours read-model merge', () => {
const ordinary = { id: 1, day_id: 2, place_id: 3, order_index: 0, place: { id: 3, name: 'Place' } };
it('keeps ordinary and legacy track places non-Tours without a facet identity', () => {
expect(assignmentSchema.parse(ordinary).tour_place_id).toBeUndefined();
const legacy = assignmentSchema.parse({ ...ordinary, tour_place_id: null, tour_route_geometry: null });
expect(legacy.tour_place_id).toBeNull();
expect(legacy.tour_route_geometry).toBeNull();
});
it('preserves nullable Tour fields, exclusion and incoming/outgoing segment modes', () => {
const fields = {
tour_place_id: 3,
tour_route_geometry: '[[48,11],[49,12]]',
route_excluded: true,
leg_transport_mode: 'walking',
incoming_leg_transport_mode: 'cycling',
};
expect(assignmentSchema.parse({ ...ordinary, ...fields })).toMatchObject(fields);
// MDT-02: the stage of a multi-day tour the day holds, null for the whole tour.
expect(assignmentSchema.parse({ ...ordinary, tour_stage_key: 'stop-1xx' }).tour_stage_key).toBe('stop-1xx');
expect(assignmentSchema.parse({ ...ordinary, tour_stage_key: null }).tour_stage_key).toBeNull();
expect(assignmentSchema.parse({ ...ordinary, tour_place_id: null, tour_route_geometry: null })).toMatchObject({
tour_place_id: null,
tour_route_geometry: null,
});
});
it('does not copy read-only joined Tours fields into create or move requests', () => {
const joined = { tour_place_id: 3, tour_route_geometry: '[[48,11],[49,12]]' };
expect(assignmentCreateRequestSchema.parse({ place_id: 3, ...joined })).toEqual({ place_id: 3 });
expect(assignmentMoveRequestSchema.parse({ new_day_id: 2, ...joined })).toEqual({ new_day_id: 2 });
});
});
it('requires a boolean for an explicit day end', () => {
expect(assignmentEndDayRequestSchema.parse({ end_day: true })).toEqual({ end_day: true });
expect(assignmentEndDayRequestSchema.parse({ end_day: false })).toEqual({ end_day: false });
@@ -22,6 +58,16 @@ describe('assignmentCreateRequestSchema', () => {
expect(assignmentCreateRequestSchema.safeParse({ place_id: '2', notes: null }).success).toBe(true);
expect(assignmentCreateRequestSchema.safeParse({}).success).toBe(false);
});
it('MDT-SH-012: takes the stage of a multi-day tour by the key of the stop it starts at', () => {
expect(assignmentCreateRequestSchema.parse({ place_id: 2, tour_stage_key: 'stop-1xx' })).toEqual({
place_id: 2,
tour_stage_key: 'stop-1xx',
});
for (const tour_stage_key of ['', 'short', 'not a key!', null, 3]) {
expect(assignmentCreateRequestSchema.safeParse({ place_id: 2, tour_stage_key }).success).toBe(false);
}
});
});
describe('assignmentMoveRequestSchema', () => {
@@ -1,4 +1,5 @@
import { assignmentPlaceSchema } from '../place/place.schema';
import { stationKeySchema } from '../tours/tours.schema';
import { z } from 'zod';
@@ -48,11 +49,20 @@ export const assignmentSchema = z.object({
// not a place (booking arrival / morning hotel). null = inherit the day default.
// Inert when the previous timeline element is a place.
incoming_leg_transport_mode: z.string().nullable().optional(),
// Kept on the day and on the map, but not part of the day's route (#2532).
route_excluded: z.boolean().optional(),
// The lodging booking that put this stop on the day, when one did. The day
// planner already shows that booking as its own overnight block, so it hides
// this row and leaves it to road trip mode, which is the view that needs the
// hotel in the driving chain. Null for every stop a traveller placed.
accommodation_id: z.number().nullable().optional(),
tour_place_id: z.number().nullable().optional(),
tour_route_geometry: z.string().nullable().optional(),
/**
* MDT-02: the stage of a multi-day tour this day holds, by the key of the
* stop the stage starts at; null where the day holds the whole tour or a place.
*/
tour_stage_key: z.string().nullable().optional(),
participants: z.array(assignmentParticipantSchema).optional(),
created_at: z.string().optional(),
place: assignmentPlaceSchema,
@@ -62,6 +72,12 @@ export type Assignment = z.infer<typeof assignmentSchema>;
export const assignmentCreateRequestSchema = z.object({
place_id: z.union([z.number(), z.string()]),
notes: z.string().nullable().optional(),
/**
* MDT-02: puts one stage of a multi-day tour on the day instead of the whole
* tour, by the key of the stop the stage starts at (the tour list's
* `stage_stops`). A stage is on one day at most.
*/
tour_stage_key: stationKeySchema.optional(),
});
export type AssignmentCreateRequest = z.infer<typeof assignmentCreateRequestSchema>;
@@ -113,6 +129,12 @@ export const assignmentTransportRequestSchema = z.object({
});
export type AssignmentTransportRequest = z.infer<typeof assignmentTransportRequestSchema>;
/** Take a stop out of the day's route, or put it back (#2532). */
export const assignmentRouteRequestSchema = z.object({
excluded: z.boolean(),
});
export type AssignmentRouteRequest = z.infer<typeof assignmentRouteRequestSchema>;
export const assignmentParticipantsRequestSchema = z.object({
user_ids: z.array(z.number()),
});
@@ -0,0 +1,44 @@
data: {"type":"start","messageId":"msg-12"}
data: {"type":"tool-output-available","toolCallId":"7c1e2d3a-0b4f-4e8a-9d6c-1f2e3a4b5c6d","output":{"tour":{"place_id":77,"name":"Ridge walk"}}}
data: {"type":"data-trek-applied","data":{"toolCallId":"7c1e2d3a-0b4f-4e8a-9d6c-1f2e3a4b5c6d","entity":"tour","ids":[77],"dayId":32,"undoUntil":"2026-06-11T09:15:00Z"}}
data: {"type":"data-trek-card","data":{"toolCallId":"7c1e2d3a-0b4f-4e8a-9d6c-1f2e3a4b5c6d","card":{"kind":"tourRoute"}}}
data: {"type":"start-step"}
data: {"type":"tool-input-start","toolCallId":"toolu_02","toolName":"list_tours"}
data: {"type":"tool-input-available","toolCallId":"toolu_02","toolName":"list_tours","input":{}}
data: {"type":"tool-output-available","toolCallId":"toolu_02","output":{"tours":[{"place_id":77,"name":"Ridge walk"}]}}
data: {"type":"data-trek-card","data":{"toolCallId":"toolu_02","card":{"kind":"tourList"}}}
data: {"type":"finish-step"}
data: {"type":"start-step"}
data: {"type":"text-start","id":"txt-0"}
data: {"type":"text-delta","id":"txt-0","delta":"The ridge walk is on Friday now. "}
data: {"type":"text-delta","id":"txt-0","delta":"A lake loop would fit on Saturday."}
data: {"type":"text-end","id":"txt-0"}
data: {"type":"tool-input-start","toolCallId":"9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d","toolName":"create_hike"}
data: {"type":"tool-input-available","toolCallId":"9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d","toolName":"create_hike","input":{"name":"Lake loop","round_trip":true}}
data: {"type":"tool-approval-request","approvalId":"9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d","toolCallId":"9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d"}
data: {"type":"data-trek-change","data":{"toolCallId":"9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d","verbKey":"addTour","subject":"Lake loop","rows":[{"op":"add","labelKey":"route","before":null,"after":"Car park → Lake → Car park"}],"dayId":null,"placeIds":[],"undoable":true,"card":{"kind":"tourRoute"}}}
data: {"type":"data-trek-quota","data":{"used":4,"limit":50}}
data: {"type":"finish","finishReason":"tool-calls"}
data: [DONE]
@@ -0,0 +1,38 @@
data: {"type":"start","messageId":"msg-12"}
data: {"type":"data-trek-thread","data":{"threadId":7,"title":"Fit the Golden Pavilion into Friday"}}
data: {"type":"start-step"}
data: {"type":"tool-input-start","toolCallId":"toolu_01","toolName":"get_trip_summary"}
data: {"type":"tool-input-available","toolCallId":"toolu_01","toolName":"get_trip_summary","input":{}}
data: {"type":"tool-output-available","toolCallId":"toolu_01","output":{"title":"Kyoto in June","days":[{"id":31,"date":"2026-06-11","places":3},{"id":32,"date":"2026-06-12","places":1}]}}
data: {"type":"finish-step"}
data: {"type":"start-step"}
data: {"type":"text-start","id":"txt-0"}
data: {"type":"text-delta","id":"txt-0","delta":"Friday has room in the afternoon. "}
data: {"type":"text-delta","id":"txt-0","delta":"I would add Kinkaku-ji there."}
data: {"type":"text-end","id":"txt-0"}
data: {"type":"tool-input-start","toolCallId":"3f2b8c1e-6d4a-4f7b-9e2c-5a1d8b7c6e40","toolName":"create_and_assign_place"}
data: {"type":"tool-input-available","toolCallId":"3f2b8c1e-6d4a-4f7b-9e2c-5a1d8b7c6e40","toolName":"create_and_assign_place","input":{"dayId":32,"name":"Kinkaku-ji","address":"1 Kinkakujicho, Kita Ward, Kyoto","lat":35.0394,"lng":135.7292}}
data: {"type":"tool-approval-request","approvalId":"3f2b8c1e-6d4a-4f7b-9e2c-5a1d8b7c6e40","toolCallId":"3f2b8c1e-6d4a-4f7b-9e2c-5a1d8b7c6e40"}
data: {"type":"data-trek-change","data":{"toolCallId":"3f2b8c1e-6d4a-4f7b-9e2c-5a1d8b7c6e40","verbKey":"addPlaceToDay","subject":"Kinkaku-ji","rows":[{"op":"add","labelKey":"day","before":null,"after":"Day 2, Fri 12 Jun"},{"op":"add","labelKey":"address","before":null,"after":"1 Kinkakujicho, Kita Ward, Kyoto"}],"dayId":32,"placeIds":[],"undoable":true}}
data: {"type":"data-trek-quota","data":{"used":3,"limit":50}}
data: {"type":"finish","finishReason":"tool-calls"}
data: [DONE]
@@ -0,0 +1,34 @@
import {
assistantAttachmentIdSchema,
assistantKeepFileArgsSchema,
assistantReadAttachedFileArgsSchema,
} from './assistant-attachments.schema';
import { describe, expect, it } from 'vitest';
const ID = '0b7c2f0e-6f6d-4a8e-9b1a-3d2c1e0f9a87';
describe('assistant attachments contract', () => {
it('takes an attachment only by a uuid, never a path or a number', () => {
expect(assistantAttachmentIdSchema.safeParse(ID).success).toBe(true);
for (const bad of ['../x', '42', '', 42, null]) {
expect(assistantAttachmentIdSchema.safeParse(bad).success).toBe(false);
}
});
it('reads the model arguments of read_attached_file and drops what the server sets itself', () => {
expect(assistantReadAttachedFileArgsSchema.parse({ attachmentId: ID, name: 'x.pdf' })).toEqual({
attachmentId: ID,
});
expect(assistantReadAttachedFileArgsSchema.safeParse({}).success).toBe(false);
});
it('keeps a file with plain ids of the trip, never a string or a negative id, and a short description', () => {
const kept = { attachmentId: ID, reservation_id: 5, budget_item_id: 7, place_id: 9, description: 'Airbnb' };
expect(assistantKeepFileArgsSchema.parse({ ...kept, name: 'x.pdf' })).toEqual(kept);
expect(assistantKeepFileArgsSchema.parse({ attachmentId: ID })).toEqual({ attachmentId: ID });
for (const bad of [{ reservation_id: '5' }, { budget_item_id: -1 }, { description: 'x'.repeat(1001) }]) {
expect(assistantKeepFileArgsSchema.safeParse({ attachmentId: ID, ...bad }).success).toBe(false);
}
});
});
@@ -0,0 +1,40 @@
import { idSchema } from '../common/primitives.schema';
import { fileUpdateRequestSchema } from '../file/file.schema';
import { z } from 'zod';
/**
* A file the user attached in the trip chat, as the conversation knows it.
*
* The server keeps the file with the thread under a random id, which the
* message's `attachment` part carries. The id never reaches anything but the
* thread it was attached in: every read answers an id of another thread or
* another user the way it answers one that does not exist.
*/
export const assistantAttachmentIdSchema = z.uuid();
export type AssistantAttachmentId = z.infer<typeof assistantAttachmentIdSchema>;
/**
* What the model calls `read_attached_file` with: the attachment, by the id
* the user's message names. The server adds the file's name and where its
* text would go to the held call before the user sees it; those are no input.
*/
export const assistantReadAttachedFileArgsSchema = z.object({
attachmentId: assistantAttachmentIdSchema,
});
export type AssistantReadAttachedFileArgs = z.infer<typeof assistantReadAttachedFileArgsSchema>;
/**
* What the model calls `keep_attached_file` with: the attachment, and what
* of the trip the kept file is attached to, the fields a trip file's update
* takes (`fileUpdateRequestSchema`) as plain ids. Every id must name a row of
* the same trip; the server checks that when the user applies the change.
*/
export const assistantKeepFileArgsSchema = z.object({
attachmentId: assistantAttachmentIdSchema,
reservation_id: idSchema.optional(),
budget_item_id: idSchema.optional(),
place_id: idSchema.optional(),
description: fileUpdateRequestSchema.shape.description.unwrap().max(1000).optional(),
});
export type AssistantKeepFileArgs = z.infer<typeof assistantKeepFileArgsSchema>;
@@ -0,0 +1,61 @@
import {
ASSISTANT_JOURNEY_SURFACES,
assistantScopeKey,
assistantScopeSchema,
HOME_ASSISTANT_SCOPE,
} from './assistant-scope.schema';
import { assistantFocusSchema } from './assistant.schema';
import { describe, expect, it } from 'vitest';
describe('assistantScopeSchema', () => {
it('ASTSCOPE-001: is a trip or a journey, each by its own positive id', () => {
expect(assistantScopeSchema.parse({ kind: 'trip', tripId: 5 })).toEqual({ kind: 'trip', tripId: 5 });
expect(assistantScopeSchema.parse({ kind: 'journey', journeyId: 12 })).toEqual({ kind: 'journey', journeyId: 12 });
expect(assistantScopeSchema.safeParse({ kind: 'trip', tripId: 0 }).success).toBe(false);
expect(assistantScopeSchema.safeParse({ kind: 'journey', tripId: 5 }).success).toBe(false);
});
it('ASTSCOPE-002: is never both and never anything else', () => {
expect(assistantScopeSchema.safeParse({ kind: 'trip', tripId: 5, journeyId: 12 }).success).toBe(false);
expect(assistantScopeSchema.safeParse({ kind: 'collection', collectionId: 3 }).success).toBe(false);
expect(assistantScopeSchema.safeParse({}).success).toBe(false);
});
it('ASTSCOPE-003: keys a trip and a journey with the same id apart', () => {
expect(assistantScopeKey({ kind: 'trip', tripId: 7 })).toBe('trip:7');
expect(assistantScopeKey({ kind: 'journey', journeyId: 7 })).toBe('journey:7');
});
it('ASTSCOPE-007: a journey names the page it is asked from, which never changes its key', () => {
const journal = { kind: 'journey', journeyId: 7, surface: 'journal' } as const;
expect(assistantScopeSchema.parse(journal)).toEqual(journal);
expect(assistantScopeSchema.safeParse({ ...journal, surface: 'planner' }).success).toBe(false);
expect(assistantScopeSchema.safeParse({ kind: 'trip', tripId: 7, surface: 'journal' }).success).toBe(false);
expect(assistantScopeKey(journal)).toBe(assistantScopeKey({ kind: 'journey', journeyId: 7, surface: 'studio' }));
expect(ASSISTANT_JOURNEY_SURFACES).toEqual(['studio', 'journal']);
});
it('ASTSCOPE-006: has a home scope that names no trip and no journey', () => {
expect(assistantScopeSchema.parse({ kind: 'home' })).toEqual(HOME_ASSISTANT_SCOPE);
expect(assistantScopeSchema.safeParse({ kind: 'home', tripId: 5 }).success).toBe(false);
expect(assistantScopeSchema.safeParse({ kind: 'home', journeyId: 12 }).success).toBe(false);
expect(assistantScopeKey(HOME_ASSISTANT_SCOPE)).toBe('home');
});
});
describe('assistantFocusSchema in the Studio', () => {
it('ASTSCOPE-004: carries the page on screen and up to 30 selected elements, by their document ids', () => {
const focus = { spreadId: 'sp-ab12', elementIds: ['p-1', 'p-2'] };
expect(assistantFocusSchema.parse(focus)).toEqual(focus);
expect(assistantFocusSchema.safeParse({ spreadId: 'sp ab' }).success).toBe(false);
expect(assistantFocusSchema.safeParse({ spreadId: 'x'.repeat(41) }).success).toBe(false);
const many = Array.from({ length: 31 }, (_, i) => `p-${i}`);
expect(assistantFocusSchema.safeParse({ elementIds: many }).success).toBe(false);
});
it('ASTSCOPE-005: leaves the planner focus as it was', () => {
expect(assistantFocusSchema.parse({ dayId: 4, placeIds: [1] })).toEqual({ dayId: 4, placeIds: [1] });
expect(assistantFocusSchema.safeParse({ dayId: 4, page: 2 }).success).toBe(false);
});
});
@@ -0,0 +1,45 @@
import { idSchema } from '../common/primitives.schema';
import { z } from 'zod';
/**
* What an assistant conversation is about: a trip (the planner's chat), a
* journey (the chat in TREK Studio, which works on the journey's book) or no
* single one (`home`, the chat on the dashboard, Vacay, Atlas, collections and
* settings, which knows all of the user's trips and works on what belongs to
* none of them). A thread belongs to exactly one of them, and the tools a turn
* offers, the context it reads and the routes it is reached under follow from
* it: `/api/trips/:tripId/assistant`, `/api/journeys/:journeyId/assistant` and
* `/api/assistant`.
*/
/**
* The two pages a journey's conversation is held on: the book in TREK Studio,
* and the journal itself (its entries, photos and settings). They share the
* journey's threads; what a turn offers and what it is told follow the page.
*/
export const ASSISTANT_JOURNEY_SURFACES = ['studio', 'journal'] as const;
export const assistantJourneySurfaceSchema = z.enum(ASSISTANT_JOURNEY_SURFACES);
export type AssistantJourneySurface = z.infer<typeof assistantJourneySurfaceSchema>;
export const assistantScopeSchema = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('trip'), tripId: idSchema }).strict(),
z
.object({
kind: z.literal('journey'),
journeyId: idSchema,
/** The page a request comes from; left out, the Studio's. Never part of the key: both pages keep one list. */
surface: assistantJourneySurfaceSchema.optional(),
})
.strict(),
z.object({ kind: z.literal('home') }).strict(),
]);
export type AssistantScope = z.infer<typeof assistantScopeSchema>;
/** The scope of the chat outside any one trip or journey. */
export const HOME_ASSISTANT_SCOPE: AssistantScope = { kind: 'home' };
/** The key a scope's conversations are kept under on a client: `trip:5`, `journey:12`, `home`. */
export function assistantScopeKey(scope: AssistantScope): string {
if (scope.kind === 'trip') return `trip:${scope.tripId}`;
return scope.kind === 'journey' ? `journey:${scope.journeyId}` : 'home';
}
@@ -0,0 +1,22 @@
import { assistantShareRequestSchema } from './assistant-share.schema';
import { describe, expect, it } from 'vitest';
describe('assistantShareRequestSchema', () => {
it('takes one to 5000 characters and trims them', () => {
expect(assistantShareRequestSchema.parse({ text: ' Day 2 is set. ' })).toEqual({ text: 'Day 2 is set.' });
expect(assistantShareRequestSchema.safeParse({ text: 'x' }).success).toBe(true);
expect(assistantShareRequestSchema.safeParse({ text: 'x'.repeat(5000) }).success).toBe(true);
});
it('refuses empty or blank text and text past the chat limit', () => {
expect(assistantShareRequestSchema.safeParse({ text: '' }).success).toBe(false);
expect(assistantShareRequestSchema.safeParse({ text: ' \n\t ' }).success).toBe(false);
expect(assistantShareRequestSchema.safeParse({ text: 'x'.repeat(5001) }).success).toBe(false);
expect(assistantShareRequestSchema.safeParse({}).success).toBe(false);
});
it('takes nothing but the text, so the origin is never the client to set', () => {
expect(assistantShareRequestSchema.safeParse({ text: 'hi', origin: 'assistant' }).success).toBe(false);
});
});
@@ -0,0 +1,15 @@
import { z } from 'zod';
/**
* POST /api/trips/:tripId/assistant/threads/:threadId/messages/:messageId/share:
* posts the text of an assistant answer to the trip's chat, marked as shared
* from the assistant. The text is what the user saw in the preview; the
* server checks that the answer is theirs and in this trip, not the words.
* It answers with the chat message (`collabMessageResponseSchema`).
*/
export const assistantShareRequestSchema = z
.object({
text: z.string().trim().min(1).max(5000),
})
.strict();
export type AssistantShareRequest = z.infer<typeof assistantShareRequestSchema>;
@@ -0,0 +1,87 @@
import {
ASSISTANT_PAGE_IMAGE,
assistantPageRenderSchema,
assistantPageViewSchema,
assistantRenderUploadRequestSchema,
drawnPhotoIdsOf,
previewBookPageRequestSchema,
} from './assistant-vision.schema';
import { assistantMessagePartSchema, uiStreamChunkSchema } from './assistant.schema';
import { describe, expect, it } from 'vitest';
const RENDER = {
requestId: '0b6f7c1e-3a52-4d8e-9a7b-2f1e0c9d8a76',
threadId: 4,
spreadId: 'sp-1',
bookVersion: 7,
hiddenPhotoIds: [12],
};
const VIEW = { spreadId: 'sp-1', bookVersion: 7, width: 1280, height: 640, bytes: 182_000, description: 'Page 2' };
describe('the Studio page image', () => {
it('ASTVIS-001: a render request names the page, the version and the photos left out; a proposal its page', () => {
expect(assistantPageRenderSchema.safeParse(RENDER).success).toBe(true);
// A proposal comes as the page the server applied it to, for the Studio to draw as it is.
const spread = { id: 'sp-1', role: 'inner', background: '#ffffff', elements: [], parked: [], entryId: null };
expect(assistantPageRenderSchema.parse({ ...RENDER, spread }).spread).toEqual(spread);
const notAPage = { ...spread, background: 'white' };
expect(assistantPageRenderSchema.safeParse({ ...RENDER, spread: notAPage }).success).toBe(false);
expect(assistantPageRenderSchema.safeParse({ ...RENDER, requestId: 'r1' }).success).toBe(false);
expect(assistantPageRenderSchema.safeParse({ ...RENDER, spreadId: '../x' }).success).toBe(false);
});
it('ASTVIS-002: a page view keeps the size of the image and the description, never the image', () => {
expect(assistantPageViewSchema.parse({ ...VIEW, data: 'aGVsbG8=' })).toEqual(VIEW);
const textOnly = { ...VIEW, width: null, height: null, bytes: null };
expect(assistantPageViewSchema.safeParse(textOnly).success).toBe(true);
});
it('ASTVIS-003: the page view is a stored part; the render request and the page view are stream chunks', () => {
expect(assistantMessagePartSchema.safeParse({ type: 'data-trek-page-view', data: VIEW }).success).toBe(true);
const request = { type: 'data-trek-render-request', data: RENDER, transient: true };
expect(uiStreamChunkSchema.safeParse(request).success).toBe(true);
expect(uiStreamChunkSchema.safeParse({ type: 'data-trek-page-view', data: VIEW }).success).toBe(true);
});
it('ASTVIS-004: an upload reads its text fields as multipart sends them, and its photo ids as a list', () => {
const fields = { bookVersion: '7', spreadId: 'sp-1', drawnPhotoIds: '12,30' };
expect(assistantRenderUploadRequestSchema.parse(fields)).toEqual({ ...fields, bookVersion: 7 });
expect(drawnPhotoIdsOf('12,30')).toEqual([12, 30]);
expect(drawnPhotoIdsOf('')).toEqual([]);
expect(drawnPhotoIdsOf(undefined)).toEqual([]);
});
it('ASTVIS-006: a preview names a page and may carry the ops of a proposed edit, nothing else', () => {
expect(previewBookPageRequestSchema.safeParse({ spreadId: 'sp-1' }).success).toBe(true);
const ops = [{ op: 'background', color: '#ffffff' }];
expect(previewBookPageRequestSchema.safeParse({ spreadId: 'sp-1', ops }).success).toBe(true);
expect(previewBookPageRequestSchema.safeParse({ spreadId: 'sp-1', ops: [] }).success).toBe(false);
expect(previewBookPageRequestSchema.safeParse({ spreadId: 'sp-1', journeyId: 3 }).success).toBe(false);
});
it('ASTVIS-005: an upload refuses ids that are no list of numbers, and fields it does not know', () => {
const base = { bookVersion: '7', spreadId: 'sp-1' };
expect(assistantRenderUploadRequestSchema.safeParse({ ...base, drawnPhotoIds: '12,,3' }).success).toBe(false);
expect(assistantRenderUploadRequestSchema.safeParse({ ...base, drawnPhotoIds: '1;2' }).success).toBe(false);
expect(assistantRenderUploadRequestSchema.safeParse({ ...base, data: 'x' }).success).toBe(false);
expect(assistantRenderUploadRequestSchema.safeParse({ ...base, bookVersion: '-1' }).success).toBe(false);
});
it('ASTVIS-007: a page may name as many photos as its frames and map stops hold, up to the cap', () => {
const many = Array.from({ length: ASSISTANT_PAGE_IMAGE.maxPagePhotos }, (_, i) => i + 1);
expect(assistantPageRenderSchema.safeParse({ ...RENDER, hiddenPhotoIds: many }).success).toBe(true);
const tooMany = [...many, ASSISTANT_PAGE_IMAGE.maxPagePhotos + 1];
expect(assistantPageRenderSchema.safeParse({ ...RENDER, hiddenPhotoIds: tooMany }).success).toBe(false);
const fields = { bookVersion: '7', spreadId: 'sp-1', drawnPhotoIds: many.join(',') };
expect(assistantRenderUploadRequestSchema.safeParse(fields).success).toBe(true);
});
it('ASTVIS-008: a preview and a render request may name a design draft, by an id that is no path', () => {
expect(previewBookPageRequestSchema.safeParse({ spreadId: 'sp-1', designId: 'd-1a2b' }).success).toBe(true);
expect(previewBookPageRequestSchema.safeParse({ spreadId: 'sp-1', designId: '../d' }).success).toBe(false);
expect(assistantPageRenderSchema.parse({ ...RENDER, designId: 'd-1a2b' }).designId).toBe('d-1a2b');
expect(assistantPageRenderSchema.safeParse({ ...RENDER, designId: 'd/1' }).success).toBe(false);
});
});
@@ -0,0 +1,123 @@
import { bookSpreadIdSchema } from '../book/book-op-ids';
import { bookDesignIdSchema, editBookPageArgs } from '../book/book-ops.schema';
import { bookSpreadSchema } from '../book/book.schema';
import { idSchema } from '../common/primitives.schema';
import { z } from 'zod';
/**
* The Studio assistant looking at a page (journey-studio.md section 3). The
* server cannot draw a page, so it asks the Studio tab that holds the turn's
* stream for one: a `data-trek-render-request` chunk names the page, the book
* version and the photos to leave out, the tab draws that one page and
* uploads it as an image, and the turn hands it to a model that reads images,
* beside the page's description. Nothing of the image is kept: the message
* stores what was looked at (`data-trek-page-view`), never the bytes.
*/
export const ASSISTANT_PAGE_IMAGE = {
/** The long edge a page is drawn at, in pixels, and the JPEG quality the Studio sends it with. */
longEdge: 1280,
jpegQuality: 0.82,
/** What the server takes at most: the bytes, the long edge and the pixels of one image. */
maxBytes: 1024 * 1024,
maxEdge: 2048,
maxPixels: 4_000_000,
/** Photos one page may name as hidden or drawn: its frames and the pictures its maps mark stops with. */
maxPagePhotos: 1000,
/** How long a turn waits for a page image before it goes on with the description alone. */
timeoutMs: 15_000,
/** Images one model request carries at most, one per tool answer; earlier ones go as their text. */
perRequest: 3,
/** Previews of a proposed change one step and one turn may ask for. */
previewsPerStep: 3,
previewsPerTurn: 8,
/**
* Previews a turn may ask for once a whole-book design is in play (it
* called design_book or revise_book_design, or looks at a draft): a design
* is judged on many pages, the cover twice. Still three images a request.
*/
previewsPerDesignTurn: 16,
} as const;
/**
* A page the server asks the Studio to draw, streamed while the turn waits.
* `spread` is a proposal's page as the server applied it (a preview): the
* Studio draws that one in place of the stored page; without it the page is
* drawn as the book stands at `bookVersion`. The photos in `hiddenPhotoIds`
* are drawn as empty frames, and a map stop showing one as a plain dot: only
* the asking user's own photos leave the browser.
*/
export const assistantPageRenderSchema = z.object({
requestId: z.uuid(),
threadId: idSchema,
spreadId: bookSpreadIdSchema,
bookVersion: z.number().int().nonnegative(),
/**
* A proposal's page as the server applied it, with the journey's photos,
* words and figures: the Studio draws this one in place of the stored page,
* nothing saved.
*/
spread: bookSpreadSchema.optional(),
/** A page of a design draft (design_book) rather than of the book: the Studio draws it from the draft. */
designId: bookDesignIdSchema.optional(),
hiddenPhotoIds: z.array(idSchema).max(ASSISTANT_PAGE_IMAGE.maxPagePhotos),
});
export type AssistantPageRender = z.infer<typeof assistantPageRenderSchema>;
/**
* What a turn looked at, as the message keeps it: the page, the version, the
* image's size when one reached the model (null when the model read the
* description alone), and the description itself. Never the image.
*/
export const assistantPageViewSchema = z.object({
spreadId: bookSpreadIdSchema,
bookVersion: z.number().int().nonnegative(),
width: z.number().int().positive().nullable(),
height: z.number().int().positive().nullable(),
bytes: z.number().int().positive().nullable(),
description: z.string().max(20_000),
});
export type AssistantPageView = z.infer<typeof assistantPageViewSchema>;
/**
* `preview_book_page`, a read of the Studio turn's own (no MCP tool): one page
* as it stands, or with `ops` as an `edit_book_page` with them would leave it,
* nothing saved. It answers the page's description and findings, and a model
* that reads images also gets the page as the Studio draws it.
*/
export const previewBookPageRequestSchema = z.strictObject({
spreadId: bookSpreadIdSchema,
ops: editBookPageArgs.ops.optional(),
/** Look at the page of a design draft instead of the book's (design_book's design_id). */
designId: bookDesignIdSchema.optional(),
});
export type PreviewBookPageRequest = z.infer<typeof previewBookPageRequestSchema>;
/**
* POST /api/journeys/:journeyId/assistant/threads/:threadId/renders/:requestId,
* multipart: the image in the field `image`, these as text fields beside it.
* `drawnPhotoIds` lists the photos the image shows, comma-separated; the
* server refuses the image when one of them is not the user's to show.
*/
export const assistantRenderUploadRequestSchema = z
.object({
bookVersion: z.coerce.number().int().nonnegative(),
spreadId: bookSpreadIdSchema,
drawnPhotoIds: z
.string()
.max(ASSISTANT_PAGE_IMAGE.maxPagePhotos * 13)
.regex(/^(?:\d{1,12}(?:,\d{1,12})*)?$/)
.optional(),
})
.strict();
export type AssistantRenderUploadRequest = z.infer<typeof assistantRenderUploadRequestSchema>;
/** The answer to an image the turn took; anything it did not take is refused with an error instead. */
export const assistantRenderUploadResponseSchema = z.object({ accepted: z.literal(true) });
export type AssistantRenderUploadResponse = z.infer<typeof assistantRenderUploadResponseSchema>;
/** The photo ids of an upload's `drawnPhotoIds` field. */
export function drawnPhotoIdsOf(field: string | undefined): number[] {
return field ? field.split(',').map(Number) : [];
}
@@ -0,0 +1,496 @@
/// <reference types="node" />
import {
ASSISTANT_CHANGE_LABEL_KEYS,
assistantAddFoundPlaceRequestSchema,
assistantAddFoundPlaceResponseSchema,
assistantAttachmentRequestSchema,
assistantChangePreviewSchema,
assistantChangePreviewWriteSchema,
assistantChatRequestSchema,
assistantDecisionsRequestSchema,
assistantFoundPlaceSchema,
assistantInsertFoundPlaceRequestSchema,
assistantMessageSchema,
assistantPlacesSchema,
assistantStopRequestSchema,
assistantWeatherSchema,
isAssistantTourFile,
UI_STREAM_DONE,
uiStreamChunkSchema,
type UiStreamChunk,
} from './assistant.schema';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
const ctx = { locale: 'de', timeZone: 'Europe/Berlin' };
/** The `data:` payloads of an SSE body, in order. */
const dataEvents = (body: string) =>
body
.split('\n\n')
.filter((event) => event.startsWith('data: '))
.map((event) => event.slice('data: '.length));
const fixture = readFileSync(fileURLToPath(new URL('./__fixtures__/ui-stream.v1.txt', import.meta.url)), 'utf8');
describe('assistantChatRequestSchema', () => {
it('takes a first message without a thread and trims the text', () => {
const parsed = assistantChatRequestSchema.parse({ ...ctx, threadId: null, text: ' Plan day 2 ' });
expect(parsed.text).toBe('Plan day 2');
});
it('refuses blank or overlong text, a bad thread id and unknown keys', () => {
expect(assistantChatRequestSchema.safeParse({ ...ctx, threadId: null, text: ' ' }).success).toBe(false);
expect(assistantChatRequestSchema.safeParse({ ...ctx, threadId: null, text: 'x'.repeat(32_001) }).success).toBe(
false,
);
expect(assistantChatRequestSchema.safeParse({ ...ctx, threadId: 0, text: 'hi' }).success).toBe(false);
expect(assistantChatRequestSchema.safeParse({ ...ctx, threadId: null, text: 'hi', tripId: 9 }).success).toBe(false);
});
it('carries a focus of at most 20 places', () => {
const many = Array.from({ length: 21 }, (_, i) => i + 1);
expect(
assistantChatRequestSchema.safeParse({ ...ctx, threadId: 3, text: 'hi', focus: { dayId: 4, placeIds: [1] } })
.success,
).toBe(true);
expect(
assistantChatRequestSchema.safeParse({ ...ctx, threadId: 3, text: 'hi', focus: { placeIds: many } }).success,
).toBe(false);
});
it('needs the locale and time zone', () => {
expect(assistantChatRequestSchema.safeParse({ threadId: null, text: 'hi' }).success).toBe(false);
});
it('names the page of a journey it is asked from, the Studio or the journal, and nothing else', () => {
const base = { ...ctx, threadId: null, text: 'hi' };
expect(assistantChatRequestSchema.parse({ ...base, surface: 'journal' }).surface).toBe('journal');
expect(assistantChatRequestSchema.parse({ ...base, surface: 'studio' }).surface).toBe('studio');
expect(assistantChatRequestSchema.parse(base).surface).toBeUndefined();
expect(assistantChatRequestSchema.safeParse({ ...base, surface: 'planner' }).success).toBe(false);
const decision = { toolCallId: 'a', approved: true };
expect(assistantDecisionsRequestSchema.parse({ ...ctx, decisions: [decision], surface: 'journal' }).surface).toBe(
'journal',
);
expect(assistantDecisionsRequestSchema.safeParse({ ...ctx, decisions: [decision], surface: 'x' }).success).toBe(
false,
);
});
});
describe('assistantAttachmentRequestSchema', () => {
it('reads the multipart text fields, the thread id from its text', () => {
expect(assistantAttachmentRequestSchema.parse({ ...ctx })).toEqual(ctx);
expect(assistantAttachmentRequestSchema.parse({ ...ctx, threadId: '12' })).toEqual({ ...ctx, threadId: 12 });
});
it('refuses a bad thread id, unknown fields and a missing context', () => {
for (const threadId of ['0', '-1', 'abc', '1.5']) {
expect(assistantAttachmentRequestSchema.safeParse({ ...ctx, threadId }).success, threadId).toBe(false);
}
expect(assistantAttachmentRequestSchema.safeParse({ ...ctx, text: 'hi' }).success).toBe(false);
expect(assistantAttachmentRequestSchema.safeParse({ threadId: '3' }).success).toBe(false);
});
});
describe('assistantDecisionsRequestSchema', () => {
it('takes one to twelve decisions', () => {
const decision = { toolCallId: 'a', approved: true };
expect(assistantDecisionsRequestSchema.safeParse({ ...ctx, decisions: [decision] }).success).toBe(true);
expect(assistantDecisionsRequestSchema.safeParse({ ...ctx, decisions: [] }).success).toBe(false);
expect(
assistantDecisionsRequestSchema.safeParse({ ...ctx, decisions: Array.from({ length: 51 }, () => decision) })
.success,
).toBe(false);
});
it('never takes arguments for a call, only the decision', () => {
expect(
assistantDecisionsRequestSchema.safeParse({
...ctx,
decisions: [{ toolCallId: 'a', approved: true, args: { name: 'x' } }],
}).success,
).toBe(false);
});
});
describe('assistantStopRequestSchema', () => {
it('is an empty JSON object', () => {
expect(assistantStopRequestSchema.safeParse({}).success).toBe(true);
expect(assistantStopRequestSchema.safeParse({ force: true }).success).toBe(false);
});
});
describe('assistantChangePreviewSchema', () => {
const preview = {
toolCallId: 'c1',
verbKey: 'addPlace',
subject: 'Kinkaku-ji',
rows: [{ op: 'add', labelKey: 'address', before: null, after: 'Kyoto' }],
dayId: null,
placeIds: [],
undoable: true,
};
it('labels rows from the closed key list only', () => {
expect(assistantChangePreviewSchema.safeParse(preview).success).toBe(true);
expect(
assistantChangePreviewSchema.safeParse({ ...preview, rows: [{ ...preview.rows[0], labelKey: 'evil' }] }).success,
).toBe(false);
expect(assistantChangePreviewWriteSchema.safeParse({ ...preview, verbKey: 'deleteTrip' }).success).toBe(false);
});
it('reads a verb a later build added as a plain update, and writes none it does not know', () => {
expect(assistantChangePreviewSchema.parse({ ...preview, verbKey: 'laterVerb' }).verbKey).toBe('genericUpdate');
expect(assistantChangePreviewWriteSchema.parse(preview).verbKey).toBe('addPlace');
expect(assistantChangePreviewWriteSchema.safeParse({ ...preview, card: { kind: 'nope' } }).success).toBe(false);
});
it('names the proposal a taken change came from by its call id, bounded like the take request', () => {
expect(assistantChangePreviewWriteSchema.parse({ ...preview, takenFrom: 'call_hike' }).takenFrom).toBe('call_hike');
expect(assistantChangePreviewSchema.parse(preview).takenFrom).toBeUndefined();
expect(assistantChangePreviewWriteSchema.safeParse({ ...preview, takenFrom: '' }).success).toBe(false);
expect(assistantChangePreviewWriteSchema.safeParse({ ...preview, takenFrom: 'c'.repeat(65) }).success).toBe(false);
});
it('holds at most twelve rows', () => {
const rows = ASSISTANT_CHANGE_LABEL_KEYS.slice(0, 13).map((labelKey) => ({
op: 'add',
labelKey,
before: null,
after: 'x',
}));
expect(assistantChangePreviewSchema.safeParse({ ...preview, rows }).success).toBe(false);
});
});
describe('assistantMessageSchema', () => {
it('reads a stored message with an expired approval', () => {
const parsed = assistantMessageSchema.safeParse({
id: '12',
role: 'assistant',
status: 'awaiting_approval',
createdAt: '2026-10-21T08:00:00.000Z',
parts: [
{ type: 'text', text: 'Adding it.' },
{
type: 'tool-call',
toolCallId: 'c1',
toolName: 'create_place',
args: { name: 'Kinkaku-ji' },
approval: { id: 'c1', resolution: 'expired' },
},
],
});
expect(parsed.success).toBe(true);
});
it('reads a user message that attached a file, by its name, type and size only', () => {
const message = { id: '13', role: 'user', status: 'complete', createdAt: '2026-10-21T08:00:00.000Z' };
const attachment = { type: 'attachment', name: 'ticket.pdf', mime: 'application/pdf', size: 2048 };
expect(assistantMessageSchema.safeParse({ ...message, parts: [attachment] }).success).toBe(true);
const negative = { ...attachment, size: -1 };
expect(assistantMessageSchema.safeParse({ ...message, parts: [negative] }).success).toBe(false);
});
it('reads the id a kept attachment goes by, and only a uuid as one', () => {
const message = { id: '14', role: 'user', status: 'complete', createdAt: '2026-10-21T08:00:00.000Z' };
const attachment = { type: 'attachment', name: 'ticket.pdf', mime: 'application/pdf', size: 2048 };
const kept = { ...attachment, attachmentId: '0b7c2f0e-6f6d-4a8e-9b1a-3d2c1e0f9a87' };
expect(assistantMessageSchema.parse({ ...message, parts: [kept] }).parts[0]).toEqual(kept);
const forged = { ...attachment, attachmentId: '../other-thread' };
expect(assistantMessageSchema.safeParse({ ...message, parts: [forged] }).success).toBe(false);
});
});
describe('uiStreamChunkSchema', () => {
it('reads an unknown error code as generic', () => {
expect(uiStreamChunkSchema.parse({ type: 'error', errorText: 'something_new' })).toEqual({
type: 'error',
errorText: 'generic',
});
expect(uiStreamChunkSchema.parse({ type: 'error', errorText: 'daily_limit' })).toEqual({
type: 'error',
errorText: 'daily_limit',
});
});
it('refuses a chunk type it does not know', () => {
expect(uiStreamChunkSchema.safeParse({ type: 'reasoning-delta', id: 'r', delta: 'x' }).success).toBe(false);
});
});
describe('ui-stream.v1 fixture', () => {
const events = dataEvents(fixture);
const chunks = events.slice(0, -1).map((event) => uiStreamChunkSchema.parse(JSON.parse(event)));
const ofType = <T extends UiStreamChunk['type']>(type: T) =>
chunks.filter((c): c is Extract<UiStreamChunk, { type: T }> => c.type === type);
it('is a stream of valid chunks closed by [DONE]', () => {
expect(events.at(-1)).toBe(UI_STREAM_DONE);
expect(chunks[0]?.type).toBe('start');
expect(chunks.at(-1)).toEqual({ type: 'finish', finishReason: 'tool-calls' });
});
it('names the new thread before anything else is said', () => {
expect(chunks[1]?.type).toBe('data-trek-thread');
});
it('asks for approval with the call id and previews that same call', () => {
const [request] = ofType('tool-approval-request');
const [change] = ofType('data-trek-change');
expect(request).toBeDefined();
expect(request?.approvalId).toBe(request?.toolCallId);
expect(change?.data.toolCallId).toBe(request?.toolCallId);
expect(ofType('tool-input-available').map((c) => c.toolCallId)).toContain(request?.toolCallId);
});
it('closes every text block it opens', () => {
const opened = ofType('text-start').map((c) => c.id);
expect(opened.length).toBeGreaterThan(0);
expect(ofType('text-end').map((c) => c.id)).toEqual(opened);
});
});
describe('mentions in a chat request', () => {
const base = { ...ctx, threadId: 3, text: 'Move @Louvre to @Friday' };
it('names up to ten days, places or bookings by id, never by label', () => {
const mentions = [
{ kind: 'place', id: 4 },
{ kind: 'day', id: 9 },
{ kind: 'reservation', id: 2 },
];
expect(assistantChatRequestSchema.safeParse({ ...base, mentions }).success).toBe(true);
const tooMany = Array.from({ length: 51 }, () => ({ kind: 'place', id: 4 }));
expect(assistantChatRequestSchema.safeParse({ ...base, mentions: tooMany }).success).toBe(false);
const labelled = [{ kind: 'place', id: 4, label: 'Louvre' }];
expect(assistantChatRequestSchema.safeParse({ ...base, mentions: labelled }).success).toBe(false);
expect(assistantChatRequestSchema.safeParse({ ...base, mentions: [{ kind: 'trip', id: 4 }] }).success).toBe(false);
});
});
describe('assistantAddFoundPlaceRequestSchema', () => {
const parse = (body: Record<string, unknown>) => assistantAddFoundPlaceRequestSchema.safeParse({ ...ctx, ...body });
it('names a found place by its ref and the day it goes on', () => {
expect(parse({ ref: 'toolu_01:2', dayId: 32 }).success).toBe(true);
});
it('refuses an empty or overlong ref, a bad day and anything about the place itself', () => {
expect(parse({ ref: '', dayId: 32 }).success).toBe(false);
expect(parse({ ref: 'x'.repeat(81), dayId: 32 }).success).toBe(false);
expect(parse({ ref: 'a:1', dayId: 0 }).success).toBe(false);
expect(parse({ ref: 'a:1', dayId: 3, name: 'Elsewhere' }).success).toBe(false);
expect(assistantAddFoundPlaceRequestSchema.safeParse({ ref: 'a:1', dayId: 3 }).success).toBe(false);
});
});
describe('assistantInsertFoundPlaceRequestSchema', () => {
const parse = (body: Record<string, unknown>) =>
assistantInsertFoundPlaceRequestSchema.safeParse({ ...ctx, ...body });
it('names a found place by its ref and the saved tour it goes into', () => {
expect(parse({ ref: 'toolu_01:2', tourId: 64 }).success).toBe(true);
});
it('refuses a bad tour, a day instead of a tour and anything about the stop itself', () => {
expect(parse({ ref: 'a:1', tourId: 0 }).success).toBe(false);
expect(parse({ ref: 'a:1', dayId: 3 }).success).toBe(false);
expect(parse({ ref: 'a:1', tourId: 64, after_key: 'abc123' }).success).toBe(false);
expect(assistantInsertFoundPlaceRequestSchema.safeParse({ ref: 'a:1', tourId: 64 }).success).toBe(false);
});
});
describe('route files attached in the chat', () => {
it('tells a GPX, KML or KMZ file by its name, whatever its case', () => {
expect(isAssistantTourFile('Herzogstand.GPX')).toBe(true);
expect(isAssistantTourFile('map.kml')).toBe(true);
expect(isAssistantTourFile('map.kmz')).toBe(true);
expect(isAssistantTourFile('ticket.pdf')).toBe(false);
expect(isAssistantTourFile('gpx')).toBe(false);
});
});
describe('the effect of a change', () => {
const preview = {
toolCallId: 'c1',
verbKey: 'addPlaceToDay',
subject: 'Kinkaku-ji',
rows: [],
dayId: 32,
placeIds: [],
undoable: true,
};
const ghost = { name: 'Kinkaku-ji', lat: 35.0394, lng: 135.7292, categoryId: null };
const add = { kind: 'add', dayId: 32, fromDayId: null, placeId: null, assignmentId: null, place: ghost };
const withEffect = (effect: unknown) => assistantChangePreviewSchema.safeParse({ ...preview, effect }).success;
it('is optional, so previews stored before it still read', () => {
expect(assistantChangePreviewSchema.safeParse(preview).success).toBe(true);
expect(withEffect(null)).toBe(true);
});
it('places a new place on its day, or moves an existing one between days', () => {
expect(withEffect(add)).toBe(true);
const existing = { placeId: 7, assignmentId: 12, place: null };
expect(withEffect({ kind: 'move', dayId: 32, fromDayId: 31, ...existing })).toBe(true);
expect(withEffect({ kind: 'remove', dayId: 31, fromDayId: null, ...existing })).toBe(true);
});
it('refuses a position off the globe, an overlong name and an unknown kind', () => {
expect(withEffect({ ...add, place: { ...ghost, lat: 91 } })).toBe(false);
expect(withEffect({ ...add, place: { ...ghost, lng: -181 } })).toBe(false);
expect(withEffect({ ...add, place: { ...ghost, name: 'x'.repeat(201) } })).toBe(false);
expect(withEffect({ ...add, kind: 'swap' })).toBe(false);
});
});
describe('assistantFoundPlaceSchema', () => {
const place = {
ref: 'toolu_01:0',
name: 'Trattoria da Enzo',
address: 'Via dei Vascellari 29, Roma',
lat: 41.8885,
lng: 12.4771,
kind: 'food',
rating: 4.6,
openNow: null,
googlePlaceId: 'ChIJ-abc_123',
osmId: null,
photoKey: 'ChIJ-abc_123',
inTripPlaceId: null,
};
const withPlace = (patch: Record<string, unknown>) => assistantFoundPlaceSchema.safeParse({ ...place, ...patch });
it('reads a place with a source id as its photo key, or coordinates', () => {
expect(withPlace({}).success).toBe(true);
expect(withPlace({ photoKey: 'coords:41.8885,12.4771' }).success).toBe(true);
expect(withPlace({ photoKey: 'coords:-33.9,-70.6' }).success).toBe(true);
expect(withPlace({ photoKey: null }).success).toBe(true);
});
it('never takes a URL or anything with a path as the photo key', () => {
const notKeys = [
'https://evil.example/p.jpg',
'//evil.example/p.jpg',
'/api/maps/place-photo/x/bytes',
'a/b',
'coords:1,2;x',
'',
];
for (const photoKey of notKeys) expect(withPlace({ photoKey }).success, photoKey).toBe(false);
});
it('refuses a Google id that is not one, a rating past five and an unknown kind', () => {
expect(withPlace({ googlePlaceId: 'a b' }).success).toBe(false);
expect(withPlace({ rating: 5.1 }).success).toBe(false);
expect(withPlace({ kind: 'casino' }).success).toBe(false);
});
it('holds at most twenty places to a step and counts the rest', () => {
const places = Array.from({ length: 21 }, (_, i) => ({ ...place, ref: `toolu_01:${i}` }));
const step = (body: Record<string, unknown>) =>
assistantPlacesSchema.safeParse({ toolCallId: 'toolu_01', ...body });
expect(step({ places: places.slice(0, 20), more: 1 }).success).toBe(true);
expect(step({ places, more: 0 }).success).toBe(false);
expect(step({ places: [], more: -1 }).success).toBe(false);
});
});
describe('assistantWeatherSchema', () => {
const day = {
dayId: 32,
date: '2026-06-12',
main: 'Clear',
tempMax: 24.5,
tempMin: 16,
rainPct: 10,
kind: 'forecast',
};
it('reads one to sixteen days, a climate day without a low or a rain chance', () => {
expect(assistantWeatherSchema.safeParse({ days: [day] }).success).toBe(true);
const climate = { ...day, dayId: null, tempMin: null, rainPct: null, kind: 'climate' };
expect(assistantWeatherSchema.safeParse({ days: [climate] }).success).toBe(true);
expect(assistantWeatherSchema.safeParse({ days: [] }).success).toBe(false);
expect(assistantWeatherSchema.safeParse({ days: Array.from({ length: 17 }, () => day) }).success).toBe(false);
});
it('refuses a date that is not a calendar date and a rain chance past 100', () => {
expect(assistantWeatherSchema.safeParse({ days: [{ ...day, date: '12.06.2026' }] }).success).toBe(false);
expect(assistantWeatherSchema.safeParse({ days: [{ ...day, rainPct: 101 }] }).success).toBe(false);
});
});
describe('the new message parts', () => {
const message = { id: '14', status: 'complete', createdAt: '2026-10-21T08:00:00.000Z' };
const rainyDay = { dayId: 32, date: '2026-06-12', main: 'Rain', tempMax: 18, tempMin: 12, rainPct: 80 };
it('keeps found places and the weather on an answer', () => {
const parts = [
{ type: 'data-trek-places', data: { toolCallId: 'toolu_01', places: [], more: 0 } },
{ type: 'data-trek-weather', data: { days: [{ ...rainyDay, kind: 'forecast' }] } },
];
expect(assistantMessageSchema.safeParse({ ...message, role: 'assistant', parts }).success).toBe(true);
});
it('keeps the checked mentions of a question with their labels', () => {
const item = { kind: 'place', id: 4, label: 'Louvre' };
const parts = [
{ type: 'text', text: 'Is @Louvre open on Monday?' },
{ type: 'data-trek-mentions', data: { items: [item] } },
];
expect(assistantMessageSchema.safeParse({ ...message, role: 'user', parts }).success).toBe(true);
const tooLong = [{ type: 'data-trek-mentions', data: { items: [{ ...item, label: 'x'.repeat(121) }] } }];
expect(assistantMessageSchema.safeParse({ ...message, role: 'user', parts: tooLong }).success).toBe(false);
});
it('never stores the live activity of a step', () => {
const activity = { type: 'data-trek-activity', data: { toolCallId: 'toolu_01', label: null, area: null } };
expect(assistantMessageSchema.safeParse({ ...message, role: 'assistant', parts: [activity] }).success).toBe(false);
});
it('answers a suggested found place with the message that holds it', () => {
const answer = { ...message, role: 'assistant', status: 'awaiting_approval', parts: [] };
expect(assistantAddFoundPlaceResponseSchema.safeParse({ message: answer }).success).toBe(true);
expect(assistantAddFoundPlaceResponseSchema.safeParse({}).success).toBe(false);
});
});
describe('the new stream chunks', () => {
const activity = (data: Record<string, unknown>) =>
uiStreamChunkSchema.safeParse({ type: 'data-trek-activity', data: { toolCallId: 'toolu_01', ...data } }).success;
it('streams the live activity of a step, marked transient, with a point or a box', () => {
const point = { type: 'point', lat: 41.89, lng: 12.47, radiusM: 1500 };
const bbox = { type: 'bbox', south: 41.8, west: 12.4, north: 41.95, east: 12.6 };
for (const area of [point, bbox, null]) expect(activity({ label: 'Trastevere', area })).toBe(true);
const chunk = { type: 'data-trek-activity', transient: true, data: { toolCallId: 't', label: null, area: null } };
expect(uiStreamChunkSchema.safeParse(chunk).success).toBe(true);
});
it('refuses an activity with a radius past 50 km or a label past 80 characters', () => {
const area = { type: 'point', lat: 41.89, lng: 12.47, radiusM: 50_001 };
expect(activity({ label: null, area })).toBe(false);
expect(activity({ label: 'x'.repeat(81), area: null })).toBe(false);
});
it('streams found places and the weather as they are stored', () => {
const places = { type: 'data-trek-places', data: { toolCallId: 'toolu_01', places: [], more: 3 } };
const day = { dayId: null, date: '2026-06-12', main: 'Clouds', tempMax: 21, tempMin: null, rainPct: null };
const weather = { type: 'data-trek-weather', data: { days: [{ ...day, kind: 'current' }] } };
expect(uiStreamChunkSchema.safeParse(places).success).toBe(true);
expect(uiStreamChunkSchema.safeParse(weather).success).toBe(true);
});
it('names the found-place refusal by its code', () => {
expect(uiStreamChunkSchema.parse({ type: 'error', errorText: 'decide_first' })).toEqual({
type: 'error',
errorText: 'decide_first',
});
});
});
+817
View File
@@ -0,0 +1,817 @@
import { bookElementIdSchema, bookSpreadIdSchema } from '../book/book-ops.schema';
import { idParamSchema, idSchema } from '../common/primitives.schema';
import { assistantAttachmentIdSchema } from './assistant-attachments.schema';
import { assistantJourneySurfaceSchema } from './assistant-scope.schema';
import { assistantPageRenderSchema, assistantPageViewSchema } from './assistant-vision.schema';
import {
assistantCardSchema,
assistantCardWriteSchema,
ATLAS_APPLIED_ENTITIES,
ATLAS_VERB_KEYS,
BOOK_APPLIED_ENTITIES,
BOOK_DESIGN_VERB_KEYS,
BOOK_VERB_KEYS,
BOOKING_APPLIED_ENTITIES,
BOOKING_VERB_KEYS,
BUDGET_APPLIED_ENTITIES,
BUDGET_VERB_KEYS,
COLLAB_APPLIED_ENTITIES,
COLLAB_VERB_KEYS,
COLLECTION_APPLIED_ENTITIES,
COLLECTION_VERB_KEYS,
JOURNEY_APPLIED_ENTITIES,
JOURNEY_VERB_KEYS,
PACKING_APPLIED_ENTITIES,
PACKING_VERB_KEYS,
ROADTRIP_APPLIED_ENTITIES,
ROADTRIP_VERB_KEYS,
storedTrekCardSchema,
TOUR_APPLIED_ENTITIES,
TOUR_VERB_KEYS,
trekCardSchema,
VACAY_APPLIED_ENTITIES,
VACAY_VERB_KEYS,
type AssistantCard,
} from './cards';
import { z } from 'zod';
/**
* Trip assistant contract for /api/trips/:tripId/assistant.
*
* The assistant works the trip through the same MCP tools any client uses.
* Reading tools run at once; every writing call is held as a change preview
* the user applies or discards, and only then runs, with the arguments the
* server stored, never ones the client sends back. A file attached in the
* chat (`attachments`) is read by the server itself: the step is the call
* `read_booking_file`, and each booking it finds is held as an
* `import_booking` change like any other. Neither is a tool the model knows.
*
* `chat`, `attachments` and `threads/:threadId/decisions` answer with a stream of UI message
* chunks (`uiStreamChunkSchema`, a subset of the UI Message Stream v1 plus the
* `data-trek-*` parts), one `data: <json>` event each, closed by
* `data: [DONE]`. `__fixtures__/ui-stream.v1.txt` is one such stream; the
* server's writer and the client's parser are both tested against it.
*/
/** Why a turn could not run or stopped, as the `error` chunk and the JSON errors name it. */
export const ASSISTANT_ERROR_CODES = [
'not_connected',
'busy',
'daily_limit',
'rate_limited',
'needs_reauth',
'usage_limit',
'not_eligible',
'invalid_key',
'provider_unavailable',
'max_steps',
// The model answered with nothing, not even after it was asked to go on.
'empty_answer',
'offline',
'no_bookings_found',
// An attached GPX, KML or KMZ file without a single track or route to take in as a tour.
'no_tracks_found',
'import_unavailable',
// A found place was suggested while the thread still holds changes nobody decided on.
'decide_first',
// TREK's own per-user limit on turns and changes, apart from the provider's `rate_limited`.
'too_many_requests',
'generic',
] as const;
export const assistantErrorCodeSchema = z.enum(ASSISTANT_ERROR_CODES);
export type AssistantErrorCode = z.infer<typeof assistantErrorCodeSchema>;
/**
* What a change does, one per writing tool. The client labels the card with
* `assistant.change.verb.<key>`. These are the core verbs; each part of TREK
* adds its own in its cards contract (`cards/<pkg>.contract.ts`).
*/
export const CORE_VERB_KEYS = [
'addPlace',
'addPlaceToDay',
'updatePlace',
'assignPlace',
'moveAssignment',
'removeFromDay',
'addDayNote',
'updateDayNote',
'addPackingItem',
'updatePackingItem',
'addTodo',
'addBudgetItem',
'updateBudgetItem',
'addReservation',
'importBooking',
'rememberNote',
// The text of a file attached in the chat, sent to the AI provider once the user agrees.
'readAttachment',
// A file attached in the chat, kept in the trip's Files, on its own or with a booking, an expense or a place.
'keepFile',
// A tour: a hike or a city walk created, a hike changed, tours taken in from a GPX file.
'addTour',
'updateTour',
'importTour',
// Any other tool: by what its annotations say it does.
'genericCreate',
'genericUpdate',
'genericRemove',
] as const;
export const ASSISTANT_CHANGE_VERB_KEYS = [
...CORE_VERB_KEYS,
...TOUR_VERB_KEYS,
...ROADTRIP_VERB_KEYS,
...BUDGET_VERB_KEYS,
...BOOKING_VERB_KEYS,
...COLLAB_VERB_KEYS,
...COLLECTION_VERB_KEYS,
...ATLAS_VERB_KEYS,
...VACAY_VERB_KEYS,
...JOURNEY_VERB_KEYS,
...PACKING_VERB_KEYS,
...BOOK_VERB_KEYS,
...BOOK_DESIGN_VERB_KEYS,
] as const;
export const assistantChangeVerbKeySchema = z.enum(ASSISTANT_CHANGE_VERB_KEYS);
export type AssistantChangeVerbKey = z.infer<typeof assistantChangeVerbKeySchema>;
/** The field a change row shows, labelled `assistant.change.label.<key>`. */
export const ASSISTANT_CHANGE_LABEL_KEYS = [
'name',
'description',
'address',
'coordinates',
'category',
'day',
'time',
'endTime',
'notes',
'website',
'phone',
'email',
'openingHours',
'price',
'currency',
'stopType',
'text',
'icon',
'color',
'position',
'quantity',
'weight',
'bag',
'packed',
'dueDate',
'priority',
'assignee',
'type',
'location',
'link',
'confirmation',
'checkIn',
'checkOut',
'stay',
'members',
'route',
// The hardest SAC grade a hike's way may take, T1 to T6.
'difficulty',
// The recorded track a tour was done on; the part of the packing list a tour points at.
'track',
'packing',
// The minutes of breaks a tour plans on top of its moving time.
'breaks',
// A new order of a day's places or of the days, as the names in that order.
'order',
// An argument of a tool without a card of its own; the row names it in `field`.
'field',
// Where the text of an attached file goes once the user agrees: the model and its host.
'sentTo',
// The booking, expense or place a kept file is attached to.
'attachedTo',
] as const;
export const assistantChangeLabelKeySchema = z.enum(ASSISTANT_CHANGE_LABEL_KEYS);
export type AssistantChangeLabelKey = z.infer<typeof assistantChangeLabelKeySchema>;
const latSchema = z.number().min(-90).max(90);
const lngSchema = z.number().min(-180).max(180);
// ── Requests ────────────────────────────────────────────────────────────────
/**
* A day, place or booking the user named with `@` in the message. The server
* checks each against the trip and takes the label from its own data, never
* from the request; one that is not in the trip is dropped without a word.
*/
export const ASSISTANT_MENTION_KINDS = ['day', 'place', 'reservation'] as const;
export const assistantMentionSchema = z
.object({
kind: z.enum(ASSISTANT_MENTION_KINDS),
id: idSchema,
})
.strict();
export type AssistantMention = z.infer<typeof assistantMentionSchema>;
/** The part of the map the planner shows, so "here" and "nearby" mean what is on screen. */
export const assistantMapViewSchema = z
.object({ south: latSchema, west: lngSchema, north: latSchema, east: lngSchema })
.strict();
export type AssistantMapView = z.infer<typeof assistantMapViewSchema>;
/**
* What the user is looking at when they ask: the selected day, or the places
* they asked about, and the part of the map on screen.
*/
export const assistantFocusSchema = z
.object({
dayId: idSchema.optional(),
placeIds: z.array(idSchema).max(20).optional(),
view: assistantMapViewSchema.optional(),
/** In the Studio: the page (spread) on screen, and the elements selected on it. */
spreadId: bookSpreadIdSchema.optional(),
elementIds: z.array(bookElementIdSchema).max(30).optional(),
})
.strict();
export type AssistantFocus = z.infer<typeof assistantFocusSchema>;
/** The language to answer in and the zone "today" is read in, sent with every turn. */
export const assistantClientCtxSchema = z.object({
locale: z.string().min(2).max(10),
timeZone: z.string().min(1).max(64),
});
export type AssistantClientCtx = z.infer<typeof assistantClientCtxSchema>;
/** POST /chat: a new message, in an existing thread or (threadId null) a new one. */
export const assistantChatRequestSchema = assistantClientCtxSchema
.extend({
threadId: idSchema.nullable(),
text: z.string().trim().min(1).max(32_000),
focus: assistantFocusSchema.optional(),
mentions: z.array(assistantMentionSchema).max(50).optional(),
/** The client draws a Studio page when the turn asks for one (the Studio's chat, assistant-vision.schema.ts). */
renders: z.boolean().optional(),
/** A journey's chat only: the page the user asks from, the Studio's when left out. A trip's chat ignores it. */
surface: assistantJourneySurfaceSchema.optional(),
})
.strict();
export type AssistantChatRequest = z.infer<typeof assistantChatRequestSchema>;
/**
* POST /attachments, multipart: the file in the field `file`, these as text
* fields beside it. A new thread when threadId is left out. Multipart sends
* every field as a string, so the id is read from its text.
*/
export const assistantAttachmentRequestSchema = assistantClientCtxSchema
.extend({
threadId: idParamSchema.optional(),
})
.strict();
export type AssistantAttachmentRequest = z.infer<typeof assistantAttachmentRequestSchema>;
/** One decision on a held change. */
export const assistantDecisionSchema = z
.object({
toolCallId: z.string().min(1).max(64),
approved: z.boolean(),
})
.strict();
export type AssistantDecision = z.infer<typeof assistantDecisionSchema>;
/** POST /threads/:threadId/decisions: every change the step holds, applied or discarded. */
export const assistantDecisionsRequestSchema = assistantClientCtxSchema
.extend({
decisions: z.array(assistantDecisionSchema).min(1).max(50),
/** As on a chat turn: the client draws a Studio page when the turn asks for one. */
renders: z.boolean().optional(),
/** As on a chat turn: the page of a journey the decision is made on, which picks the tools the turn goes on with. */
surface: assistantJourneySurfaceSchema.optional(),
})
.strict();
export type AssistantDecisionsRequest = z.infer<typeof assistantDecisionsRequestSchema>;
/** POST /stop. No fields: the body is JSON only so the request cannot be sent cross-site as a form. */
export const assistantStopRequestSchema = z.object({}).strict();
export type AssistantStopRequest = z.infer<typeof assistantStopRequestSchema>;
/** POST /tool-calls/:toolCallId/undo. No fields, for the same reason as stop. */
export const assistantUndoRequestSchema = z.object({}).strict();
export type AssistantUndoRequest = z.infer<typeof assistantUndoRequestSchema>;
/**
* POST /threads/:threadId/found-places: suggest a place from a search result
* for a day. `ref` names the place in the thread's stored places part; the
* server holds the change like any other and runs no model turn for it.
*/
export const assistantAddFoundPlaceRequestSchema = assistantClientCtxSchema
.extend({
ref: z.string().min(1).max(80),
dayId: idSchema,
})
.strict();
export type AssistantAddFoundPlaceRequest = z.infer<typeof assistantAddFoundPlaceRequestSchema>;
/**
* POST /threads/:threadId/found-places/tour: "+ Tour" on a place a search
* found, while a saved tour is open in the planner. Held like "+ Day 3": the
* place comes from the stored search results, the tour must be one of this
* trip's, and the server picks where along it the stop goes.
*/
export const assistantInsertFoundPlaceRequestSchema = assistantClientCtxSchema
.extend({
ref: z.string().min(1).max(80),
tourId: idSchema,
})
.strict();
export type AssistantInsertFoundPlaceRequest = z.infer<typeof assistantInsertFoundPlaceRequestSchema>;
/** The route files the chat takes in as tours (P7), beside the booking files. */
export const ASSISTANT_TOUR_FILE_EXTENSIONS = ['.gpx', '.kml', '.kmz'] as const;
/** Whether a file the user attached is a route file, by its name. */
export function isAssistantTourFile(fileName: string): boolean {
const dot = fileName.lastIndexOf('.');
const ext = dot < 0 ? '' : fileName.slice(dot).toLowerCase();
return (ASSISTANT_TOUR_FILE_EXTENSIONS as readonly string[]).includes(ext);
}
/**
* POST /threads/:threadId/proposals: take a proposal an answer showed as a
* card ("Plan this"). `toolCallId` names the read whose card it was; the
* server holds the matching change like a found place, from what it stored,
* and answers like the found places route.
*/
export const assistantTakeProposalRequestSchema = assistantClientCtxSchema
.extend({
toolCallId: z.string().min(1).max(64),
})
.strict();
export type AssistantTakeProposalRequest = z.infer<typeof assistantTakeProposalRequestSchema>;
// ── Change previews ─────────────────────────────────────────────────────────
/**
* What a change does to the day plan, so the map can show it before it is
* applied: the day it lands on (for a removal, the day it leaves), the day a
* move comes from, and for a place that does not exist yet its name and
* position. Null for a change that does not touch the plan.
*/
export const assistantChangeEffectSchema = z.object({
kind: z.enum(['add', 'remove', 'move']),
dayId: idSchema,
fromDayId: idSchema.nullable(),
placeId: idSchema.nullable(),
assignmentId: idSchema.nullable(),
place: z
.object({
name: z.string().max(200),
lat: latSchema,
lng: lngSchema,
categoryId: idSchema.nullable(),
})
.nullable(),
});
export type AssistantChangeEffect = z.infer<typeof assistantChangeEffectSchema>;
/** One line of a change card, in plain words: names, dates and times, never ids. */
export const assistantChangeRowSchema = z.object({
op: z.enum(['add', 'change', 'move']),
labelKey: assistantChangeLabelKeySchema,
before: z.string().nullable(),
after: z.string(),
// The argument a `field` row shows, as the tool names it.
field: z.string().max(60).optional(),
});
export type AssistantChangeRow = z.infer<typeof assistantChangeRowSchema>;
/** A held writing call as the server writes it: every verb and card one this build knows. */
export const assistantChangePreviewWriteSchema = z.object({
toolCallId: z.string(),
verbKey: assistantChangeVerbKeySchema,
// What the change is about: the place, note or item name.
subject: z.string(),
rows: z.array(assistantChangeRowSchema).max(12),
// Where "Show on map" goes after the change was applied.
dayId: idSchema.nullable(),
placeIds: z.array(idSchema),
// Whether applying it can be undone for a while (a create with a matching delete).
undoable: z.boolean(),
// Left out by servers and stored previews from before the map showed changes.
effect: assistantChangeEffectSchema.nullable().optional(),
// The tool behind a card without one of its own, and the part of TREK it works in.
tool: z.string().max(80).optional(),
domain: z.string().max(40).optional(),
// What the change will do, drawn as a card; absent on older rows and on cards without one.
card: trekCardSchema.nullable().optional(),
// The proposal a change held by "Plan this" was taken from (its call id); absent on every other change.
takenFrom: assistantTakeProposalRequestSchema.shape.toolCallId.optional(),
});
/**
* A held writing call as the user sees it before deciding, and as it is read
* back: a verb a later build added reads as a plain update and a card this
* build cannot draw as none, so an older client or a rolled back server still
* shows the change instead of dropping it.
*/
export const assistantChangePreviewSchema = assistantChangePreviewWriteSchema.extend({
verbKey: assistantChangeVerbKeySchema.catch('genericUpdate'),
card: storedTrekCardSchema.optional(),
});
export type AssistantChangePreview = z.infer<typeof assistantChangePreviewSchema>;
/** What an applied change can touch in the core; each part of TREK adds its own in its cards contract. */
export const CORE_APPLIED_ENTITIES = [
'place',
'assignment',
'day_note',
'packing',
'todo',
'budget',
'reservation',
'memory',
'tour',
// A file kept in the trip's Files.
'file',
'other',
] as const;
const assistantAppliedEntitySchema = z.enum([
...CORE_APPLIED_ENTITIES,
...TOUR_APPLIED_ENTITIES,
...ROADTRIP_APPLIED_ENTITIES,
...BUDGET_APPLIED_ENTITIES,
...BOOKING_APPLIED_ENTITIES,
...COLLAB_APPLIED_ENTITIES,
...COLLECTION_APPLIED_ENTITIES,
...ATLAS_APPLIED_ENTITIES,
...VACAY_APPLIED_ENTITIES,
...JOURNEY_APPLIED_ENTITIES,
...PACKING_APPLIED_ENTITIES,
...BOOK_APPLIED_ENTITIES,
]);
/** An applied change as the server writes it: what it touched, and until when it can be undone. */
const assistantAppliedWriteSchema = z.object({
toolCallId: z.string(),
entity: assistantAppliedEntitySchema,
ids: z.array(idSchema),
dayId: idSchema.nullable(),
undoUntil: z.string().nullable(),
});
/** An applied change as it is read back: an entity a later build added reads as `other`, with nothing to open. */
export const assistantAppliedSchema = assistantAppliedWriteSchema.extend({
entity: assistantAppliedEntitySchema.catch('other'),
});
export type AssistantApplied = z.infer<typeof assistantAppliedSchema>;
// ── Cards in an answer ──────────────────────────────────────────────────────
/** The kind a found place is drawn as, read from whatever its source calls it. */
export const ASSISTANT_FOUND_PLACE_KINDS = [
'lodging',
'food',
'drinks',
'sight',
'shopping',
'transport',
'beach',
'nature',
'activity',
] as const;
/**
* One place a search step found, normalized by the server from the tool's
* result. It never carries a URL: the client asks TREK's photo proxy with
* `photoKey` (a source id or `coords:lat,lng`) and shows only a same-origin
* answer. `openNow` is set only from the source's own flag and only while
* the trip is running; `inTripPlaceId` names the trip's place when it is the
* same one.
*/
export const assistantFoundPlaceSchema = z.object({
// `${toolCallId}:${index}`, the handle a suggestion for a day names it by.
ref: z.string().max(80),
name: z.string().max(120),
address: z.string().max(200).nullable(),
lat: latSchema,
lng: lngSchema,
kind: z.enum(ASSISTANT_FOUND_PLACE_KINDS).nullable(),
rating: z.number().min(0).max(5).nullable(),
openNow: z.boolean().nullable(),
googlePlaceId: z
.string()
.regex(/^[\w-]{1,200}$/)
.nullable(),
osmId: z.string().max(40).nullable(),
photoKey: z
.string()
.regex(/^([\w-]{1,200}|coords:-?\d{1,3}(\.\d{1,12})?,-?\d{1,3}(\.\d{1,12})?)$/)
.nullable(),
inTripPlaceId: idSchema.nullable(),
});
export type AssistantFoundPlace = z.infer<typeof assistantFoundPlaceSchema>;
/** The places one search step found: at most eight, `more` counts the rest. */
export const assistantPlacesSchema = z.object({
toolCallId: z.string().max(64),
places: z.array(assistantFoundPlaceSchema).max(20),
more: z.number().int().nonnegative(),
});
export type AssistantPlaces = z.infer<typeof assistantPlacesSchema>;
/**
* The weather the steps of an answer looked up, one entry per date.
* Temperatures are °C; the client converts them to the user's unit. `main`
* is the condition the weather icon is chosen by.
*/
export const assistantWeatherDaySchema = z.object({
dayId: idSchema.nullable(),
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
main: z.string().max(20),
tempMax: z.number(),
tempMin: z.number().nullable(),
rainPct: z.number().int().min(0).max(100).nullable(),
kind: z.enum(['forecast', 'climate', 'current']),
});
export type AssistantWeatherDay = z.infer<typeof assistantWeatherDaySchema>;
export const assistantWeatherSchema = z.object({
days: z.array(assistantWeatherDaySchema).min(1).max(16),
});
export type AssistantWeather = z.infer<typeof assistantWeatherSchema>;
/**
* The tool the model ends an answer with to offer what the user may ask
* next. The server answers it itself and never shows it as a step.
*/
export const ASSISTANT_FOLLOW_UPS_TOOL = 'suggest_follow_ups';
/** The longest follow-up question the chat shows on one chip. */
export const MAX_FOLLOW_UP_CHARS = 80;
/** How many follow-up questions an answer offers at most. */
export const MAX_FOLLOW_UPS = 3;
/** The questions the model offers to ask next, fitting the conversation, in the user's language. */
export const assistantFollowUpsSchema = z.object({
questions: z.array(z.string().min(1).max(MAX_FOLLOW_UP_CHARS)).min(1).max(MAX_FOLLOW_UPS),
});
export type AssistantFollowUps = z.infer<typeof assistantFollowUpsSchema>;
/**
* The step a provider's own web search shows as in the chat: a tool call the
* server records for the step list, never sent back to the model as one.
*/
export const ASSISTANT_WEB_SEARCH_STEP = 'web_search';
/** How many pages one answer names as its sources at most. */
export const MAX_ASSISTANT_SOURCES = 12;
/**
* The pages an answer drew on from the provider's web search, in the order
* they were cited, each once: a link to open and its title.
*/
export const assistantSourcesSchema = z.object({
sources: z
.array(
z.object({
url: z
.string()
.max(2000)
.regex(/^https?:\/\//),
title: z.string().max(200),
}),
)
.min(1)
.max(MAX_ASSISTANT_SOURCES),
});
export type AssistantSources = z.infer<typeof assistantSourcesSchema>;
/** Where a running step looks: a point with a radius, or a box. */
export const assistantActivityAreaSchema = z.discriminatedUnion('type', [
z.object({
type: z.literal('point'),
lat: latSchema,
lng: lngSchema,
radiusM: z.number().int().min(50).max(50_000),
}),
z.object({
type: z.literal('bbox'),
south: latSchema,
west: lngSchema,
north: latSchema,
east: lngSchema,
}),
]);
export type AssistantActivityArea = z.infer<typeof assistantActivityAreaSchema>;
/**
* What a running step is doing, for the live line and the map: the place or
* query it names (shortened), and the area it searches when that is small
* enough to show. Only streamed, never stored.
*/
export const assistantActivitySchema = z.object({
toolCallId: z.string().max(64),
label: z.string().max(80).nullable(),
area: assistantActivityAreaSchema.nullable(),
});
export type AssistantActivity = z.infer<typeof assistantActivitySchema>;
/** The mentions of a user message as the server checked them, with the labels it took from the trip. */
export const assistantMentionsSchema = z.object({
items: z
.array(
z.object({
kind: z.enum(ASSISTANT_MENTION_KINDS),
id: idSchema,
label: z.string().max(120),
}),
)
.max(50),
});
export type AssistantMentions = z.infer<typeof assistantMentionsSchema>;
// ── Threads and messages ────────────────────────────────────────────────────
export const assistantThreadSummarySchema = z.object({
id: idSchema,
title: z.string(),
lastMessageAt: z.string(),
});
export type AssistantThreadSummary = z.infer<typeof assistantThreadSummarySchema>;
/** GET /threads: the user's latest threads in this trip. */
export const assistantThreadListResponseSchema = z.object({ threads: z.array(assistantThreadSummarySchema) });
export type AssistantThreadListResponse = z.infer<typeof assistantThreadListResponseSchema>;
/**
* A server-side approval gate on a tool call. `resolution` closes a request
* nobody decided: it expired after 24 hours, or the turn was cancelled.
*/
export const assistantToolApprovalSchema = z.object({
id: z.string(),
approved: z.boolean().optional(),
resolution: z.enum(['cancelled', 'expired']).optional(),
});
export type AssistantToolApproval = z.infer<typeof assistantToolApprovalSchema>;
/**
* The parts of a message, with the change, receipt and card parts read or
* written as given. Generic over the three schemas so the emitted declaration
* keeps each one's own Zod type instead of a precomputed object type, which a
* consumer without strictNullChecks would read differently from its own infer.
*/
function messagePartSchema<
Change extends z.ZodType<AssistantChangePreview>,
Applied extends z.ZodType<AssistantApplied>,
Card extends z.ZodType<AssistantCard>,
>(change: Change, applied: Applied, card: Card) {
return z.discriminatedUnion('type', [
z.object({ type: z.literal('text'), text: z.string() }),
// A file the user handed the assistant. Only its description is kept here, never its content; the
// server keeps the file under `attachmentId` (left out on messages from before it kept files).
z.object({
type: z.literal('attachment'),
name: z.string(),
mime: z.string(),
size: z.number().int().nonnegative(),
attachmentId: assistantAttachmentIdSchema.optional(),
}),
z.object({
type: z.literal('tool-call'),
toolCallId: z.string(),
toolName: z.string(),
args: z.record(z.string(), z.unknown()),
result: z.unknown().optional(),
isError: z.boolean().optional(),
approval: assistantToolApprovalSchema.optional(),
}),
z.object({ type: z.literal('data-trek-change'), data: change }),
z.object({ type: z.literal('data-trek-applied'), data: applied }),
z.object({ type: z.literal('data-trek-places'), data: assistantPlacesSchema }),
z.object({ type: z.literal('data-trek-weather'), data: assistantWeatherSchema }),
// What the model offers to ask next, at the end of an answer.
z.object({ type: z.literal('data-trek-follow-ups'), data: assistantFollowUpsSchema }),
// The pages the answer cites from the provider's web search.
z.object({ type: z.literal('data-trek-sources'), data: assistantSourcesSchema }),
// The card of one tool call: a read's beside the answer, an applied write's on the message that proposed it.
z.object({ type: z.literal('data-trek-card'), data: card }),
// Only on a user message.
z.object({ type: z.literal('data-trek-mentions'), data: assistantMentionsSchema }),
// A Studio page the turn looked at: what it was and its description, never the image.
z.object({ type: z.literal('data-trek-page-view'), data: assistantPageViewSchema }),
]);
}
/** One stored part of a message, in the order the model produced it, as a reader takes it. */
export const assistantMessagePartSchema = messagePartSchema(
assistantChangePreviewSchema,
assistantAppliedSchema,
assistantCardSchema,
);
export type AssistantMessagePart = z.infer<typeof assistantMessagePartSchema>;
/** The parts as the server writes them: a verb, entity or card this build cannot name is a bug in the writer. */
export const assistantMessagePartWriteSchema = messagePartSchema(
assistantChangePreviewWriteSchema,
assistantAppliedWriteSchema,
assistantCardWriteSchema,
);
/**
* A message's parts as they are read back: a `data-trek-*` part this build
* does not know, or one that no longer reads, is dropped, so a part a later
* build added never blanks the message around it. Any other broken part
* still fails the whole list. A known part reads through its tolerant fields
* (a later verb, entity or card kind); parts are written strictly, with
* `assistantMessagePartWriteSchema`.
*/
export const assistantStoredPartsSchema = z
.array(
z.union([
assistantMessagePartSchema,
z.object({ type: z.string().startsWith('data-trek-') }).transform(() => null),
]),
)
.transform((parts) => parts.filter((part): part is AssistantMessagePart => part !== null));
export const assistantMessageSchema = z.object({
id: z.string(),
role: z.enum(['user', 'assistant']),
parts: z.array(assistantMessagePartSchema),
status: z.enum(['complete', 'awaiting_approval', 'aborted', 'error']),
createdAt: z.string(),
});
export type AssistantMessage = z.infer<typeof assistantMessageSchema>;
/** GET /threads/:threadId: the thread with its latest 50 messages, oldest first. */
export const assistantThreadResponseSchema = z.object({
thread: assistantThreadSummarySchema,
messages: z.array(assistantMessageSchema),
});
export type AssistantThreadResponse = z.infer<typeof assistantThreadResponseSchema>;
/** POST /threads/:threadId/found-places: the new assistant message holding the suggested change. */
export const assistantAddFoundPlaceResponseSchema = z.object({ message: assistantMessageSchema });
export type AssistantAddFoundPlaceResponse = z.infer<typeof assistantAddFoundPlaceResponseSchema>;
/** POST /tool-calls/:toolCallId/undo */
export const assistantUndoResponseSchema = z.object({ undone: z.literal(true) });
export type AssistantUndoResponse = z.infer<typeof assistantUndoResponseSchema>;
// ── Stream ──────────────────────────────────────────────────────────────────
/** The marker the last `data:` event of a stream carries instead of a chunk. */
export const UI_STREAM_DONE = '[DONE]';
/**
* The chunks of an assistant stream. A client ignores a chunk whose type it
* does not know, so new types can be added without breaking older clients.
* An error names an `AssistantErrorCode`; one this client does not know reads
* as `generic`.
*/
export const uiStreamChunkSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('start'), messageId: z.string() }),
z.object({ type: z.literal('start-step') }),
z.object({ type: z.literal('text-start'), id: z.string() }),
z.object({ type: z.literal('text-delta'), id: z.string(), delta: z.string() }),
z.object({ type: z.literal('text-end'), id: z.string() }),
z.object({ type: z.literal('tool-input-start'), toolCallId: z.string(), toolName: z.string() }),
z.object({
type: z.literal('tool-input-available'),
toolCallId: z.string(),
toolName: z.string(),
input: z.record(z.string(), z.unknown()),
}),
// approvalId is the toolCallId: one id addresses the call and its decision.
z.object({ type: z.literal('tool-approval-request'), approvalId: z.string(), toolCallId: z.string() }),
z.object({ type: z.literal('tool-output-available'), toolCallId: z.string(), output: z.unknown() }),
z.object({ type: z.literal('tool-output-error'), toolCallId: z.string(), errorText: z.string() }),
z.object({ type: z.literal('tool-output-denied'), toolCallId: z.string() }),
z.object({ type: z.literal('data-trek-thread'), data: z.object({ threadId: idSchema, title: z.string() }) }),
z.object({ type: z.literal('data-trek-change'), data: assistantChangePreviewSchema }),
z.object({ type: z.literal('data-trek-applied'), data: assistantAppliedSchema }),
z.object({ type: z.literal('data-trek-places'), data: assistantPlacesSchema }),
z.object({ type: z.literal('data-trek-weather'), data: assistantWeatherSchema }),
z.object({ type: z.literal('data-trek-follow-ups'), data: assistantFollowUpsSchema }),
z.object({ type: z.literal('data-trek-sources'), data: assistantSourcesSchema }),
z.object({ type: z.literal('data-trek-card'), data: assistantCardSchema }),
// Live progress of a running step; the message never keeps it.
z.object({
type: z.literal('data-trek-activity'),
data: assistantActivitySchema,
transient: z.literal(true).optional(),
}),
// A Studio page the turn asks the Studio tab to draw and upload; the message never keeps it.
z.object({
type: z.literal('data-trek-render-request'),
data: assistantPageRenderSchema,
transient: z.literal(true).optional(),
}),
z.object({ type: z.literal('data-trek-page-view'), data: assistantPageViewSchema }),
z.object({
type: z.literal('data-trek-quota'),
data: z.object({ used: z.number().int().nonnegative(), limit: z.number().int().nonnegative() }),
}),
z.object({ type: z.literal('finish-step') }),
z.object({ type: z.literal('finish'), finishReason: z.enum(['stop', 'tool-calls', 'error']).optional() }),
z.object({ type: z.literal('error'), errorText: assistantErrorCodeSchema.catch('generic') }),
z.object({ type: z.literal('abort') }),
]);
export type UiStreamChunk = z.infer<typeof uiStreamChunkSchema>;
@@ -0,0 +1,49 @@
import { idSchema } from '../../common/primitives.schema';
import { atlasCountryCodeSchema, atlasRegionCodeSchema, atlasTallySchema } from './atlas-country.card';
import { cardCountSchema, cardDateSchema, cardText } from './card-parts';
import { z } from 'zod';
/** When a wish is planned for: a year, a month or a day ("2027", "2027-05", "2027-05-14"). */
export const atlasTargetDateSchema = z.string().regex(/^\d{4}(-\d{2}(-\d{2})?)?$/);
/** One wish of the bucket list. Never its coordinates: the card names it, the Atlas places it. */
export const atlasBucketEntrySchema = z.object({
/** Null on a wish that is still to be added. */
id: idSchema.nullable(),
name: cardText(120),
/** Null without a country, and for a legacy alpha-3 code (the card shows a star then). */
countryCode: atlasCountryCodeSchema.nullable(),
regionCode: atlasRegionCodeSchema.nullable(),
targetDate: atlasTargetDateSchema.nullable(),
notes: cardText(200).nullable(),
/** The day the wish came true. */
reachedOn: cardDateSchema.nullable(),
reachedFrom: z.enum(['manual', 'dawarich']).nullable(),
});
/** What an add, a change or a removal does to the bucket list. */
export const atlasBucketChangeSchema = z.object({
op: z.enum(['add', 'update', 'remove']),
/** The wish as it is: set on a change and a removal. */
before: atlasBucketEntrySchema.nullable(),
/** The same wish is on the list already, so the add will be refused. */
duplicate: z.boolean(),
/** How many wishes the list holds. */
wishes: atlasTallySchema.nullable(),
});
/**
* Wishes of the bucket list: the open ones first, soonest first, then the ones
* that came true. An answer shows the list; a change card shows the one wish
* it adds, changes or removes (`items[0]`).
*/
export const atlasBucketCardSchema = z.object({
kind: z.literal('atlasBucket'),
items: z.array(atlasBucketEntrySchema).min(1).max(12),
more: cardCountSchema,
change: atlasBucketChangeSchema.nullable(),
});
export type AtlasBucketCard = z.infer<typeof atlasBucketCardSchema>;
export type AtlasBucketEntry = z.infer<typeof atlasBucketEntrySchema>;
export type AtlasBucketChange = z.infer<typeof atlasBucketChangeSchema>;
@@ -0,0 +1,107 @@
import { atlasBucketCardSchema, type AtlasBucketCard, type AtlasBucketEntry } from './atlas-bucket.card';
import { atlasCountryCardSchema, type AtlasCountryCard } from './atlas-country.card';
import { atlasPassportCardSchema, type AtlasPassportCard } from './atlas-passport.card';
import { ATLAS_APPLIED_ENTITIES, ATLAS_CARD_SCHEMAS } from './atlas.contract';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { describe, expect, it } from 'vitest';
const passport: AtlasPassportCard = {
kind: 'atlasPassport',
countries: { visited: 23, planned: 4, idea: 1 },
totals: { trips: 48, days: 410, places: 990, cities: 312, flownKm: 182_300 },
flags: [
{ code: 'JP', status: 'visited' },
{ code: 'PT', status: 'planned' },
],
moreFlags: 21,
continents: [{ name: 'Europe', visited: 14, planned: 2 }],
nextTrip: { title: 'Lisbon', startDate: '2026-11-03', daysUntil: 12 },
streakYears: 3,
};
const kyoto = { code: 'JP-26', name: 'Kyoto', before: null, after: 'visited' as const };
const markJapan: NonNullable<AtlasCountryCard['change']> = {
op: 'mark',
region: kyoto,
after: 'visited',
countries: { before: 23, after: 24 },
regions: { before: 0, after: 1 },
};
const kyotoTrip = { id: 7, title: 'Kyoto in spring', startDate: '2024-04-03', endDate: '2024-04-14' };
const country: AtlasCountryCard = {
kind: 'atlasCountry',
code: 'JP',
status: 'planned',
markedBy: null,
placeCount: 14,
tripCount: 2,
trips: [kyotoTrip],
moreTrips: 1,
places: ['Fushimi Inari'],
morePlaces: 13,
change: markJapan,
};
const lights: AtlasBucketEntry = {
id: null,
name: 'Northern lights',
countryCode: 'IS',
regionCode: null,
targetDate: '2027-02',
notes: 'Glacier hike and hot springs',
reachedOn: null,
reachedFrom: null,
};
const bucket: AtlasBucketCard = {
kind: 'atlasBucket',
items: [lights],
more: 0,
change: { op: 'add', before: null, duplicate: false, wishes: { before: 7, after: 8 } },
};
describe('the atlas cards', () => {
it('CARDS-ATLAS-001: the passport, a country change and a bucket wish parse as themselves and in the union', () => {
expect(atlasPassportCardSchema.parse(passport)).toEqual(passport);
expect(atlasCountryCardSchema.parse(country)).toEqual(country);
expect(atlasBucketCardSchema.parse(bucket)).toEqual(bucket);
for (const card of [passport, country, bucket]) {
expect(trekCardSchema.parse(card)).toEqual(card);
expect(JSON.stringify(card)).not.toMatch(/https?:/);
}
expect(ATLAS_CARD_SCHEMAS).toHaveLength(3);
expect(ATLAS_APPLIED_ENTITIES).toEqual(['atlas']);
});
it('CARDS-ATLAS-002: a lower case or alpha-3 country code and a region outside the ISO form are refused', () => {
expect(atlasCountryCardSchema.safeParse({ ...country, code: 'jp' }).success).toBe(false);
expect(atlasCountryCardSchema.safeParse({ ...country, code: 'JPN' }).success).toBe(false);
const region = { ...kyoto, code: 'Kyoto' };
expect(atlasCountryCardSchema.safeParse({ ...country, change: { ...markJapan, region } }).success).toBe(false);
const wish = { ...lights, countryCode: 'isl' };
expect(atlasBucketCardSchema.safeParse({ ...bucket, items: [wish] }).success).toBe(false);
});
it('CARDS-ATLAS-003: lists past their bounds and an empty bucket card do not parse, and read as null', () => {
const flags = Array.from({ length: 41 }, () => ({ code: 'FR', status: 'visited' as const }));
expect(atlasPassportCardSchema.safeParse({ ...passport, flags }).success).toBe(false);
const trips = Array.from({ length: 5 }, () => kyotoTrip);
expect(atlasCountryCardSchema.safeParse({ ...country, trips }).success).toBe(false);
expect(atlasBucketCardSchema.safeParse({ ...bucket, items: [] }).success).toBe(false);
expect(storedTrekCardSchema.parse({ ...bucket, items: [] })).toBeNull();
expect(storedTrekCardSchema.parse({ ...passport, countries: { visited: -1, planned: 0, idea: 0 } })).toBeNull();
});
it('CARDS-ATLAS-004: a target date is a year, a month or a day, and a counter after a change may be unknown', () => {
for (const targetDate of ['2027', '2027-05', '2027-05-14']) {
const wish = { ...lights, targetDate };
expect(atlasBucketCardSchema.safeParse({ ...bucket, items: [wish] }).success).toBe(true);
}
const wish = { ...lights, targetDate: 'May 2027' };
expect(atlasBucketCardSchema.safeParse({ ...bucket, items: [wish] }).success).toBe(false);
const unknown = { ...markJapan, after: 'unknown' as const, countries: { before: 23, after: null } };
expect(atlasCountryCardSchema.parse({ ...country, change: unknown }).change?.countries?.after).toBeNull();
});
});
@@ -0,0 +1,70 @@
import { visitStatusSchema } from '../../atlas/atlas.schema';
import { idSchema } from '../../common/primitives.schema';
import { cardCountSchema, cardDateSchema, cardText } from './card-parts';
import { z } from 'zod';
/** ISO 3166-1 alpha-2 in upper case: the only code a flag and a country name are drawn from. */
export const atlasCountryCodeSchema = z.string().regex(/^[A-Z]{2}$/);
/** ISO 3166-2 as the atlas stores a region ("DE-BY", "US-CA"). */
export const atlasRegionCodeSchema = z.string().regex(/^[A-Z]{2}-[A-Z0-9]{1,8}$/);
/** A counter a change moves. `after` is null when the user's trips decide it, known once the change is applied. */
export const atlasTallySchema = z.object({ before: cardCountSchema, after: cardCountSchema.nullable() });
/** Where a country or a region stands after a change: `none` is off the map, `unknown` is up to the trips. */
export const atlasStatusAfterSchema = z.enum(['visited', 'planned', 'idea', 'none', 'unknown']);
/** A trip that went to the country, as a line of the card. */
const atlasTripLineSchema = z.object({
id: idSchema,
title: cardText(80),
startDate: cardDateSchema.nullable(),
endDate: cardDateSchema.nullable(),
});
/** What a mark or an unmark does to the country, or to one of its regions. */
export const atlasCountryChangeSchema = z.object({
op: z.enum(['mark', 'unmark']),
/** Set when the change is about one region of the country. */
region: z
.object({
code: atlasRegionCodeSchema,
name: cardText(80),
before: visitStatusSchema.nullable(),
after: atlasStatusAfterSchema,
})
.nullable(),
/** The country's own status once the change is applied. */
after: atlasStatusAfterSchema,
/** Visited countries of the whole atlas; null when the atlas could not be read. */
countries: atlasTallySchema.nullable(),
/** Visited regions of this country, on region changes only. */
regions: atlasTallySchema.nullable(),
});
/**
* One country of the atlas: its status, who marked it, the trips and places
* that put it there. An answer (`change` null) shows it as it is now; a change
* card shows it as it was, with what the mark or unmark does to it and to the
* visited counters.
*/
export const atlasCountryCardSchema = z.object({
kind: z.literal('atlasCountry'),
code: atlasCountryCodeSchema,
/** Now on an answer, before the change on a change card; null when the country is not on the map. */
status: visitStatusSchema.nullable(),
markedBy: z.enum(['manual', 'dawarich', 'region']).nullable(),
placeCount: cardCountSchema.nullable(),
tripCount: cardCountSchema.nullable(),
trips: z.array(atlasTripLineSchema).max(4),
moreTrips: cardCountSchema,
places: z.array(cardText(80)).max(8),
morePlaces: cardCountSchema,
change: atlasCountryChangeSchema.nullable(),
});
export type AtlasCountryCard = z.infer<typeof atlasCountryCardSchema>;
export type AtlasCountryChange = z.infer<typeof atlasCountryChangeSchema>;
export type AtlasTally = z.infer<typeof atlasTallySchema>;
export type AtlasStatusAfter = z.infer<typeof atlasStatusAfterSchema>;
@@ -0,0 +1,52 @@
import { visitStatusSchema } from '../../atlas/atlas.schema';
import { atlasCountryCodeSchema } from './atlas-country.card';
import { cardCountSchema, cardDateSchema, cardText } from './card-parts';
import { z } from 'zod';
/** The continents of CONTINENT_MAP and its fallback; the client names them with the Atlas page's own words. */
export const ATLAS_CARD_CONTINENTS = [
'Europe',
'Asia',
'North America',
'South America',
'Africa',
'Oceania',
'Antarctica',
'Other',
] as const;
export const atlasCardContinentSchema = z.enum(ATLAS_CARD_CONTINENTS);
export type AtlasCardContinent = z.infer<typeof atlasCardContinentSchema>;
/**
* The user's travel picture as the Atlas page shows it: visited, planned and
* wished-for countries, the trips, days, places and cities behind them, the
* distance flown, the flags, the continents, the next trip and the streak.
*/
export const atlasPassportCardSchema = z.object({
kind: z.literal('atlasPassport'),
countries: z.object({ visited: cardCountSchema, planned: cardCountSchema, idea: cardCountSchema }),
totals: z.object({
trips: cardCountSchema,
days: cardCountSchema,
places: cardCountSchema,
cities: cardCountSchema,
/** Rounded kilometres; null when nothing was flown. */
flownKm: cardCountSchema.nullable(),
}),
/** Visited countries, latest first, then planned ones, soonest first. */
flags: z.array(z.object({ code: atlasCountryCodeSchema, status: visitStatusSchema })).max(40),
moreFlags: cardCountSchema,
continents: z
.array(z.object({ name: atlasCardContinentSchema, visited: cardCountSchema, planned: cardCountSchema }))
.max(8),
nextTrip: z
.object({
title: cardText(80),
startDate: cardDateSchema.nullable(),
daysUntil: z.number().int().min(0).max(36_500).nullable(),
})
.nullable(),
streakYears: z.number().int().min(0).max(200).nullable(),
});
export type AtlasPassportCard = z.infer<typeof atlasPassportCardSchema>;
@@ -0,0 +1,19 @@
import { atlasBucketCardSchema } from './atlas-bucket.card';
import { atlasCountryCardSchema } from './atlas-country.card';
import { atlasPassportCardSchema } from './atlas-passport.card';
export * from './atlas-bucket.card';
export * from './atlas-country.card';
export * from './atlas-passport.card';
/**
* What the atlas brings to the assistant chat: the kinds of card it draws,
* the verbs of its change cards and what an applied change of its
* touches, beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else.
*/
export const ATLAS_CARD_SCHEMAS = [atlasPassportCardSchema, atlasCountryCardSchema, atlasBucketCardSchema] as const;
export const ATLAS_VERB_KEYS = [] as const;
/** A country, a region or a wish of the bucket list: the receipt opens the Atlas. */
export const ATLAS_APPLIED_ENTITIES = ['atlas'] as const;
@@ -0,0 +1,90 @@
import { ASSISTANT_CHANGE_VERB_KEYS, assistantChangePreviewSchema } from '../assistant.schema';
import { BOOK_DESIGN_CARD_LIMITS, bookDesignCardSchema } from './book-design.card';
import { BOOK_DESIGN_VERB_KEYS } from './book-design.contract';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { describe, expect, it } from 'vitest';
// BKDCARD-001 to BKDCARD-004
function card(over: Record<string, unknown> = {}) {
return {
kind: 'bookDesign',
change: 'proposed',
journeyId: 4,
designId: 'd-1',
baseVersion: 7,
style: 'editorial',
paper: '#faf8f4',
ink: '#1a1a1a',
accent: '#b45309',
heading: 'playfair',
body: 'garamond',
spreads: [
{
spreadId: 'sp-1',
index: 0,
action: 'replace',
beat: 'cover',
chapter: null,
entryId: null,
photoCount: 1,
severe: 0,
warn: 0,
},
{
spreadId: 'sp-9',
index: 3,
action: 'insert',
beat: 'hero',
chapter: 'Alfama',
entryId: 12,
photoCount: 1,
severe: 0,
warn: 1,
},
],
more: 0,
leftOut: 3,
revisionId: null,
skipped: [],
...over,
};
}
describe('the book design card', () => {
it('BKDCARD-001: reads a design card through the union, as itself', () => {
const parsed = trekCardSchema.parse(card());
expect(parsed.kind).toBe('bookDesign');
expect(bookDesignCardSchema.parse(parsed).spreads).toHaveLength(2);
expect(storedTrekCardSchema.parse(card({ change: 'applied', revisionId: 5 }))).toMatchObject({ revisionId: 5 });
});
it('BKDCARD-002: a field past its bound, an unknown style or reason, reads as no card', () => {
const page = card().spreads[1];
const longChapter = [{ ...page, chapter: 'x'.repeat(BOOK_DESIGN_CARD_LIMITS.chapter + 1) }];
expect(storedTrekCardSchema.parse(card({ spreads: longChapter }))).toBeNull();
expect(storedTrekCardSchema.parse(card({ style: 'baroque' }))).toBeNull();
expect(storedTrekCardSchema.parse(card({ skipped: [{ spreadId: 'sp-1', reason: 'tired' }] }))).toBeNull();
const many = Array.from({ length: BOOK_DESIGN_CARD_LIMITS.spreads + 1 }, () => page);
expect(storedTrekCardSchema.parse(card({ spreads: many }))).toBeNull();
});
it('BKDCARD-003: rides on a change preview with its own verb', () => {
const preview = assistantChangePreviewSchema.parse({
toolCallId: 'call_1',
verbKey: 'designBook',
subject: '',
rows: [],
dayId: null,
placeIds: [],
undoable: true,
card: card(),
});
expect([preview.verbKey, preview.card?.kind]).toEqual(['designBook', 'bookDesign']);
});
it('BKDCARD-004: names the verbs of the book-level changes in the shared enum', () => {
expect(ASSISTANT_CHANGE_VERB_KEYS).toEqual(expect.arrayContaining([...BOOK_DESIGN_VERB_KEYS]));
});
});
@@ -0,0 +1,66 @@
import { BOOK_DESIGN_SKIP_REASONS } from '../../book/book-design-tools.schema';
import { bookDesignIdSchema, bookSpreadIdSchema } from '../../book/book-ops.schema';
import { BOOK_FONTS_IDS } from '../../book/book.schema';
import { BOOK_DESIGN_STYLES } from '../../book/design/design-directives.schema';
import { BOOK_DESIGN_ACTIONS } from '../../book/design/design-merge';
import { BOOK_DESIGN_BEATS } from '../../book/design/design-pacing';
import { idSchema } from '../../common/primitives.schema';
import { cardCountSchema, cardHexColorSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* A whole-book design as the Studio's chat shows it: the book's look (style,
* paper, ink, accent, the two typefaces) and the plan page by page, what
* each page becomes and how many findings the server's check left on it.
* `none` is the answer of `design_book` (a draft, nothing proposed yet),
* `proposed` the held `apply_book_design`, `applied` its receipt with the
* revision that takes it back and the pages it left as they were. The pages
* themselves are drawn from the draft (GET /api/journeys/:id/book-designs/:designId),
* never carried in the card.
*/
export const BOOK_DESIGN_CARD_LIMITS = { spreads: 120, chapter: 40 } as const;
export const BOOK_DESIGN_CARD_CHANGES = ['none', 'proposed', 'applied'] as const;
/** One page of the plan as a card names it. */
export const bookDesignCardSpreadSchema = z.object({
spreadId: bookSpreadIdSchema,
index: cardCountSchema,
action: z.enum(BOOK_DESIGN_ACTIONS),
beat: z.enum(BOOK_DESIGN_BEATS),
chapter: cardText(BOOK_DESIGN_CARD_LIMITS.chapter).nullable(),
entryId: idSchema.nullable(),
photoCount: cardCountSchema,
severe: cardCountSchema,
warn: cardCountSchema,
});
export type BookDesignCardSpread = z.infer<typeof bookDesignCardSpreadSchema>;
export const bookDesignCardSchema = z.object({
kind: z.literal('bookDesign'),
change: z.enum(BOOK_DESIGN_CARD_CHANGES),
journeyId: idSchema,
designId: bookDesignIdSchema,
/** The book's version the draft was made against; null for a journey without a book. */
baseVersion: cardCountSchema.nullable(),
style: z.enum(BOOK_DESIGN_STYLES),
paper: cardHexColorSchema,
ink: cardHexColorSchema,
accent: cardHexColorSchema,
heading: z.enum(BOOK_FONTS_IDS),
body: z.enum(BOOK_FONTS_IDS),
spreads: z.array(bookDesignCardSpreadSchema).max(BOOK_DESIGN_CARD_LIMITS.spreads),
/** Plan pages past the ones listed. */
more: cardCountSchema,
/** Photos of the journey the design left out. */
leftOut: cardCountSchema,
/** Once applied: the revision the undo restores. */
revisionId: idSchema.nullable(),
/** Once applied: the pages the apply left as they were, and why. */
skipped: z
.array(z.object({ spreadId: bookSpreadIdSchema, reason: z.enum(BOOK_DESIGN_SKIP_REASONS) }))
.max(BOOK_DESIGN_CARD_LIMITS.spreads),
});
export type BookDesignCard = z.infer<typeof bookDesignCardSchema>;
@@ -0,0 +1,20 @@
import { bookDesignCardSchema } from './book-design.card';
export * from './book-design.card';
/**
* What the assistant's whole-book design brings to the chat: the card of a
* design and its proposal, and the verbs of the book-level changes (the
* design applied, the page format and numbers, a page copied, a layout kept
* or taken away). They touch pages of the book, so they name the photo
* book's own entity (`book_page`, book.contract.ts) and add none.
*/
export const BOOK_DESIGN_CARD_SCHEMAS = [bookDesignCardSchema] as const;
export const BOOK_DESIGN_VERB_KEYS = [
'designBook',
'setBookSetup',
'setBookTheme',
'duplicateBookPage',
'saveBookLayout',
'removeBookLayout',
] as const;
@@ -0,0 +1,119 @@
import { ASSISTANT_CHANGE_VERB_KEYS, assistantAppliedSchema, assistantChangePreviewSchema } from '../assistant.schema';
import { BOOK_PAGE_CARD_LIMITS, bookPageCardSchema, type BookCardPage } from './book-page.card';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { describe, expect, it } from 'vitest';
// BOOKCARD-001 to BOOKCARD-007
function page(over: Partial<BookCardPage> = {}): BookCardPage {
return { spreadId: 'sp-lisbon', index: 2, role: 'inner', number: 1, photos: 3, ...over };
}
function card(over: Record<string, unknown> = {}) {
return {
kind: 'bookPage',
journeyId: 4,
change: 'changed',
baseVersion: 7,
pages: [page()],
count: 0,
movedTo: null,
ops: [
{ op: 'layout', template: 'two-up' },
{ op: 'background', color: '#f4efe6' },
],
cover: null,
layout: { kind: 'template', id: 'two-up', name: null },
photosAdded: 2,
findings: [{ code: 'overlap', severity: 'severe' }],
moreFindings: 0,
...over,
};
}
describe('the book page card', () => {
it('BOOKCARD-001: reads a full card through the union, as itself, its operations parsed by the book engine', () => {
const parsed = trekCardSchema.parse(card());
expect(parsed.kind).toBe('bookPage');
const own = bookPageCardSchema.parse(parsed);
expect(own.ops).toHaveLength(2);
expect(own.ops[0]).toMatchObject({ op: 'layout', template: 'two-up' });
});
it('BOOKCARD-002: a cover change carries its arguments, a new book no page and no version', () => {
const cover = { template: 'cover-full', photoId: 81, title: 'Portugal', subtitle: null };
expect(bookPageCardSchema.safeParse(card({ ops: [], cover, layout: null })).success).toBe(true);
const fresh = card({ change: 'new', baseVersion: null, pages: [], count: 5, ops: [], layout: null, findings: [] });
expect(bookPageCardSchema.safeParse(fresh).success).toBe(true);
});
it('BOOKCARD-003: an operation the engine refuses, an unknown template or a page past the cap reads as no card', () => {
expect(storedTrekCardSchema.parse(card({ ops: [{ op: 'explode' }] }))).toBeNull();
const cover = { template: 'nope', photoId: null, title: null, subtitle: null };
expect(storedTrekCardSchema.parse(card({ cover }))).toBeNull();
const eleven = Array.from({ length: 11 }, (_, i) => page({ spreadId: `sp-${i}`, index: i }));
expect(storedTrekCardSchema.parse(card({ pages: eleven }))).toBeNull();
expect(storedTrekCardSchema.parse(card({ pages: [page({ spreadId: 'not a page id' })] }))).toBeNull();
});
it('BOOKCARD-004: holds at most six findings, each a known code and severity', () => {
const findings = Array.from({ length: BOOK_PAGE_CARD_LIMITS.findings + 1 }, () => ({
code: 'empty_frame',
severity: 'warn',
}));
expect(bookPageCardSchema.safeParse(card({ findings })).success).toBe(false);
expect(bookPageCardSchema.safeParse(card({ findings: [{ code: 'ugly', severity: 'warn' }] })).success).toBe(false);
expect(bookPageCardSchema.safeParse(card({ findings: findings.slice(1), moreFindings: 3 })).success).toBe(true);
});
it('BOOKCARD-005: rides on a change preview', () => {
const preview = assistantChangePreviewSchema.parse({
toolCallId: 'call_1',
verbKey: 'editBookPage',
subject: 'Lisbon',
rows: [],
dayId: null,
placeIds: [],
undoable: true,
card: card(),
});
expect(preview.verbKey).toBe('editBookPage');
expect(preview.card?.kind).toBe('bookPage');
});
it('BOOKCARD-006: names its verbs and its entity in the shared enums', () => {
expect(ASSISTANT_CHANGE_VERB_KEYS).toEqual(
expect.arrayContaining([
'createBook',
'addBookPages',
'editBookPage',
'moveBookPage',
'removeBookPages',
'setBookCover',
]),
);
const applied = assistantAppliedSchema.parse({
toolCallId: 'call_1',
entity: 'book_page',
ids: [],
dayId: null,
undoUntil: null,
});
expect(applied.entity).toBe('book_page');
});
it('BOOKCARD-007: carries the page after as the server made it; without one it reads, an unreadable one drops itself', () => {
const after = { id: 'sp-lisbon', role: 'inner', background: '#ffffff', elements: [], parked: [], entryId: null };
expect(bookPageCardSchema.parse(card({ after })).after).toEqual(after);
// A card from before the page rode on it, as the thread keeps it, reads as it was.
expect(bookPageCardSchema.parse(card()).after).toBeUndefined();
expect(storedTrekCardSchema.parse(card())).toMatchObject({ kind: 'bookPage', journeyId: 4 });
// A page a later build cannot read drops itself, never the card: the Studio then runs the operations.
const unread = { ...after, background: 'white' };
const kept = bookPageCardSchema.parse(card({ after: unread }));
expect(kept.after).toBeUndefined();
expect(kept.ops).toHaveLength(2);
expect(storedTrekCardSchema.parse(card({ after: unread }))).toMatchObject({ kind: 'bookPage', journeyId: 4 });
});
});
@@ -0,0 +1,116 @@
import {
BOOK_FINDING_CODES,
BOOK_OP_LIMITS,
bookAnyTemplateIdSchema,
bookPageOpSchema,
bookSpreadIdSchema,
} from '../../book/book-ops.schema';
import { bookSpreadSchema, MAX_BOOK_TITLE, MAX_SPREADS } from '../../book/book.schema';
import { idSchema } from '../../common/primitives.schema';
import { cardCountSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* A change to a journey's photo book as the Studio's chat shows it: the pages
* a held book write works on, what it lays them out on and brings onto them,
* and what the server's check of the result found. For an edit or the cover
* it carries the page after as the server's trial of the change made it, so
* the Studio draws the page before and after with the view the editor uses,
* never from an image, and the page after as the server would write it. The
* page operations ride along for a card without that page and for a book
* that moved on since the trial: the Studio runs them on its own book with
* the same engine. Once applied it names the pages as the change left them.
*/
/** How much of a change a card carries; the server cuts to the same numbers. */
export const BOOK_PAGE_CARD_LIMITS = { findings: 6, layout: 60 } as const;
/** What the change does to its pages: makes them, changes them, moves one, or deletes them. */
export const BOOK_PAGE_CARD_CHANGES = ['new', 'changed', 'moved', 'willDelete'] as const;
/** One page as a card names it. */
export const bookCardPageSchema = z.object({
spreadId: bookSpreadIdSchema,
/** Where it stands in the book, the cover at 0. */
index: z
.number()
.int()
.min(0)
.max(MAX_SPREADS - 1),
role: bookSpreadSchema.shape.role.unwrap(),
/** Its place among the double pages, from 1; null for a single page (the covers, the first and the last). */
number: z.number().int().min(1).max(MAX_SPREADS).nullable(),
/** Photos placed on it. */
photos: cardCountSchema,
});
export type BookCardPage = z.infer<typeof bookCardPageSchema>;
/** A finding of the server's check, by its code: the client names it in the user's language. */
export const bookCardFindingSchema = z.object({
code: z.enum(BOOK_FINDING_CODES),
severity: z.enum(['severe', 'warn', 'info']),
});
export type BookCardFinding = z.infer<typeof bookCardFindingSchema>;
/** The layout a change lays a page out on. A saved layout carries its own name; the built-in ones the client names. */
export const bookCardLayoutSchema = z.object({
kind: z.enum(['template', 'grid', 'saved', 'auto']),
id: cardText(BOOK_PAGE_CARD_LIMITS.layout),
name: cardText(BOOK_PAGE_CARD_LIMITS.layout).nullable(),
});
export type BookCardLayout = z.infer<typeof bookCardLayoutSchema>;
/** `set_book_cover`'s arguments, null where the call leaves a part of the cover as it is. */
export const bookCardCoverSchema = z.object({
template: bookAnyTemplateIdSchema.nullable(),
photoId: idSchema.nullable(),
title: z.string().max(MAX_BOOK_TITLE).nullable(),
subtitle: z.string().max(MAX_BOOK_TITLE).nullable(),
});
export type BookCardCover = z.infer<typeof bookCardCoverSchema>;
export const bookPageCardSchema = z.object({
kind: z.literal('bookPage'),
journeyId: idSchema,
change: z.enum(BOOK_PAGE_CARD_CHANGES),
/** The book's version the change was checked against; null for a journey without a book. */
baseVersion: cardCountSchema.nullable(),
/**
* The pages the change works on, as they stand before it: the page edited,
* the cover, the page moved, the pages deleted, the page new ones follow.
* Once applied, the pages as the change left them, new ones included.
*/
pages: z.array(bookCardPageSchema).max(BOOK_OP_LIMITS.pagesPerCall),
/** How many pages the change adds or deletes; for a new book, its pages. */
count: cardCountSchema,
/** Where a moved page lands among the double pages, from 1. */
movedTo: z.number().int().min(1).max(MAX_SPREADS).nullable(),
/**
* `edit_book_page`'s operations, to draw the page after where the card has
* no `after` or the Studio's book moved on from `baseVersion`; empty for
* another tool, when too long to carry, or when the page after needs their
* room.
*/
ops: z.array(bookPageOpSchema).max(BOOK_OP_LIMITS.opsPerCall),
cover: bookCardCoverSchema.nullable(),
/**
* The page an edit or the cover leaves, as the server's trial of the change
* made it with the journey's photos, words and figures: a caption from its
* photo's caption, a text from its entry, a map from the route. The Studio
* draws the page after from it while its book is at `baseVersion`. Absent
* on a card from before it, on a page too heavy to carry and on another
* tool's card, where the Studio runs `ops` or `cover` on its own book, as
* it does once its book moved on; absent once applied, where it draws the
* page as it is. One a later build cannot read drops itself, never the card.
*/
after: bookSpreadSchema.optional().catch(undefined),
layout: bookCardLayoutSchema.nullable(),
/** Photos the change brings onto its pages that were not on them. */
photosAdded: cardCountSchema,
/** The check's findings on the pages after the change, the most severe first. */
findings: z.array(bookCardFindingSchema).max(BOOK_PAGE_CARD_LIMITS.findings),
/** Severe findings and warnings past those; the info ones past them are not counted. */
moreFindings: cardCountSchema,
});
export type BookPageCard = z.infer<typeof bookPageCardSchema>;
@@ -0,0 +1,23 @@
import { bookPageCardSchema } from './book-page.card';
export * from './book-page.card';
/**
* What the Studio's photo book brings to the assistant chat: the kind of card
* a held book write draws, the verbs of its change cards and what an applied
* one touches. cards/index.ts and assistant.schema.ts spread these into the
* card union and the shared enums, so a new kind, verb or entity is added
* here and nowhere else.
*/
export const BOOK_CARD_SCHEMAS = [bookPageCardSchema] as const;
/** A book laid down, pages added, changed, moved or deleted, the cover set. */
export const BOOK_VERB_KEYS = [
'createBook',
'addBookPages',
'editBookPage',
'moveBookPage',
'removeBookPages',
'setBookCover',
] as const;
/** A page of a journey's book; the receipt opens the Studio on it. Pages have string ids, so the card names them. */
export const BOOK_APPLIED_ENTITIES = ['book_page'] as const;
@@ -0,0 +1,125 @@
import {
BOOKING_CHANGED_FIELDS,
bookingCardSchema,
type BookingItem,
type BookingLeg,
type BookingStay,
type BookingTicket,
} from './booking.card';
import { BOOKING_APPLIED_ENTITIES, BOOKING_VERB_KEYS } from './booking.contract';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { describe, expect, it } from 'vitest';
const day = { id: 31, number: 1, date: '2026-06-03' };
const LEG: BookingLeg = {
carrier: 'Lufthansa',
number: 'LH 400',
departs: '08:15',
departsDay: day,
arrives: '11:05',
arrivesDay: day,
minutes: 530,
seat: '12A',
platform: null,
};
const TICKET: BookingTicket = {
shape: 'ticket',
stops: [
{ name: 'Frankfurt', code: 'FRA', lat: 50.03, lng: 8.57 },
{ name: 'New York', code: 'JFK', lat: 40.64, lng: -73.78 },
],
legs: [LEG],
minutes: 530,
mappable: true,
};
const STAY: BookingStay = {
shape: 'stay',
accommodationId: 601,
placeId: 12,
address: 'Invalidenstraße 38',
lat: 52.53,
lng: 13.38,
photoKey: 'ChIJmercure',
checkIn: { day, from: '15:00', until: '20:00' },
checkOut: { day: { id: 33, number: 3, date: '2026-06-05' }, by: '11:00' },
nights: 2,
};
const ticket: BookingItem = {
tripId: 4,
tripTitle: null,
reservationId: 501,
type: 'flight',
title: 'Frankfurt to New York',
status: 'confirmed',
needsReview: false,
hasReference: true,
price: { amount: 420, currency: 'EUR' },
travelers: [{ id: 7, name: 'mia', avatarKey: 'mia.png' }],
moreTravelers: 0,
changed: [],
body: TICKET,
};
const stay: BookingItem = {
...ticket,
reservationId: null,
type: 'hotel',
status: null,
body: STAY,
};
const card = (items: unknown[], extra: Record<string, unknown> = {}) => ({
kind: 'booking',
change: 'none',
items,
more: 0,
...extra,
});
describe('bookingCardSchema', () => {
it('CARDBOOK-001: takes a ticket, a stay and a venue in one card, and the union reads it', () => {
const body = { shape: 'venue', day, starts: '19:00', ends: null, location: 'Borchardt', placeId: 13 };
const venue = { ...ticket, body: { ...body, lat: null, lng: null } };
expect(bookingCardSchema.safeParse(card([ticket, stay, venue])).success).toBe(true);
expect(trekCardSchema.safeParse(card([ticket], { change: 'update' })).success).toBe(true);
});
it('CARDBOOK-002: holds one to eight bookings and counts the rest', () => {
expect(bookingCardSchema.safeParse(card([])).success).toBe(false);
expect(bookingCardSchema.safeParse(card(Array.from({ length: 9 }, () => ticket))).success).toBe(false);
expect(bookingCardSchema.safeParse(card([ticket], { more: -1 })).success).toBe(false);
});
it('CARDBOOK-003: refuses a picture address or a coordinate key as photo key, and a clock past 23:59', () => {
const photo = (photoKey: string) => card([{ ...stay, body: { ...STAY, photoKey } }]);
expect(bookingCardSchema.safeParse(photo('https://maps.example/x.jpg')).success).toBe(false);
expect(bookingCardSchema.safeParse(photo('coords:52.5,13.4')).success).toBe(false);
const late = { ...ticket, body: { ...TICKET, legs: [{ ...LEG, departs: '24:00' }] } };
expect(bookingCardSchema.safeParse(card([late])).success).toBe(false);
});
it('CARDBOOK-004: refuses a ticket without a leg, an unknown shape, a lowercase code and a currency in words', () => {
expect(bookingCardSchema.safeParse(card([{ ...ticket, body: { ...TICKET, legs: [] } }])).success).toBe(false);
expect(bookingCardSchema.safeParse(card([{ ...ticket, body: { shape: 'cruise' } }])).success).toBe(false);
const code = { ...ticket, body: { ...TICKET, stops: [{ name: 'Frankfurt', code: 'fra', lat: null, lng: null }] } };
expect(bookingCardSchema.safeParse(card([code])).success).toBe(false);
const words = { ...ticket, price: { amount: 5, currency: 'euro' } };
expect(bookingCardSchema.safeParse(card([words])).success).toBe(false);
});
it('CARDBOOK-005: a changed field must be one the card knows; a broken card reads as none, never the message', () => {
expect(bookingCardSchema.safeParse(card([{ ...ticket, changed: [...BOOKING_CHANGED_FIELDS] }])).success).toBe(true);
expect(bookingCardSchema.safeParse(card([{ ...ticket, changed: ['seat'] }])).success).toBe(false);
expect(storedTrekCardSchema.parse(card([{ ...ticket, title: '' }]))).toBeNull();
});
it('CARDBOOK-006: the bookings add their verbs and the stay as an applied entity', () => {
expect(BOOKING_VERB_KEYS).toEqual(['addStay', 'updateStay', 'updateReservation']);
expect(BOOKING_APPLIED_ENTITIES).toEqual(['accommodation']);
});
});
+153
View File
@@ -0,0 +1,153 @@
import { idSchema } from '../../common/primitives.schema';
import { RESERVATION_STATUSES } from '../../reservation/reservation-types';
import {
cardClockSchema,
cardCountSchema,
cardDaySchema,
cardLatSchema,
cardLngSchema,
cardMoneySchema,
cardPersonSchema,
cardPhotoKeySchema,
cardText,
} from './card-parts';
import { z } from 'zod';
/**
* Bookings in the assistant chat: a flight, a train, a hire car (a ticket), a
* hotel or any stay (a stay), a table, a show, a tour or a car park (a
* venue). One card per tool call holds the bookings it is about, at most
* eight, with the rest counted; an e-ticket file with a flight, a hotel and a
* flight back stays one itinerary. A booking's reference never travels, only
* that it has one: the chat is stored and can be shared, and the planner
* blurs it too.
*/
/** The type column is free text: any short key passes, the client draws an unknown one as `other`. */
const bookingTypeSchema = z.string().regex(/^[a-z_]{1,30}$/);
const lat = cardLatSchema.nullable();
const lng = cardLngSchema.nullable();
/** One end or stop of a route: the airport or station, its code where it has one. */
const bookingStopSchema = z.object({
name: cardText(80),
code: z
.string()
.regex(/^[A-Z0-9]{2,5}$/)
.nullable(),
lat,
lng,
});
/** One segment; a stopover's arrival lives only here (a stop's endpoint carries the onward departure). */
const bookingLegSchema = z.object({
carrier: cardText(60).nullable(),
number: cardText(20).nullable(),
departs: cardClockSchema.nullable(),
departsDay: cardDaySchema.nullable(),
arrives: cardClockSchema.nullable(),
arrivesDay: cardDaySchema.nullable(),
/** Only when both ends know their zone. */
minutes: z.number().int().min(1).max(10_080).nullable(),
seat: cardText(20).nullable(),
platform: cardText(20).nullable(),
});
const ticketBodySchema = z.object({
shape: z.literal('ticket'),
/** From, the stops, to; empty when no route is known (a hire car, a taxi). */
stops: z.array(bookingStopSchema).max(9),
/** One per segment between the stops, else exactly one. */
legs: z.array(bookingLegSchema).min(1).max(8),
/** First departure to last arrival. */
minutes: z.number().int().min(1).max(20_160).nullable(),
/** A saved booking with two stops that have coordinates: the plan can draw it. */
mappable: z.boolean(),
});
const stayBodySchema = z.object({
shape: z.literal('stay'),
/** Null while a create or a new place waits. */
accommodationId: idSchema.nullable(),
placeId: idSchema.nullable(),
address: cardText(200).nullable(),
lat,
lng,
/** A Google place id for TREK's photo proxy; never a picture address. */
photoKey: cardPhotoKeySchema.nullable(),
checkIn: z
.object({ day: cardDaySchema, from: cardClockSchema.nullable(), until: cardClockSchema.nullable() })
.nullable(),
checkOut: z.object({ day: cardDaySchema, by: cardClockSchema.nullable() }).nullable(),
nights: z.number().int().min(0).max(366).nullable(),
});
const venueBodySchema = z.object({
shape: z.literal('venue'),
day: cardDaySchema.nullable(),
starts: cardClockSchema.nullable(),
ends: cardClockSchema.nullable(),
/** The location text, else the linked place's name. */
location: cardText(200).nullable(),
placeId: idSchema.nullable(),
lat,
lng,
});
/** What an update changes, as the card shows it (its derived values, not the raw arguments). */
export const BOOKING_CHANGED_FIELDS = [
'title',
'type',
'status',
'day',
'time',
'route',
'stay',
'checkIn',
'checkOut',
'location',
'price',
'travelers',
'reference',
] as const;
export type BookingChangedField = (typeof BOOKING_CHANGED_FIELDS)[number];
export const bookingItemSchema = z.object({
tripId: idSchema,
/** Only on a row of another trip (the upcoming bookings across every trip). */
tripTitle: cardText(120).nullable(),
reservationId: idSchema.nullable(),
type: bookingTypeSchema,
title: cardText(200),
/** Null for a transit journey, a bare stay, or a status not known. */
status: z.enum(RESERVATION_STATUSES).nullable(),
needsReview: z.boolean(),
/** A confirmation number exists; the number itself never travels. */
hasReference: z.boolean(),
price: cardMoneySchema.nullable(),
travelers: z.array(cardPersonSchema).max(8),
moreTravelers: z.number().int().min(0).max(500),
changed: z.array(z.enum(BOOKING_CHANGED_FIELDS)).max(BOOKING_CHANGED_FIELDS.length),
body: z.discriminatedUnion('shape', [ticketBodySchema, stayBodySchema, venueBodySchema]),
});
export type BookingItem = z.infer<typeof bookingItemSchema>;
export type BookingBody = BookingItem['body'];
export type BookingTicket = Extract<BookingBody, { shape: 'ticket' }>;
export type BookingStay = Extract<BookingBody, { shape: 'stay' }>;
export type BookingVenue = Extract<BookingBody, { shape: 'venue' }>;
export type BookingLeg = BookingTicket['legs'][number];
export type BookingStop = BookingTicket['stops'][number];
/** What a held write does to its bookings; `none` on an answer and on an applied change. */
export const BOOKING_CHANGES = ['none', 'create', 'update', 'remove'] as const;
export const bookingCardSchema = z.object({
kind: z.literal('booking'),
change: z.enum(BOOKING_CHANGES),
items: z.array(bookingItemSchema).min(1).max(8),
/** Bookings the answer held past the eight shown. */
more: cardCountSchema,
});
export type BookingCard = z.infer<typeof bookingCardSchema>;
@@ -0,0 +1,16 @@
import { bookingCardSchema } from './booking.card';
export * from './booking.card';
/**
* What the bookings bring to the assistant chat: the kinds of card they draw,
* the verbs of their change cards and what an applied change of theirs
* touches, beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else.
*/
export const BOOKING_CARD_SCHEMAS = [bookingCardSchema] as const;
/** addReservation and importBooking sit in the core list already. */
export const BOOKING_VERB_KEYS = ['addStay', 'updateStay', 'updateReservation'] as const;
/** 'reservation' is a core entity already; a stay is its own row. */
export const BOOKING_APPLIED_ENTITIES = ['accommodation'] as const;
@@ -0,0 +1,154 @@
import { ASSISTANT_CHANGE_VERB_KEYS, assistantAppliedSchema, assistantChangePreviewSchema } from '../assistant.schema';
import { BUDGET_APPLIED_ENTITIES, BUDGET_CARD_SCHEMAS, BUDGET_VERB_KEYS } from './budget.contract';
import { costPerPersonCardSchema, type CostPerPersonCard } from './cost-per-person.card';
import { EXPENSE_PEOPLE_MAX, expensesCardSchema, type CardExpense, type ExpensesCard } from './expenses.card';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { paymentsCardSchema, type PaymentsCard } from './payments.card';
import { settlementCardSchema, type SettlementCard } from './settlement.card';
import { describe, expect, it } from 'vitest';
const ana = { id: 7, name: 'Ana', avatarKey: 'ana.png' };
const ben = { id: 8, name: 'Ben', avatarKey: null };
const dinner: CardExpense = {
id: 31,
name: 'Dinner at Lokanta',
category: 'food',
amount: { amount: 84, currency: 'EUR' },
tripAmount: null,
date: '2026-06-03',
place: { id: 12, name: 'Lokanta' },
payers: [{ person: ana, amount: 84 }],
split: 'equal',
shares: [
{ person: ana, amount: 42, paid: true },
{ person: ben, amount: 42, paid: false },
],
moreShares: 0,
note: null,
receipts: 2,
before: null,
highlight: [],
change: 'none',
};
const expenses: ExpensesCard = {
kind: 'expenses',
rows: [dinner],
offset: 0,
more: 13,
total: { amount: 1204.5, currency: 'EUR' },
unconverted: 1,
};
const payments: PaymentsCard = {
kind: 'payments',
rows: [
{
id: null,
from: ben,
to: ana,
amount: { amount: 42.5, currency: 'EUR' },
date: '2026-06-07',
note: 'Bank transfer',
before: { from: ana, to: null, amount: { amount: 40, currency: 'EUR' } },
change: 'changed',
},
],
more: 0,
};
const settlement: SettlementCard = {
kind: 'settlement',
currency: 'EUR',
flows: [{ from: ben, to: ana, amount: 42.5 }],
moreFlows: 0,
balances: [
{ person: ana, balance: 42.5 },
{ person: ben, balance: -42.5 },
],
moreBalances: 0,
recorded: 3,
unconverted: { entries: 2, currencies: ['USD'] },
};
const perPerson: CostPerPersonCard = {
kind: 'costPerPerson',
currency: 'EUR',
rows: [{ person: ana, share: 69, paid: 45, count: 2 }],
more: 0,
};
describe('budget cards', () => {
it('CARDS-BUD-001: the four kinds join the card union and read back as built', () => {
expect(BUDGET_CARD_SCHEMAS).toEqual([
expensesCardSchema,
paymentsCardSchema,
settlementCardSchema,
costPerPersonCardSchema,
]);
for (const card of [expenses, payments, settlement, perPerson]) {
expect(trekCardSchema.parse(card)).toEqual(card);
expect(storedTrekCardSchema.parse(card)).toEqual(card);
}
});
it('CARDS-BUD-002: a waiting change states what it replaces and whom it is about', () => {
const update: CardExpense = {
...dinner,
amount: { amount: 96, currency: 'EUR' },
before: { name: null, amount: { amount: 84, currency: 'EUR' }, category: null, date: null, split: 'custom' },
highlight: [8],
change: 'changed',
};
expect(expensesCardSchema.parse({ ...expenses, rows: [update], total: null }).rows[0]).toEqual(update);
expect(expensesCardSchema.safeParse({ ...expenses, rows: [{ ...update, change: 'moved' }] }).success).toBe(false);
// A refund is a negative amount; nothing past a billion is.
const refund = { ...dinner, amount: { amount: -20, currency: 'EUR' } };
expect(expensesCardSchema.safeParse({ ...expenses, rows: [refund] }).success).toBe(true);
expect(expensesCardSchema.safeParse({ ...expenses, total: { amount: 2e9, currency: 'EUR' } }).success).toBe(false);
});
it('CARDS-BUD-003: lists and splits are bounded, and a card past a bound reads as no card', () => {
const many = Array.from({ length: EXPENSE_PEOPLE_MAX + 1 }, (_, i) => ({
person: { ...ben, id: 100 + i },
amount: 1,
paid: false,
}));
expect(storedTrekCardSchema.parse({ ...expenses, rows: [{ ...dinner, shares: many }] })).toBeNull();
expect(storedTrekCardSchema.parse({ ...expenses, rows: Array.from({ length: 13 }, () => dinner) })).toBeNull();
expect(storedTrekCardSchema.parse({ ...expenses, rows: [] })).toBeNull();
expect(storedTrekCardSchema.parse({ ...expenses, offset: -1 })).toBeNull();
const free = { ...payments.rows[0], amount: { amount: 0, currency: 'EUR' } };
expect(storedTrekCardSchema.parse({ ...payments, rows: [free] })).toBeNull();
expect(storedTrekCardSchema.parse({ ...settlement, currency: 'euro' })).toBeNull();
expect(storedTrekCardSchema.parse({ ...perPerson, rows: [] })).toBeNull();
});
it('CARDS-BUD-004: people carry a stored file name only, never an address', () => {
const linked = { ...ana, avatarKey: 'https://sso.example/ana.png' };
expect(storedTrekCardSchema.parse({ ...perPerson, rows: [{ ...perPerson.rows[0], person: linked }] })).toBeNull();
const upward = { from: ana, to: { ...ben, avatarKey: '../x' }, amount: 1 };
expect(storedTrekCardSchema.parse({ ...settlement, flows: [upward] })).toBeNull();
});
it('CARDS-BUD-005: a payment change reads its verb, and a payment receipt its own entity', () => {
expect(BUDGET_VERB_KEYS).toEqual(['addPayment', 'updatePayment']);
for (const verb of BUDGET_VERB_KEYS) expect(ASSISTANT_CHANGE_VERB_KEYS).toContain(verb);
const preview = {
toolCallId: 'c1',
verbKey: 'addPayment',
subject: 'Ben → Ana',
rows: [],
dayId: null,
placeIds: [],
undoable: true,
card: payments,
};
expect(assistantChangePreviewSchema.parse(preview)).toMatchObject({ verbKey: 'addPayment', card: payments });
expect(BUDGET_APPLIED_ENTITIES).toEqual(['settlement']);
const receipt = { toolCallId: 'c1', entity: 'settlement', ids: [5], dayId: null, undoUntil: null };
expect(assistantAppliedSchema.parse(receipt).entity).toBe('settlement');
});
});
@@ -0,0 +1,27 @@
import { costPerPersonCardSchema } from './cost-per-person.card';
import { expensesCardSchema } from './expenses.card';
import { paymentsCardSchema } from './payments.card';
import { settlementCardSchema } from './settlement.card';
export * from './cost-per-person.card';
export * from './expenses.card';
export * from './payments.card';
export * from './settlement.card';
/**
* What the budget brings to the assistant chat: the kinds of card it draws,
* the verbs of its change cards and what an applied change of its
* touches, beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else.
*/
export const BUDGET_CARD_SCHEMAS = [
expensesCardSchema,
paymentsCardSchema,
settlementCardSchema,
costPerPersonCardSchema,
] as const;
/** A settle-up payment recorded or changed; removing one is a plain removal. */
export const BUDGET_VERB_KEYS = ['addPayment', 'updatePayment'] as const;
/** A settle-up payment: the receipt opens the Costs tab, where the payments are listed. */
export const BUDGET_APPLIED_ENTITIES = ['settlement'] as const;
+60
View File
@@ -0,0 +1,60 @@
import { idSchema } from '../../common/primitives.schema';
import { z } from 'zod';
/**
* The pieces every card of the assistant chat is built from. A kind uses
* these, `idSchema` and its domain's own enums, nothing else, so every card
* bounds its text the same way and none of them carries a URL or a path: a
* picture travels as a key the client turns into TREK's own address.
*/
/** One line of text, clipped and masked by the server before it is sent. */
export const cardText = (max: number) => z.string().min(1).max(max);
export const cardLatSchema = z.number().min(-90).max(90);
export const cardLngSchema = z.number().min(-180).max(180);
/** A point of a line to draw, `[lat, lng]` at five decimals; single points are `{ lat, lng }` objects. */
export type CardPoint = [number, number];
// Re-typed on the way out: server and client compile without strictNullChecks, where an inferred tuple
// makes every item optional and no longer fits a `[number, number]`.
export const cardPointSchema = z.tuple([cardLatSchema, cardLngSchema]).transform(([lat, lng]): CardPoint => [lat, lng]);
export const cardDateSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
export const cardClockSchema = z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/);
export const cardInstantSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);
/** A colour the data carries (a member's, a category's); the client draws it through safeHexColor. */
export const cardHexColorSchema = z.string().regex(/^#[0-9a-fA-F]{6}$/);
export const cardCurrencySchema = z.string().regex(/^[A-Z]{3}$/);
export const cardMoneySchema = z.object({ amount: z.number().min(-1e9).max(1e9), currency: cardCurrencySchema });
export const cardCountSchema = z.number().int().min(0).max(1_000_000);
/** A stored file name (an avatar, a place image): the client builds TREK's own path. Never a URL, never a path. */
export const cardFileKeySchema = z.string().regex(/^(?!.*\.\.)[A-Za-z0-9][\w.-]{0,199}$/);
/** A Google place id for TREK's photo proxy, like a found place's photo key without `coords:`. */
export const cardPhotoKeySchema = z.string().regex(/^[\w-]{1,200}$/);
/** A traveller as a card shows them: the client compares `id` with the signed-in user, so no card says "me". */
export const cardPersonSchema = z.object({
id: idSchema,
name: cardText(80),
avatarKey: cardFileKeySchema.nullable(),
});
/** A trip day: its id for links, its number or date for words. */
export const cardDaySchema = z.object({
id: idSchema.nullable(),
number: z.number().int().min(1).max(999).nullable(),
date: cardDateSchema.nullable(),
});
/** The most one card may weigh, as JSON text; a heavier one is not sent at all. */
export const MAX_CARD_CHARS = 24_000;
export type CardMoney = z.infer<typeof cardMoneySchema>;
export type CardPerson = z.infer<typeof cardPersonSchema>;
export type CardDay = z.infer<typeof cardDaySchema>;
@@ -0,0 +1,33 @@
import { idSchema } from '../../common/primitives.schema';
import { cardInstantSchema, cardLatSchema, cardLngSchema, cardMoneySchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* A charger as one look at it found it: how many points were free when it
* was checked, the cheapest published price per kWh, and where the figures
* come from. A snapshot with its time, never refreshed in the chat, and
* never the source's address: the attribution is its name and licence.
*/
export const chargingCardSchema = z.object({
kind: z.literal('charging'),
// The stop of the trip it is, or null for a charger found by its position.
placeId: idSchema.nullable(),
name: cardText(80).nullable(),
station: cardText(120).nullable(),
lat: cardLatSchema.nullable(),
lng: cardLngSchema.nullable(),
status: z.enum(['ok', 'unknown', 'ambiguous', 'unavailable']),
stale: z.boolean(),
available: z.number().int().min(0).max(999).nullable(),
total: z.number().int().min(0).max(999),
checkedAt: cardInstantSchema.nullable(),
updatedAt: cardInstantSchema.nullable(),
// The cheapest unconditional energy price with tax, per kWh; null when the prices are in several currencies.
energy: cardMoneySchema.nullable(),
// The other price components the tariffs name besides that one.
otherPrices: z.number().int().min(0).max(99),
source: cardText(80).nullable(),
license: cardText(120).nullable(),
});
export type ChargingCard = z.infer<typeof chargingCardSchema>;
@@ -0,0 +1,67 @@
import { idSchema } from '../../common/primitives.schema';
import { cardInstantSchema, cardPersonSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* Messages of the trip chat, drawn the way the chat draws them: a bubble per
* message, the others on one side with their face and name, the user's own on
* the other in the accent. An answer shows the last few messages a read
* returned and counts the older ones; a held write shows the one message it
* sends, removes or reacts to, as it will look afterwards. A file travels as
* its id only, which the client turns into TREK's own download path.
*/
/** One emoji of a message's reactions; `mine` says the signed-in user is among them, which only the server knows. */
const chatReactionSchema = z.object({
emoji: z.string().min(1).max(16),
count: z.number().int().min(1).max(999),
mine: z.boolean(),
/** The first names behind it, for the tooltip the chat shows. */
names: z.array(cardText(80)).max(6),
});
/** A file sent with a message: an image is drawn in the bubble, any other file named. */
const chatFileSchema = z.object({
fileId: idSchema,
image: z.boolean(),
name: cardText(120).nullable(),
});
/** The message a bubble answers, quoted on top of it. */
const chatReplySchema = z.object({
name: cardText(80),
text: cardText(120),
});
export const COLLAB_BUBBLE_CHANGES = ['none', 'send', 'remove', 'react'] as const;
export const collabBubbleCardSchema = z.object({
/** Null while a send waits for its decision. */
id: idSchema.nullable(),
author: cardPersonSchema,
/** Line breaks kept; empty only for a message that is an image alone. */
text: z.string().max(4000),
/** The text was cut: an excerpt of a long message, or a send longer than the bubble holds. */
cut: z.boolean(),
/** Null while a send waits for its decision. */
at: cardInstantSchema.nullable(),
reply: chatReplySchema.nullable(),
reactions: z.array(chatReactionSchema).max(8),
files: z.array(chatFileSchema).max(4),
/** Shared from an assistant answer: the chat marks it so. */
fromAssistant: z.boolean(),
change: z.enum(COLLAB_BUBBLE_CHANGES),
/** The emoji a held reaction toggles. */
reactEmoji: z.string().min(1).max(16).nullable(),
});
export type CollabBubbleCard = z.infer<typeof collabBubbleCardSchema>;
export const collabChatCardSchema = z.object({
kind: z.literal('collabChat'),
/** Oldest first, as the chat lists them. */
messages: z.array(collabBubbleCardSchema).min(1).max(6),
/** Older messages of the read that are not shown. */
earlier: z.number().int().min(0).max(10_000),
});
export type CollabChatCard = z.infer<typeof collabChatCardSchema>;
@@ -0,0 +1,44 @@
import { idSchema } from '../../common/primitives.schema';
import { cardCountSchema, cardHexColorSchema, cardPersonSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* Shared notes of the trip, drawn like the note cards of the Collab tab: a
* head band tinted by the category's colour with its title, and the start of
* its text under it. An answer holds up to four notes of a read (pinned
* first) and counts the rest; a held write holds the one note it adds,
* changes or deletes, as it will look afterwards. A note's link travels as
* its host only, never as an address the chat could open.
*/
export const COLLAB_NOTE_CHANGES = ['none', 'create', 'update', 'remove'] as const;
/** The parts of a note a held change sets to something new. */
export const COLLAB_NOTE_FIELDS = ['title', 'body', 'category', 'color', 'website', 'pinned'] as const;
export const collabNoteCardSchema = z.object({
/** Null while a new note waits for its decision. */
noteId: idSchema.nullable(),
title: cardText(200),
/** Markdown with its line breaks, shown in three lines as the note card does. */
body: z.string().min(1).max(600).nullable(),
category: cardText(100).nullable(),
color: cardHexColorSchema.nullable(),
pinned: z.boolean(),
/** "example.org": the host of the note's link. */
websiteHost: z.string().min(1).max(253).nullable(),
files: z.number().int().min(0).max(999),
author: cardPersonSchema.nullable(),
change: z.enum(COLLAB_NOTE_CHANGES),
changed: z.array(z.enum(COLLAB_NOTE_FIELDS)).max(6),
});
export type CollabNoteCard = z.infer<typeof collabNoteCardSchema>;
export const collabNotesCardSchema = z.object({
kind: z.literal('collabNotes'),
notes: z.array(collabNoteCardSchema).min(1).max(4),
/** Notes of the read that are not shown. */
more: cardCountSchema,
});
export type CollabNotesCard = z.infer<typeof collabNotesCardSchema>;
@@ -0,0 +1,54 @@
import { idSchema } from '../../common/primitives.schema';
import { cardCountSchema, cardInstantSchema, cardPersonSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* Polls of the trip, drawn like the poll cards of the Collab tab: the
* question, what kind of poll it is, and its options with their bars. An
* answer holds up to four polls of a read (open ones first) and counts the
* rest; a held write holds the one poll it starts, votes in, closes or
* deletes, as it will look afterwards. Whether the signed-in user voted for
* an option is something only the server knows, so it travels as `mine`.
*/
const pollOptionCardSchema = z.object({
text: cardText(160),
votes: z.number().int().min(0).max(9999),
mine: z.boolean(),
/** The first three voters, as the poll card shows them. */
voters: z.array(cardPersonSchema).max(3),
});
export const COLLAB_POLL_CHANGES = ['none', 'create', 'vote', 'close', 'remove'] as const;
/** Why the server would refuse a held vote: the poll is closed, or it has no such option. */
export const COLLAB_POLL_WARNINGS = ['closed', 'unknownOption'] as const;
export const collabPollCardSchema = z.object({
/** Null while a new poll waits for its decision. */
pollId: idSchema.nullable(),
question: cardText(300),
options: z.array(pollOptionCardSchema).min(1).max(12),
moreOptions: z.number().int().min(0).max(500),
multiple: z.boolean(),
/** Closed by hand; the client adds the deadline, as the Collab tab does. */
closed: z.boolean(),
deadline: cardInstantSchema.nullable(),
author: cardPersonSchema.nullable(),
change: z.enum(COLLAB_POLL_CHANGES),
/** The option a held vote toggles. */
votedIndex: z.number().int().min(0).max(499).nullable(),
/** True when the held vote is cast, false when it is taken back. */
votedAdds: z.boolean(),
warning: z.enum(COLLAB_POLL_WARNINGS).nullable(),
});
export type CollabPollCard = z.infer<typeof collabPollCardSchema>;
export const collabPollsCardSchema = z.object({
kind: z.literal('collabPolls'),
polls: z.array(collabPollCardSchema).min(1).max(4),
/** Polls of the read that are not shown. */
more: cardCountSchema,
});
export type CollabPollsCard = z.infer<typeof collabPollsCardSchema>;
@@ -0,0 +1,130 @@
import { assistantAppliedSchema } from '../assistant.schema';
import {
COLLAB_APPLIED_ENTITIES,
COLLAB_VERB_KEYS,
type CollabChatCard,
type CollabNotesCard,
type CollabPollsCard,
} from './collab.contract';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { describe, expect, it } from 'vitest';
const ANNA = { id: 7, name: 'Anna', avatarKey: 'anna.png' };
/** A message as the trip chat shows it. */
const bubble = (over: Partial<CollabChatCard['messages'][number]> = {}): CollabChatCard['messages'][number] => ({
id: 11,
author: ANNA,
text: 'Shall we take\nthe early train?',
cut: false,
at: '2026-10-21T09:12:00Z',
reply: null,
reactions: [{ emoji: '❤️', count: 2, mine: true, names: ['Anna', 'Jon'] }],
files: [{ fileId: 4, image: true, name: 'ticket.jpg' }],
fromAssistant: false,
change: 'none',
reactEmoji: null,
...over,
});
const chat = (over: Partial<CollabChatCard> = {}): CollabChatCard => ({
kind: 'collabChat',
messages: [bubble()],
earlier: 3,
...over,
});
const poll = (over: Partial<CollabPollsCard['polls'][number]> = {}): CollabPollsCard['polls'][number] => ({
pollId: 5,
question: 'Where do we eat on Friday?',
options: [
{ text: 'Trattoria Roma', votes: 2, mine: true, voters: [ANNA] },
{ text: 'Night market', votes: 0, mine: false, voters: [] },
],
moreOptions: 0,
multiple: false,
closed: false,
deadline: '2026-10-24T18:00:00Z',
author: ANNA,
change: 'none',
votedIndex: null,
votedAdds: false,
warning: null,
...over,
});
const note = (over: Partial<CollabNotesCard['notes'][number]> = {}): CollabNotesCard['notes'][number] => ({
noteId: 9,
title: 'Restaurants to try',
body: 'Pasta at **Luigi**\nthe rooftop bar',
category: 'Ideas',
color: '#10b981',
pinned: true,
websiteHost: 'luigis.it',
files: 2,
author: ANNA,
change: 'none',
changed: [],
...over,
});
describe('the trip chat cards', () => {
it('CARDS-COLLAB-001: a chat, a poll and a note card read as themselves in the union', () => {
for (const card of [
chat(),
{ kind: 'collabPolls', polls: [poll()], more: 2 },
{ kind: 'collabNotes', notes: [note()], more: 0 },
]) {
expect(trekCardSchema.parse(card)).toEqual(card);
}
});
it('CARDS-COLLAB-002: a held send has no id and no time yet, and an image alone has no text', () => {
const held = chat({ messages: [bubble({ id: null, at: null, change: 'send', reactions: [], files: [] })] });
expect(trekCardSchema.parse(held)).toEqual(held);
expect(trekCardSchema.safeParse(chat({ messages: [bubble({ text: '' })] })).success).toBe(true);
});
it('CARDS-COLLAB-003: an avatar is a stored file name, never an address or a way up', () => {
for (const avatarKey of ['https://idp.test/me.png', '../secret.png', '/uploads/avatars/a.png']) {
const card = chat({ messages: [bubble({ author: { ...ANNA, avatarKey } })] });
expect(trekCardSchema.safeParse(card).success).toBe(false);
expect(storedTrekCardSchema.parse(card)).toBeNull();
}
});
it('CARDS-COLLAB-004: a time is a UTC moment to the second, as the server normalises it', () => {
expect(trekCardSchema.safeParse(chat({ messages: [bubble({ at: '2026-10-21 09:12:00' })] })).success).toBe(false);
expect(trekCardSchema.safeParse(chat({ messages: [bubble({ at: '2026-10-21T09:12Z' })] })).success).toBe(false);
const late = { kind: 'collabPolls', polls: [poll({ deadline: '2026-10-24' })], more: 0 };
expect(trekCardSchema.safeParse(late).success).toBe(false);
});
it('CARDS-COLLAB-005: lists past their bounds read as null', () => {
const seven = Array.from({ length: 7 }, (_, index) => bubble({ id: index + 1 }));
expect(storedTrekCardSchema.parse(chat({ messages: seven }))).toBeNull();
expect(storedTrekCardSchema.parse(chat({ messages: [] }))).toBeNull();
const five = [1, 2, 3, 4, 5].map((pollId) => poll({ pollId }));
expect(storedTrekCardSchema.parse({ kind: 'collabPolls', polls: five, more: 0 })).toBeNull();
expect(storedTrekCardSchema.parse({ kind: 'collabNotes', notes: [], more: 0 })).toBeNull();
const many = Array.from({ length: 13 }, (_, index) => ({ text: `#${index}`, votes: 0, mine: false, voters: [] }));
expect(storedTrekCardSchema.parse({ kind: 'collabPolls', polls: [poll({ options: many })], more: 0 })).toBeNull();
expect(storedTrekCardSchema.parse(chat({ messages: [bubble({ text: 'x'.repeat(4001) })] }))).toBeNull();
});
it('CARDS-COLLAB-006: a note colour is a hex colour and its link only a host', () => {
const tinted = { kind: 'collabNotes', notes: [note({ color: 'url(https://x.test/p)' })], more: 0 };
expect(trekCardSchema.safeParse(tinted).success).toBe(false);
const linked = { kind: 'collabNotes', notes: [{ ...note(), website: 'https://x.test' }], more: 0 };
expect(trekCardSchema.parse(linked)).toEqual({ kind: 'collabNotes', notes: [note()], more: 0 });
});
it('CARDS-COLLAB-007: the trip chat adds three applied entities and no verb', () => {
expect(COLLAB_VERB_KEYS).toEqual([]);
for (const entity of COLLAB_APPLIED_ENTITIES) {
const receipt = { toolCallId: 'call_1', entity, ids: [3], dayId: null, undoUntil: null };
expect(assistantAppliedSchema.parse(receipt).entity).toBe(entity);
}
});
});
@@ -0,0 +1,19 @@
import { collabChatCardSchema } from './collab-chat.card';
import { collabNotesCardSchema } from './collab-notes.card';
import { collabPollsCardSchema } from './collab-polls.card';
export * from './collab-chat.card';
export * from './collab-notes.card';
export * from './collab-polls.card';
/**
* What the trip chat brings to the assistant chat: the kinds of card it draws,
* the verbs of its change cards and the entities its applied changes touch,
* beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else. Its changes keep the generic
* verbs (add, change, remove) and name their tool instead.
*/
export const COLLAB_CARD_SCHEMAS = [collabChatCardSchema, collabPollsCardSchema, collabNotesCardSchema] as const;
export const COLLAB_VERB_KEYS = [] as const;
export const COLLAB_APPLIED_ENTITIES = ['collab_message', 'collab_poll', 'collab_note'] as const;
@@ -0,0 +1,44 @@
import { COLLECTION_STATUSES } from '../../collection/collection.schema';
import { cardCountSchema, cardHexColorSchema, cardPersonSchema, cardText } from './card-parts';
import { collectionCardListSchema } from './collection-places.card';
import { z } from 'zod';
/**
* The lists a user keeps, as the chat shows them: each with its colour, size
* and people, an incoming invite with whom it came from, the lists a place is
* saved in with its status in each, and what a held change does to a list.
*/
/** What a change does to a list; `none` on an answer. */
export const COLLECTION_LIST_CHANGES = [
'none',
'add',
'update',
'remove',
'join',
'decline',
'withdraw',
'order',
] as const;
export const collectionListRowSchema = collectionCardListSchema.extend({
/** The place's status in this list (a lookup of where a place is saved). */
status: z.enum(COLLECTION_STATUSES).nullable(),
/** Who sent an incoming invite, or whom a withdrawn one was for. */
person: cardPersonSchema.nullable(),
/** An invite the user has not answered yet. */
invite: z.boolean(),
change: z.enum(COLLECTION_LIST_CHANGES),
before: z.object({ name: cardText(120), color: cardHexColorSchema.nullable() }).nullable(),
});
export type CollectionListRow = z.infer<typeof collectionListRowSchema>;
export const collectionListsCardSchema = z.object({
kind: z.literal('collectionLists'),
lists: z.array(collectionListRowSchema).max(12),
more: cardCountSchema,
/** The place a lookup asked about, as it was asked. */
place: cardText(120).nullable(),
});
export type CollectionListsCard = z.infer<typeof collectionListsCardSchema>;
@@ -0,0 +1,132 @@
import { COLLECTION_STATUSES } from '../../collection/collection.schema';
import { idSchema } from '../../common/primitives.schema';
import {
cardCountSchema,
cardFileKeySchema,
cardHexColorSchema,
cardLatSchema,
cardLngSchema,
cardPhotoKeySchema,
cardText,
} from './card-parts';
import { z } from 'zod';
/**
* Saved places of the collections as the chat shows them: a list's head with
* its colour, size and people, its places as its rows (status, labels, rating,
* whether the trip has the place already), and what a held change does to
* them. A saved place's id is its own and never a trip place's: the one link
* to the trip is `inTripPlaceId`.
*/
const statusSchema = z.enum(COLLECTION_STATUSES);
/** The fields of a saved place a change can touch, each named on the card by its label. */
export const COLLECTION_CARD_FIELDS = [
'name',
'address',
'coordinates',
'description',
'notes',
'category',
'link',
'photo',
] as const;
/** What a change does to a label of a list; `none` on an answer. */
export const COLLECTION_LABEL_CHANGES = ['none', 'add', 'rename', 'remove'] as const;
/** A list as a card names it: its colour dot, its size and how many share it. `id` null: the list a change creates. */
export const collectionCardListSchema = z.object({
id: idSchema.nullable(),
name: cardText(120),
color: cardHexColorSchema.nullable(),
placeCount: cardCountSchema.nullable(),
/** Accepted members besides the owner. */
memberCount: cardCountSchema,
/** Places per status, only where the whole list was read. */
counts: z.object({ idea: cardCountSchema, want: cardCountSchema, visited: cardCountSchema }).nullable(),
});
export type CollectionCardList = z.infer<typeof collectionCardListSchema>;
export const collectionCardLabelSchema = z.object({
id: idSchema.nullable(),
name: cardText(60),
color: cardHexColorSchema.nullable(),
/** How many places of its list carry it, where the whole list was read. */
places: cardCountSchema.nullable(),
change: z.enum(COLLECTION_LABEL_CHANGES),
before: z.object({ name: cardText(60), color: cardHexColorSchema.nullable() }).nullable(),
});
export type CollectionCardLabel = z.infer<typeof collectionCardLabelSchema>;
/** What a held change does to one saved place. */
export const collectionCardDeltaSchema = z.object({
status: z.object({ from: statusSchema.nullable(), to: statusSchema }).nullable(),
/** The user's own vote; `to: null` takes it away. */
rating: z.object({ to: z.number().int().min(1).max(5).nullable() }).nullable(),
labelsAdded: z.array(idSchema).max(10),
labelsRemoved: z.array(idSchema).max(10),
fields: z.array(z.enum(COLLECTION_CARD_FIELDS)).max(8),
movedTo: collectionCardListSchema.nullable(),
removed: z.boolean(),
});
export type CollectionCardDelta = z.infer<typeof collectionCardDeltaSchema>;
export const collectionCardPlaceSchema = z.object({
/** The saved place's own id; null before a save is applied. */
id: idSchema.nullable(),
listId: idSchema.nullable(),
name: cardText(120),
address: cardText(200).nullable(),
lat: cardLatSchema.nullable(),
lng: cardLngSchema.nullable(),
category: z
.object({ name: cardText(60), icon: cardText(40).nullable(), color: cardHexColorSchema.nullable() })
.nullable(),
status: statusSchema,
labelIds: z.array(idSchema).max(10),
rating: z.number().min(1).max(5).nullable(),
ratingCount: cardCountSchema,
/** The Google place id the photo proxy finds its picture by. */
googlePlaceId: cardPhotoKeySchema.nullable(),
osmId: cardText(40).nullable(),
/** The file name of its own uploaded photo; the client builds `/uploads/places/<key>`. */
imageKey: cardFileKeySchema.nullable(),
/** The same place in the chat's trip, by its provider id or the trip place it was saved from. */
inTripPlaceId: idSchema.nullable(),
/** The lists that hold the place already (a save's warning). */
savedIn: z.array(z.object({ listId: idSchema, name: cardText(120), status: statusSchema })).max(3),
delta: collectionCardDeltaSchema.nullable(),
});
export type CollectionCardPlace = z.infer<typeof collectionCardPlaceSchema>;
/** What an applied change of several places did, from the tool's answer. */
export const collectionCardOutcomeSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('duplicate'), name: cardText(120) }),
z.object({
type: z.literal('copied'),
copied: cardCountSchema,
skipped: cardCountSchema,
skippedNames: z.array(cardText(120)).max(5),
}),
z.object({ type: z.literal('statusSet'), updated: cardCountSchema, found: cardCountSchema }),
]);
export type CollectionCardOutcome = z.infer<typeof collectionCardOutcomeSchema>;
export const collectionPlacesCardSchema = z.object({
kind: z.literal('collectionPlaces'),
/** Null when the places sit in several lists. */
list: collectionCardListSchema.nullable(),
places: z.array(collectionCardPlaceSchema).max(8),
more: cardCountSchema,
/** Only the labels the shown places carry or the change names. */
labels: z.array(collectionCardLabelSchema).max(24),
outcome: collectionCardOutcomeSchema.nullable(),
/** A status set on a trip place in every list that holds it. */
everyList: z.boolean(),
/** A copy into a trip other than the chat's. */
otherTrip: z.boolean(),
});
export type CollectionPlacesCard = z.infer<typeof collectionPlacesCardSchema>;
@@ -0,0 +1,138 @@
import { assistantAppliedSchema } from '../assistant.schema';
import { MAX_CARD_CHARS } from './card-parts';
import { collectionListsCardSchema } from './collection-lists.card';
import { collectionPlacesCardSchema } from './collection-places.card';
import { COLLECTION_APPLIED_ENTITIES } from './collection.contract';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { describe, expect, it } from 'vitest';
const list = { id: 12, name: 'Paris food', color: '#e11d48', placeCount: 12, memberCount: 2, counts: null };
const place = {
id: 34,
listId: 12,
name: 'Septime',
address: '80 Rue de Charonne',
lat: 48.853,
lng: 2.381,
category: { name: 'Restaurant', icon: 'Utensils', color: '#f97316' },
status: 'want',
labelIds: [5],
rating: 4.5,
ratingCount: 2,
googlePlaceId: 'ChIJseptime',
osmId: null,
imageKey: 'septime.jpg',
inTripPlaceId: null,
savedIn: [],
delta: null,
};
const placesCard = {
kind: 'collectionPlaces',
list,
places: [place],
more: 0,
labels: [{ id: 5, name: 'Dinner', color: '#2563eb', places: 3, change: 'none', before: null }],
outcome: null,
everyList: false,
otherTrip: false,
};
const row = {
...list,
status: null,
person: null,
invite: false,
change: 'none',
before: null,
};
describe('collection cards', () => {
it('CARDS-COLL-001: a list with its saved places and labels reads as itself through the union', () => {
expect(trekCardSchema.parse(placesCard)).toEqual(placesCard);
expect(storedTrekCardSchema.parse(placesCard)).toEqual(placesCard);
expect(JSON.stringify(placesCard).length).toBeLessThan(MAX_CARD_CHARS);
});
it('CARDS-COLL-002: a place a change has not saved yet and the list a change creates carry no id', () => {
const pending = {
...placesCard,
list: { ...list, id: null, placeCount: 0, memberCount: 0 },
places: [{ ...place, id: null, listId: null, imageKey: null, delta: deltaOf({ removed: false }) }],
};
expect(collectionPlacesCardSchema.safeParse(pending).success).toBe(true);
});
it('CARDS-COLL-003: a photo is a stored file name, never an address or a path', () => {
const refused = ['https://example.com/a.jpg', '/uploads/places/a.jpg', '../a.jpg', 'data:image/png;base64,x'];
for (const imageKey of refused) {
const card = { ...placesCard, places: [{ ...place, imageKey }] };
expect(collectionPlacesCardSchema.safeParse(card).success, imageKey).toBe(false);
}
});
it('CARDS-COLL-004: rows, labels and names stay inside their bounds; a card past them reads as null', () => {
const nine = Array.from({ length: 9 }, (_, i) => ({ ...place, id: i + 1 }));
expect(collectionPlacesCardSchema.safeParse({ ...placesCard, places: nine }).success).toBe(false);
expect(collectionPlacesCardSchema.safeParse({ ...placesCard, list: { ...list, name: '' } }).success).toBe(false);
const tooHigh = { ...placesCard, places: [{ ...place, rating: 6 }] };
expect(collectionPlacesCardSchema.safeParse(tooHigh).success).toBe(false);
expect(storedTrekCardSchema.parse({ ...placesCard, places: nine })).toBeNull();
});
it('CARDS-COLL-005: a change names the status it leaves, the vote it casts and the fields it touches', () => {
const delta = deltaOf({ status: { from: 'idea', to: 'visited' }, rating: { to: null }, fields: ['photo'] });
const card = { ...placesCard, places: [{ ...place, delta }] };
expect(collectionPlacesCardSchema.parse(card).places[0]?.delta).toEqual(delta);
const unknownField = { ...placesCard, places: [{ ...place, delta: deltaOf({ fields: ['phone'] }) }] };
expect(collectionPlacesCardSchema.safeParse(unknownField).success).toBe(false);
});
it('CARDS-COLL-006: an applied copy, a duplicate and a status set across lists each say what happened', () => {
for (const outcome of [
{ type: 'duplicate', name: 'Septime' },
{ type: 'copied', copied: 2, skipped: 1, skippedNames: ['Le Comptoir'] },
{ type: 'statusSet', updated: 3, found: 2 },
]) {
expect(collectionPlacesCardSchema.safeParse({ ...placesCard, outcome }).success, outcome.type).toBe(true);
}
});
it('CARDS-COLL-007: the lists card holds lists, invites and a lookup of where a place is saved', () => {
const card = {
kind: 'collectionLists',
lists: [
{ ...row, status: 'visited' },
{ ...row, id: 13, invite: true, person: { id: 4, name: 'Maya', avatarKey: null }, placeCount: null },
],
more: 0,
place: 'Septime',
};
expect(trekCardSchema.parse(card)).toEqual(card);
const thirteen = Array.from({ length: 13 }, (_, i) => ({ ...row, id: i + 1 }));
expect(collectionListsCardSchema.safeParse({ ...card, lists: thirteen }).success).toBe(false);
expect(collectionListsCardSchema.safeParse({ ...card, lists: [{ ...row, change: 'rename' }] }).success).toBe(false);
});
it('CARDS-COLL-008: an applied change names a list or a saved place as what it touched', () => {
for (const entity of COLLECTION_APPLIED_ENTITIES) {
const applied = { toolCallId: 'c1', entity, ids: [12], dayId: null, undoUntil: null };
expect(assistantAppliedSchema.parse(applied).entity).toBe(entity);
}
});
});
function deltaOf(over: Record<string, unknown>) {
return {
status: null,
rating: null,
labelsAdded: [],
labelsRemoved: [],
fields: [],
movedTo: null,
removed: false,
...over,
};
}
@@ -0,0 +1,18 @@
import { collectionListsCardSchema } from './collection-lists.card';
import { collectionPlacesCardSchema } from './collection-places.card';
export * from './collection-lists.card';
export * from './collection-places.card';
/**
* What the collections bring to the assistant chat: the kinds of card they draw,
* the verbs of their change cards and what an applied change of theirs
* touches, beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else.
*/
export const COLLECTION_CARD_SCHEMAS = [collectionPlacesCardSchema, collectionListsCardSchema] as const;
/** Their changes read as the plain add, change and remove, named by each tool's own label. */
export const COLLECTION_VERB_KEYS = [] as const;
/** A list (`collection`) and a saved place of one (`collection_place`), both opened in Collections. */
export const COLLECTION_APPLIED_ENTITIES = ['collection', 'collection_place'] as const;
@@ -0,0 +1,55 @@
import { idSchema } from '../../common/primitives.schema';
import { roadtripCorridorRequestSchema } from '../../roadtrip/planning.schema';
import { MAX_TRIP_DAYS } from '../../trip/trip.schema';
import { cardLatSchema, cardLngSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* What search_roadtrip_corridor found along one day's drive, in the order
* the drive passes it: how far into the drive and how far off the road each
* hit lies, between which stops, and for a charger its sockets. A search
* that is not done yet says how much of the road it has searched.
*/
/** The hits a card lists; the rest are counted in `more`. */
export const CORRIDOR_CARD_HITS_MAX = 12;
export const corridorCardSchema = z.object({
kind: z.literal('corridor'),
dayId: idSchema.nullable(),
dayNumber: z.number().int().min(1).max(MAX_TRIP_DAYS),
category: roadtripCorridorRequestSchema.shape.category,
widthKm: z.number().positive().max(10),
hits: z
.array(
z.object({
// `<toolCallId>:<index>`, the way a found place is named.
ref: z.string().min(1).max(80),
name: cardText(80).nullable(),
brand: cardText(40).nullable(),
lat: cardLatSchema,
lng: cardLngSchema,
alongKm: z.number().min(0).max(40_000),
offKm: z.number().min(0).max(10),
// The names of the stops the hit lies between, in driving order.
between: z.tuple([cardText(80), cardText(80)]).nullable(),
sockets: z
.array(
z.object({
type: cardText(20),
kw: z.number().min(0).max(2000).nullable(),
count: z.number().int().min(0).max(99).nullable(),
}),
)
.max(4),
}),
)
.max(CORRIDOR_CARD_HITS_MAX),
more: z.number().int().min(0).max(10_000),
searched: z.object({ done: z.number().int().min(0).max(1000), total: z.number().int().min(0).max(1000) }),
// Areas that failed, came back cut short, or are still to be searched.
partial: z.boolean(),
});
export type CorridorCard = z.infer<typeof corridorCardSchema>;
export type CorridorCardHit = CorridorCard['hits'][number];
@@ -0,0 +1,30 @@
import { cardCurrencySchema, cardPersonSchema } from './card-parts';
import { z } from 'zod';
/**
* What the trip's expenses come to for each traveller, in the trip
* currency: the sum of their shares, how much of that is marked paid, and in
* how many expenses they take part. Largest share first.
*/
/** Travellers one card names; the rest are counted in `more`. */
export const COST_PER_PERSON_ROWS_MAX = 20;
export const costPerPersonCardSchema = z.object({
kind: z.literal('costPerPerson'),
currency: cardCurrencySchema,
rows: z
.array(
z.object({
person: cardPersonSchema,
share: z.number().min(-1e9).max(1e9),
paid: z.number().min(-1e9).max(1e9),
count: z.number().int().min(0).max(100_000),
}),
)
.min(1)
.max(COST_PER_PERSON_ROWS_MAX),
more: z.number().int().min(0).max(1000),
});
export type CostPerPersonCard = z.infer<typeof costPerPersonCardSchema>;
@@ -0,0 +1,55 @@
import { idSchema } from '../../common/primitives.schema';
import { MAX_TRIP_DAYS } from '../../trip/trip.schema';
import { cardLatSchema, cardLngSchema, cardPointSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* One day's route drawn straight from stop to stop, with the via points a
* change sends the drive through: the card of every change that bends a
* day's drive, and of a Google Maps route read or imported. Straight lines on
* purpose: TREK routes the road once the change is applied.
*/
/** The stops of a day a card draws. */
export const DAY_ROUTE_CARD_STOPS_MAX = 40;
/** The via points a card draws. */
export const DAY_ROUTE_CARD_VIAS_MAX = 100;
export const dayRouteCardSchema = z.object({
kind: z.literal('dayRoute'),
dayId: idSchema.nullable(),
dayNumber: z.number().int().min(1).max(MAX_TRIP_DAYS).nullable(),
stops: z
.array(
z.object({
placeId: idSchema.nullable(),
name: cardText(80),
lat: cardLatSchema,
lng: cardLngSchema,
// A stop the change adds to the day.
added: z.boolean(),
}),
)
.max(DAY_ROUTE_CARD_STOPS_MAX),
vias: z
.array(
z.object({
lat: cardLatSchema,
lng: cardLngSchema,
// The stop of the day the via follows, counting from 0.
after: z.number().int().min(0).max(500),
state: z.enum(['added', 'moved', 'removed', 'repinned']),
// Where a moved via was before.
from: cardPointSchema.nullable(),
}),
)
.max(DAY_ROUTE_CARD_VIAS_MAX),
// The stop every new via follows, and the imported track the chain was fitted to.
afterName: cardText(80).nullable(),
track: cardText(80).nullable(),
// Stops of a read Google Maps route that have no position.
unresolved: z.array(cardText(80)).max(10),
});
export type DayRouteCard = z.infer<typeof dayRouteCardSchema>;
export type DayRouteCardVia = DayRouteCard['vias'][number];
+102
View File
@@ -0,0 +1,102 @@
import { idSchema } from '../../common/primitives.schema';
import { cardDateSchema, cardMoneySchema, cardPersonSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* Expenses of the trip as the Costs page shows them: the name, the amount in
* the currency it was paid in (and in the trip currency when that differs and
* a rate is known), the day, the place it belongs to, who paid how much and
* who shares it. One card serves the expense list (`list_budget_items`) and
* every change to a single expense: the row of a change carries what it
* replaces (`before`), the people it is about (`highlight`) and what happens
* to it (`change`). Amounts are numbers with a currency code; the client
* writes them the way the Costs page does.
*/
/** Rows one expenses card lists; the rest are counted in `more`. */
export const EXPENSE_ROWS_MAX = 12;
/** Payers or shares one row names; the rest of a split are counted in `moreShares`. */
export const EXPENSE_PEOPLE_MAX = 20;
/** A signed amount: a refund is negative (#2176). */
const cardAmountSchema = z.number().min(-1e9).max(1e9);
/** How an expense is shared: evenly, in amounts of its own per person, or by nobody (planning only). */
export const expenseSplitSchema = z.enum(['equal', 'custom', 'none']);
/** What a change does to a row; an answer's rows are `none`. */
export const expenseChangeSchema = z.enum(['none', 'new', 'changed', 'willDelete']);
/** One person's part of an expense, and whether they have paid it. */
export const cardExpenseShareSchema = z.object({
person: cardPersonSchema,
amount: cardAmountSchema,
paid: z.boolean(),
});
/** Someone who paid for the expense, and how much. */
export const cardExpensePayerSchema = z.object({ person: cardPersonSchema, amount: cardAmountSchema });
/**
* The values a waiting update replaces, each null where the update leaves it
* alone: a category or a date that was empty before reads as unchanged.
*/
export const cardExpenseBeforeSchema = z.object({
name: cardText(120).nullable(),
amount: cardMoneySchema.nullable(),
category: z.string().max(60).nullable(),
date: cardDateSchema.nullable(),
split: expenseSplitSchema.nullable(),
});
export const cardExpenseSchema = z.object({
/** Null while a new expense waits for its decision. */
id: idSchema.nullable(),
name: cardText(120),
/** As stored; the client maps it to a Costs category, legacy free text included. */
category: z.string().max(60).nullable(),
/** The total in the currency it was entered in (the trip's when it names none). */
amount: cardMoneySchema,
/** The total in the trip currency, only when that differs and a rate converts it. */
tripAmount: cardMoneySchema.nullable(),
date: cardDateSchema.nullable(),
place: z.object({ id: idSchema, name: cardText(120) }).nullable(),
payers: z.array(cardExpensePayerSchema).max(EXPENSE_PEOPLE_MAX),
split: expenseSplitSchema,
shares: z.array(cardExpenseShareSchema).max(EXPENSE_PEOPLE_MAX),
/** Shares of the split past the ones named. */
moreShares: z.number().int().min(0).max(1000),
/** A change row's note; list rows leave it out. */
note: cardText(160).nullable(),
/** How many receipts are attached; never the files themselves. */
receipts: z.number().int().min(0).max(999),
before: cardExpenseBeforeSchema.nullable(),
/** The people the change is about: a paid tick set, someone joining the split. */
highlight: z.array(idSchema).max(EXPENSE_PEOPLE_MAX),
change: expenseChangeSchema,
});
export const expensesCardSchema = z.object({
kind: z.literal('expenses'),
rows: z.array(cardExpenseSchema).min(1).max(EXPENSE_ROWS_MAX),
/**
* Where in the trip's list the rows start: a later page of the list starts
* past 0, so two pages read as one list only where they meet. 0 on a change.
*/
offset: z.number().int().min(0).max(100_000),
/** Expenses of the trip the card leaves out. */
more: z.number().int().min(0).max(100_000),
/** The list's total over every expense, in the trip currency; null on a change. */
total: cardMoneySchema.nullable(),
/** Expenses the total leaves out: foreign ones no rate converts yet. */
unconverted: z.number().int().min(0).max(100_000),
});
export type ExpensesCard = z.infer<typeof expensesCardSchema>;
export type CardExpense = z.infer<typeof cardExpenseSchema>;
export type CardExpenseShare = z.infer<typeof cardExpenseShareSchema>;
export type CardExpensePayer = z.infer<typeof cardExpensePayerSchema>;
export type CardExpenseBefore = z.infer<typeof cardExpenseBeforeSchema>;
export type ExpenseSplit = z.infer<typeof expenseSplitSchema>;
export type ExpenseChange = z.infer<typeof expenseChangeSchema>;
@@ -0,0 +1,14 @@
import { journalChatCardSchema } from './journal-chat.card';
import { tripChatCardSchema } from './trip-chat.card';
export * from './journal-chat.card';
export * from './trip-chat.card';
/**
* What the chat outside any one trip (the `home` scope) brings to the
* assistant chat: the cards that offer to go on in a trip's own chat or on a
* journal's page. It has no change cards of its own; the writes it proposes
* are the atlas', the vacation planner's, the collections' and a new
* journal's. cards/index.ts spreads the kinds into the card union.
*/
export const HOME_CARD_SCHEMAS = [tripChatCardSchema, journalChatCardSchema] as const;
+209
View File
@@ -0,0 +1,209 @@
import {
ASSISTANT_CHANGE_VERB_KEYS,
assistantAppliedSchema,
assistantChangePreviewSchema,
assistantMessagePartSchema,
assistantMessagePartWriteSchema,
assistantStoredPartsSchema,
assistantTakeProposalRequestSchema,
CORE_APPLIED_ENTITIES,
CORE_VERB_KEYS,
uiStreamChunkSchema,
UI_STREAM_DONE,
} from '../assistant.schema';
import { cardFileKeySchema, cardPersonSchema, cardText, MAX_CARD_CHARS } from './card-parts';
import { assistantCardSchema, storedTrekCardSchema, trekCardSchema } from './index';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
import { z } from 'zod';
const CALL = 'call_1';
const preview = {
toolCallId: CALL,
verbKey: 'addTour',
subject: 'Lake loop',
rows: [],
dayId: null,
placeIds: [],
undoable: true,
};
/** Every kind as its package declares it today, built from its own literal. */
const KINDS = trekCardSchema.options.map((option) => option.shape.kind.value);
/**
* A kind as the packages build theirs, from the card parts, with bounds to
* cross: the read tolerance is the same for every kind, so these cases hold
* whatever fields the packages give their own.
*/
const probeSchema = z
.discriminatedUnion('kind', [
z.object({ kind: z.literal('probe'), title: cardText(8), people: z.array(cardPersonSchema).max(2) }),
])
.nullable()
.catch(null);
describe('the card union', () => {
it('CARDS-001: holds every kind once, each read as itself', () => {
expect(new Set(KINDS).size).toBe(KINDS.length);
expect(KINDS).toEqual(expect.arrayContaining(['tourRoute', 'tourList', 'packingList', 'todoList']));
for (const kind of KINDS) {
const read = storedTrekCardSchema.parse({ kind });
if (read !== null) expect(read.kind).toBe(kind);
}
});
it('CARDS-002: reads an unknown kind, a missing kind or no card at all as null', () => {
for (const card of [{ kind: 'bookPage' }, {}, null, undefined, 'tourRoute', 7]) {
expect(storedTrekCardSchema.parse(card)).toBeNull();
}
});
it('CARDS-003: reads a field past its bound as null, and drops keys a kind does not declare', () => {
expect(probeSchema.parse({ kind: 'probe', title: 'Far too long a title', people: [] })).toBeNull();
const four = [1, 2, 3, 4].map((id) => ({ id, name: `P${id}`, avatarKey: null }));
expect(probeSchema.parse({ kind: 'probe', title: 'Walk', people: four })).toBeNull();
expect(probeSchema.parse({ kind: 'probe', title: 'Walk', people: [], url: 'https://x.test' })).toEqual({
kind: 'probe',
title: 'Walk',
people: [],
});
});
it('CARDS-004: a stored file key is a file name, never a path, a URL or a way up', () => {
expect(cardFileKeySchema.safeParse('a1b2c3.jpg').success).toBe(true);
for (const key of ['../secret', 'avatars/a.jpg', 'https://x.test/a.jpg', '.hidden', 'a..b', '']) {
expect(cardFileKeySchema.safeParse(key).success).toBe(false);
}
expect(MAX_CARD_CHARS).toBe(24_000);
});
});
describe('cards in parts, chunks and previews', () => {
it('CARDS-010: a card part reads an unknown, a kindless or a broken card as null and keeps the part', () => {
for (const card of [{ kind: 'bookPage', page: 3 }, { title: 'x' }, 'nope']) {
const part = assistantMessagePartSchema.parse({ type: 'data-trek-card', data: { toolCallId: CALL, card } });
expect(part).toEqual({ type: 'data-trek-card', data: { toolCallId: CALL, card: null } });
}
});
it('CARDS-011: a card chunk reads the same way, and a known card comes through with extra keys dropped', () => {
const unknown = uiStreamChunkSchema.parse({
type: 'data-trek-card',
data: { toolCallId: CALL, card: { kind: 'x' } },
});
expect(unknown).toEqual({ type: 'data-trek-card', data: { toolCallId: CALL, card: null } });
const known = assistantCardSchema.parse({ toolCallId: CALL, card: { kind: KINDS[0], later: 1 }, extra: true });
expect(known).not.toHaveProperty('extra');
if (known.card !== null) expect(known.card).not.toHaveProperty('later');
});
it('CARDS-012: a change preview reads without a card, and with a broken one as null', () => {
expect(assistantChangePreviewSchema.parse(preview)).not.toHaveProperty('card');
expect(assistantChangePreviewSchema.parse({ ...preview, card: { kind: 'nope' } }).card).toBeNull();
expect(assistantChangePreviewSchema.parse({ ...preview, card: { title: 'no kind' } }).card).toBeNull();
});
it('CARDS-014: a verb or an entity a later build added reads as a plain update and as other', () => {
const later = { ...preview, verbKey: 'laterVerb' };
expect(assistantChangePreviewSchema.parse(later).verbKey).toBe('genericUpdate');
const receipt = { toolCallId: CALL, entity: 'later_entity', ids: [4], dayId: null, undoUntil: null };
expect(assistantAppliedSchema.parse(receipt).entity).toBe('other');
const parts = assistantStoredPartsSchema.parse([
{ type: 'data-trek-change', data: later },
{ type: 'data-trek-applied', data: receipt },
]);
expect(parts.map((part) => part.type)).toEqual(['data-trek-change', 'data-trek-applied']);
});
it('CARDS-013: a card is always under its call, whose id is 1 to 64 characters', () => {
expect(assistantCardSchema.safeParse({ toolCallId: '', card: null }).success).toBe(false);
expect(assistantCardSchema.safeParse({ toolCallId: 'x'.repeat(65), card: null }).success).toBe(false);
});
});
describe('stored parts', () => {
it('CARDS-020: drop a data part this build does not know, or one that no longer reads, and keep the rest', () => {
const parts = assistantStoredPartsSchema.parse([
{ type: 'text', text: 'Here is the walk.' },
{ type: 'data-trek-book-page', data: { page: 3 } },
{ type: 'data-trek-places', data: { toolCallId: CALL } },
{ type: 'data-trek-card', data: { toolCallId: CALL, card: { kind: 'future' } } },
{ type: 'data-trek-change', data: preview },
]);
expect(parts.map((part) => part.type)).toEqual(['text', 'data-trek-card', 'data-trek-change']);
});
it('CARDS-021: still refuse a broken part that is not a data part', () => {
expect(assistantStoredPartsSchema.safeParse([{ type: 'text', text: 5 }]).success).toBe(false);
expect(assistantStoredPartsSchema.safeParse([{ type: 'tool-call' }]).success).toBe(false);
});
it('CARDS-022: are written strictly: an unknown part is no part', () => {
expect(assistantMessagePartSchema.safeParse({ type: 'data-trek-book-page', data: {} }).success).toBe(false);
expect(assistantMessagePartWriteSchema.safeParse({ type: 'data-trek-book-page', data: {} }).success).toBe(false);
});
it('CARDS-023: are written strictly: no verb, entity or card kind this build does not know', () => {
const write = (part: unknown) => assistantMessagePartWriteSchema.safeParse(part).success;
expect(write({ type: 'data-trek-change', data: preview })).toBe(true);
expect(write({ type: 'data-trek-change', data: { ...preview, verbKey: 'laterVerb' } })).toBe(false);
expect(write({ type: 'data-trek-change', data: { ...preview, card: { kind: 'nope' } } })).toBe(false);
const receipt = { toolCallId: CALL, entity: 'later_entity', ids: [4], dayId: null, undoUntil: null };
expect(write({ type: 'data-trek-applied', data: receipt })).toBe(false);
expect(write({ type: 'data-trek-card', data: { toolCallId: CALL, card: { kind: 'nope' } } })).toBe(false);
expect(write({ type: 'data-trek-card', data: { toolCallId: CALL, card: null } })).toBe(true);
});
});
describe('the enums the packages extend', () => {
it('CARDS-030: keep every core verb and entity, the hike verbs among them', () => {
expect(ASSISTANT_CHANGE_VERB_KEYS).toEqual(expect.arrayContaining([...CORE_VERB_KEYS]));
expect(ASSISTANT_CHANGE_VERB_KEYS).toEqual(expect.arrayContaining(['addTour', 'updateTour', 'importTour']));
expect(new Set(ASSISTANT_CHANGE_VERB_KEYS).size).toBe(ASSISTANT_CHANGE_VERB_KEYS.length);
for (const entity of CORE_APPLIED_ENTITIES) {
expect(assistantAppliedSchema.shape.entity.safeParse(entity).success).toBe(true);
}
});
});
describe('assistantTakeProposalRequestSchema', () => {
it('CARDS-040: names the read whose proposal is taken, with the turn context and nothing else', () => {
const ctx = { locale: 'en', timeZone: 'Europe/Berlin' };
expect(assistantTakeProposalRequestSchema.parse({ ...ctx, toolCallId: CALL })).toEqual({
...ctx,
toolCallId: CALL,
});
expect(assistantTakeProposalRequestSchema.safeParse({ ...ctx, toolCallId: '' }).success).toBe(false);
expect(assistantTakeProposalRequestSchema.safeParse({ ...ctx, toolCallId: CALL, args: {} }).success).toBe(false);
expect(assistantTakeProposalRequestSchema.safeParse({ toolCallId: CALL }).success).toBe(false);
});
});
describe('ui-stream.cards.v1 fixture', () => {
const text = readFileSync(resolve(__dirname, '../__fixtures__/ui-stream.cards.v1.txt'), 'utf8');
const events = text
.split('\n\n')
.filter(Boolean)
.map((event) => event.slice('data: '.length));
const chunks = events.slice(0, -1).map((event) => uiStreamChunkSchema.parse(JSON.parse(event)));
it('CARDS-050: is a stream of valid chunks closed by [DONE]', () => {
expect(events.at(-1)).toBe(UI_STREAM_DONE);
expect(chunks.length).toBeGreaterThan(10);
});
it('CARDS-051: carries an applied write card after its receipt, a read card after its answer, a held one in its preview', () => {
const types = chunks.map((chunk) => chunk.type);
const cards = chunks.flatMap((chunk) => (chunk.type === 'data-trek-card' ? [chunk.data.toolCallId] : []));
const applied = chunks.find((chunk) => chunk.type === 'data-trek-applied');
const read = chunks.find((chunk) => chunk.type === 'tool-input-start' && chunk.toolName === 'list_tours');
expect(applied?.type === 'data-trek-applied' && applied.data.toolCallId).toBe(cards[0]);
expect(read?.type === 'tool-input-start' && read.toolCallId).toBe(cards[1]);
expect(types.indexOf('data-trek-applied')).toBeLessThan(types.indexOf('data-trek-card'));
const change = chunks.find((chunk) => chunk.type === 'data-trek-change');
expect(change?.type === 'data-trek-change' && 'card' in change.data).toBe(true);
});
});
+86
View File
@@ -0,0 +1,86 @@
import { ATLAS_CARD_SCHEMAS } from './atlas.contract';
import { BOOK_DESIGN_CARD_SCHEMAS } from './book-design.contract';
import { BOOK_CARD_SCHEMAS } from './book.contract';
import { BOOKING_CARD_SCHEMAS } from './booking.contract';
import { BUDGET_CARD_SCHEMAS } from './budget.contract';
import { COLLAB_CARD_SCHEMAS } from './collab.contract';
import { COLLECTION_CARD_SCHEMAS } from './collection.contract';
import { HOME_CARD_SCHEMAS } from './home.contract';
import { JOURNEY_CARD_SCHEMAS } from './journey.contract';
import { PACKING_CARD_SCHEMAS } from './packing.contract';
import { ROADTRIP_CARD_SCHEMAS } from './roadtrip.contract';
import { TOUR_CARD_SCHEMAS } from './tour.contract';
import { VACAY_CARD_SCHEMAS } from './vacay.contract';
import { z } from 'zod';
export * from './card-parts';
export * from './atlas.contract';
export * from './book.contract';
export * from './book-design.contract';
export * from './booking.contract';
export * from './budget.contract';
export * from './collab.contract';
export * from './collection.contract';
export * from './home.contract';
export * from './journey.contract';
export * from './packing.contract';
export * from './roadtrip.contract';
export * from './tour.contract';
export * from './vacay.contract';
/**
* The cards of the assistant chat: one per tool call, drawn beside an answer
* (a read's result) or inside a change card (what a held write will do, and
* what it did once applied). Each part of TREK owns its kinds in its
* `<pkg>.contract.ts`; the server builds every card from the tool's own
* answer and checks it against this union before it is sent.
*/
const trekCardUnion = z.discriminatedUnion('kind', [
...TOUR_CARD_SCHEMAS,
...ROADTRIP_CARD_SCHEMAS,
...BUDGET_CARD_SCHEMAS,
...BOOKING_CARD_SCHEMAS,
...COLLAB_CARD_SCHEMAS,
...COLLECTION_CARD_SCHEMAS,
...ATLAS_CARD_SCHEMAS,
...VACAY_CARD_SCHEMAS,
...JOURNEY_CARD_SCHEMAS,
...PACKING_CARD_SCHEMAS,
...BOOK_CARD_SCHEMAS,
...BOOK_DESIGN_CARD_SCHEMAS,
...HOME_CARD_SCHEMAS,
]);
type TrekCardUnion = typeof trekCardUnion;
/**
* The card union under a name of its own: the message, part and thread
* schemas that hold cards then refer to it instead of spelling out every kind
* again, which made the server's typecheck run out of memory. The one member
* keeps the interface from being empty; it is the union's own.
*/
export interface TrekCardSchema extends TrekCardUnion {
readonly options: TrekCardUnion['options'];
}
export const trekCardSchema: TrekCardSchema = trekCardUnion;
export type TrekCard = z.infer<typeof trekCardSchema>;
export type TrekCardKind = TrekCard['kind'];
export type TrekCardOf<K extends TrekCardKind> = Extract<TrekCard, { kind: K }>;
/**
* How a stored or streamed card is read. A kind this build does not know, a
* missing field or a value past a bound reads as null and the card is left
* out, never the message around it: a newer server may write kinds an older
* client or a rolled back server has not heard of (verified with zod 4.6.5).
* Keys a kind does not declare are dropped, so a field added later reads too.
*/
export const storedTrekCardSchema = trekCardSchema.nullable().catch(null);
/** The card of one tool call, under that call's id: a read's, or a held or applied write's. */
export const assistantCardSchema = z.object({
toolCallId: z.string().min(1).max(64),
card: storedTrekCardSchema,
});
export type AssistantCard = z.infer<typeof assistantCardSchema>;
/** The same as the server writes it: a card the union refuses is a bug in its builder, never a silent null. */
export const assistantCardWriteSchema = assistantCardSchema.extend({ card: trekCardSchema.nullable() });
@@ -0,0 +1,46 @@
import { storedTrekCardSchema, trekCardSchema } from './index';
import { journalChatCardSchema } from './journal-chat.card';
import { describe, expect, it } from 'vitest';
const card = {
kind: 'journalChat',
journey: {
id: 12,
title: 'Japan 2026',
subtitle: 'Two weeks in autumn',
startDate: '2026-11-02',
endDate: '2026-11-16',
entryCount: 4,
photoCount: 120,
},
question: 'Make a new entry for Berlin Hauptbahnhof',
} as const;
describe('journalChatCardSchema', () => {
it('JOURNALCHAT-001: is part of the card union and reads as itself', () => {
expect(trekCardSchema.parse(card)).toEqual(card);
expect(storedTrekCardSchema.parse(card)).toEqual(card);
});
it('JOURNALCHAT-002: takes a journal without dates, a subtitle or a question', () => {
const bare = {
kind: 'journalChat',
journey: { id: 3, title: 'Notes', subtitle: null, startDate: null, endDate: null, entryCount: 0, photoCount: 0 },
question: null,
};
expect(journalChatCardSchema.parse(bare)).toEqual(bare);
});
it('JOURNALCHAT-003: refuses a bad id, a bad date, an empty title, a negative count or an overlong question', () => {
expect(journalChatCardSchema.safeParse({ ...card, journey: { ...card.journey, id: 0 } }).success).toBe(false);
expect(
journalChatCardSchema.safeParse({ ...card, journey: { ...card.journey, startDate: '2.11.2026' } }).success,
).toBe(false);
expect(journalChatCardSchema.safeParse({ ...card, journey: { ...card.journey, title: '' } }).success).toBe(false);
expect(journalChatCardSchema.safeParse({ ...card, journey: { ...card.journey, entryCount: -1 } }).success).toBe(
false,
);
expect(journalChatCardSchema.safeParse({ ...card, question: 'x'.repeat(501) }).success).toBe(false);
});
});
@@ -0,0 +1,28 @@
import { idSchema } from '../../common/primitives.schema';
import { cardCountSchema, cardDateSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* A journal the chat outside any one trip offers to go on with on the
* journal's own page: the conversation there knows the journal's entries and
* photos and can change them, which the chat on the dashboard does not. The
* question is what the user asked about the journal, handed over so it waits
* there ready to send.
*/
export const journalChatCardSchema = z.object({
kind: z.literal('journalChat'),
journey: z.object({
id: idSchema,
title: cardText(200),
subtitle: cardText(300).nullable(),
/** The days of the trips it holds, when it holds any. */
startDate: cardDateSchema.nullable(),
endDate: cardDateSchema.nullable(),
entryCount: cardCountSchema,
photoCount: cardCountSchema,
}),
/** The question to ask on the journal's page, in the user's words; null when there is none to hand over. */
question: cardText(500).nullable(),
});
export type JournalChatCard = z.infer<typeof journalChatCardSchema>;
@@ -0,0 +1,126 @@
import {
ASSISTANT_CHANGE_VERB_KEYS,
assistantAppliedSchema,
assistantChangePreviewSchema,
assistantMessagePartSchema,
uiStreamChunkSchema,
} from '../assistant.schema';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { JOURNEY_CARD_LIMITS, journeyEntriesCardSchema, type JourneyEntryLook } from './journey-entries.card';
import { describe, expect, it } from 'vitest';
// JRNCARD-001 to JRNCARD-006
function look(over: Partial<JourneyEntryLook> = {}): JourneyEntryLook {
return {
entryId: 12,
type: 'entry',
title: 'Sunset at the Spree',
date: '2026-10-21',
time: '14:30',
place: 'Berlin',
point: { lat: 52.52, lng: 13.405 },
countryCode: 'DE',
story: 'The light over the river was unreal.',
mood: 'amazing',
weather: 'sunny',
photoId: 7,
video: false,
photoCount: 4,
visibility: 'public',
draft: false,
fromTripPlace: false,
dayIndex: 0,
...over,
};
}
function card(entries: JourneyEntryLook[], over: Record<string, unknown> = {}) {
return {
kind: 'journeyEntries',
journeyId: 3,
journalTitle: 'Berlin 2026',
tripJournal: true,
change: 'none',
entries,
more: 0,
...over,
};
}
describe('the journal entries card', () => {
it('JRNCARD-001: reads a full card through the union, as itself', () => {
const parsed = trekCardSchema.parse(card([look(), look({ entryId: 13, photoId: null, dayIndex: 1 })]));
expect(parsed.kind).toBe('journeyEntries');
expect(journeyEntriesCardSchema.parse(parsed).entries).toHaveLength(2);
});
it('JRNCARD-002: holds one to eight entries, a pending entry without an id among them', () => {
expect(journeyEntriesCardSchema.safeParse(card([])).success).toBe(false);
const eight = Array.from({ length: JOURNEY_CARD_LIMITS.entries }, (_, i) => look({ entryId: i + 1 }));
expect(journeyEntriesCardSchema.safeParse(card(eight)).success).toBe(true);
expect(journeyEntriesCardSchema.safeParse(card([...eight, look({ entryId: 99 })])).success).toBe(false);
expect(journeyEntriesCardSchema.safeParse(card([look({ entryId: null })], { change: 'new' })).success).toBe(true);
});
it('JRNCARD-003: a story past its bound, a bad date, time or country reads as no card at all', () => {
const bad = [
look({ story: 'x'.repeat(JOURNEY_CARD_LIMITS.story + 1) }),
look({ date: '21.10.2026' }),
look({ time: '9:05' }),
look({ countryCode: 'de' }),
look({ mood: 'Very Happy' }),
look({ point: { lat: 91, lng: 0 } }),
look({ title: '' }),
];
for (const entry of bad) {
expect(journeyEntriesCardSchema.safeParse(card([entry])).success).toBe(false);
expect(storedTrekCardSchema.parse(card([entry]))).toBeNull();
}
});
it('JRNCARD-004: carries no address of a picture, only the photo id', () => {
const parsed = journeyEntriesCardSchema.parse(
card([{ ...look(), thumbnail_path: '/uploads/x.jpg', file_path: 'secret' } as JourneyEntryLook]),
);
const text = JSON.stringify(parsed);
expect(text).not.toContain('thumbnail_path');
expect(text).not.toContain('/uploads/');
expect(parsed.entries[0]?.photoId).toBe(7);
});
it('JRNCARD-005: rides a data-trek-card part and chunk, and a change preview', () => {
const data = { toolCallId: 'call_1', card: card([look()]) };
const part = assistantMessagePartSchema.parse({ type: 'data-trek-card', data });
expect(part.type === 'data-trek-card' && part.data.card?.kind).toBe('journeyEntries');
const chunk = uiStreamChunkSchema.parse({ type: 'data-trek-card', data });
expect(chunk.type === 'data-trek-card' && chunk.data.card?.kind).toBe('journeyEntries');
const preview = assistantChangePreviewSchema.parse({
toolCallId: 'call_1',
verbKey: 'addJournalEntry',
subject: 'Sunset at the Spree',
rows: [],
dayId: null,
placeIds: [],
undoable: true,
card: card([look({ entryId: null })], { change: 'new' }),
});
expect(preview.verbKey).toBe('addJournalEntry');
expect(preview.card?.kind).toBe('journeyEntries');
});
it('JRNCARD-006: names its verbs and its entity in the shared enums', () => {
expect(ASSISTANT_CHANGE_VERB_KEYS).toEqual(
expect.arrayContaining(['addJournalEntry', 'updateJournalEntry', 'removeJournalEntry']),
);
const applied = assistantAppliedSchema.parse({
toolCallId: 'call_1',
entity: 'journey_entry',
ids: [12],
dayId: null,
undoUntil: null,
});
expect(applied.entity).toBe('journey_entry');
});
});
@@ -0,0 +1,97 @@
import { idSchema } from '../../common/primitives.schema';
import { journeyEntryTypeSchema, journeyEntryVisibilitySchema } from '../../journey/journey.schema';
import { cardClockSchema, cardCountSchema, cardDateSchema, cardLatSchema, cardLngSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* Entries of one travel journal as the assistant chat shows them: what a
* read of the journal found (one entry or several), what a held change will
* write, and what it wrote once applied. One kind for all three, so the
* answer, the change row and the receipt read one shape.
*/
/** How much of a journal a card carries; the server clips to the same numbers. */
export const JOURNEY_CARD_LIMITS = {
entries: 8,
title: 100,
place: 80,
story: 240,
journal: 80,
weather: 40,
tags: 6,
tag: 40,
points: 3,
point: 80,
} as const;
/** The verdict on a place as a card shows it: the first points on each side, and how many each side holds. */
export const journeyEntryVerdictSchema = z.object({
pros: z.array(cardText(JOURNEY_CARD_LIMITS.point)).max(JOURNEY_CARD_LIMITS.points),
cons: z.array(cardText(JOURNEY_CARD_LIMITS.point)).max(JOURNEY_CARD_LIMITS.points),
prosCount: cardCountSchema,
consCount: cardCountSchema,
});
export type JourneyEntryVerdict = z.infer<typeof journeyEntryVerdictSchema>;
/**
* One entry as a card shows it. Its texts are plain and on one line (the story
* without its markdown, cut to its start), masked like a provider answer when
* they come from a result; a photo travels as its id, never as a path.
*/
export const journeyEntryLookSchema = z.object({
/** Null for an entry a held change has not written yet. */
entryId: idSchema.nullable(),
type: journeyEntryTypeSchema,
title: cardText(JOURNEY_CARD_LIMITS.title).nullable(),
date: cardDateSchema,
time: cardClockSchema.nullable(),
/** The place as the entry names it; the client shortens it as the journal does. */
place: cardText(JOURNEY_CARD_LIMITS.place).nullable(),
point: z.object({ lat: cardLatSchema, lng: cardLngSchema }).nullable(),
countryCode: z
.string()
.regex(/^[A-Z]{2}$/)
.nullable(),
story: cardText(JOURNEY_CARD_LIMITS.story).nullable(),
/** A mood id; the client draws the ones it knows and leaves the rest out. */
mood: z
.string()
.regex(/^[a-z]{1,20}$/)
.nullable(),
/** A weather id the journal knows, or the words the traveller wrote. */
weather: cardText(JOURNEY_CARD_LIMITS.weather).nullable(),
/** The TREK photo the entry opens with (its thumbnail), the first one that has a picture. */
photoId: idSchema.nullable(),
/** That photo is the poster of a clip. */
video: z.boolean(),
photoCount: cardCountSchema,
visibility: journeyEntryVisibilitySchema,
draft: z.boolean(),
/** Made from a place of a trip: deleting it turns it back into a suggestion. */
fromTripPlace: z.boolean(),
/** Which day of the journal it falls on, counted from 0, for the day's colour; null when unknown. */
dayIndex: z.number().int().min(0).max(9_999).nullable(),
/** Its first tags. Optional, like the two below: cards stored before they existed leave them out. */
tags: z.array(cardText(JOURNEY_CARD_LIMITS.tag)).max(JOURNEY_CARD_LIMITS.tags).optional(),
verdict: journeyEntryVerdictSchema.nullable().optional(),
/** In a new order of the journal's entries, this one changed its place. */
moved: z.boolean().optional(),
});
export type JourneyEntryLook = z.infer<typeof journeyEntryLookSchema>;
/** What a change card's entries go through: nothing on an answer, else what the change does to them. */
export const JOURNEY_CARD_CHANGES = ['none', 'new', 'changed', 'willDelete', 'reordered'] as const;
export const journeyEntriesCardSchema = z.object({
kind: z.literal('journeyEntries'),
journeyId: idSchema,
journalTitle: cardText(JOURNEY_CARD_LIMITS.journal).nullable(),
/** The journal is the one the open trip shows in its Journal tab, as read when the card was made. */
tripJournal: z.boolean(),
change: z.enum(JOURNEY_CARD_CHANGES),
entries: z.array(journeyEntryLookSchema).min(1).max(JOURNEY_CARD_LIMITS.entries),
/** Entries the read found that the card does not carry. */
more: cardCountSchema,
});
export type JourneyEntriesCard = z.infer<typeof journeyEntriesCardSchema>;
@@ -0,0 +1,39 @@
import { storedTrekCardSchema, trekCardSchema } from './index';
import { JOURNEY_HEADER_LIMITS, journeyHeaderCardSchema } from './journey-header.card';
import { describe, expect, it } from 'vitest';
const card = {
kind: 'journeyHeader',
journeyId: 12,
title: 'Japan 2026',
subtitle: null,
change: 'changed',
trips: [{ id: 5, title: 'Tokyo days', startDate: '2026-11-02', endDate: null, change: 'link' }],
entries: 3,
photos: null,
suggestions: 9,
} as const;
describe('journeyHeaderCardSchema', () => {
it('JOURNEYHEADER-001: is part of the card union and reads as itself', () => {
expect(trekCardSchema.parse(card)).toEqual(card);
expect(storedTrekCardSchema.parse(card)).toEqual(card);
});
it('JOURNEYHEADER-002: takes a new journal without an id, and a trip the user trips do not list', () => {
const fresh = { ...card, journeyId: null, change: 'new', trips: [{ ...card.trips[0], id: null }] };
expect(journeyHeaderCardSchema.parse(fresh)).toEqual(fresh);
});
it('JOURNEYHEADER-003: refuses an unknown change, too many trips, an empty title or a negative count', () => {
expect(journeyHeaderCardSchema.safeParse({ ...card, change: 'renamed' }).success).toBe(false);
const many = Array.from({ length: JOURNEY_HEADER_LIMITS.trips + 1 }, () => card.trips[0]);
expect(journeyHeaderCardSchema.safeParse({ ...card, trips: many }).success).toBe(false);
expect(journeyHeaderCardSchema.safeParse({ ...card, title: '' }).success).toBe(false);
expect(journeyHeaderCardSchema.safeParse({ ...card, entries: -1 }).success).toBe(false);
expect(journeyHeaderCardSchema.safeParse({ ...card, trips: [{ ...card.trips[0], change: 'moved' }] }).success).toBe(
false,
);
});
});
@@ -0,0 +1,47 @@
import { idSchema } from '../../common/primitives.schema';
import { cardCountSchema, cardDateSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* A journal itself as the assistant chat shows a change of it: a new one,
* its settings changed, a trip linked or unlinked, its suggestions brought
* back, or the whole journal deleted. The rows of the change card say what
* changes field by field; this card is the journal under them, its trips and
* what a change takes with it.
*/
/** How much of a journal the card carries; the server clips to the same numbers. */
export const JOURNEY_HEADER_LIMITS = { title: 200, subtitle: 300, trips: 12, tripTitle: 120 } as const;
/** What the change does to the journal: makes it, changes it, deletes it. */
export const JOURNEY_HEADER_CHANGES = ['new', 'changed', 'willDelete'] as const;
/** What the change does to one of its trips. */
export const JOURNEY_HEADER_TRIP_CHANGES = ['kept', 'link', 'unlink'] as const;
export const journeyHeaderTripSchema = z.object({
/** Null for a trip a new journal names that the user's trips do not list. */
id: idSchema.nullable(),
title: cardText(JOURNEY_HEADER_LIMITS.tripTitle),
startDate: cardDateSchema.nullable(),
endDate: cardDateSchema.nullable(),
change: z.enum(JOURNEY_HEADER_TRIP_CHANGES),
});
export type JourneyHeaderTrip = z.infer<typeof journeyHeaderTripSchema>;
export const journeyHeaderCardSchema = z.object({
kind: z.literal('journeyHeader'),
/** Null for a journal a held change has not made yet. */
journeyId: idSchema.nullable(),
title: cardText(JOURNEY_HEADER_LIMITS.title),
subtitle: cardText(JOURNEY_HEADER_LIMITS.subtitle).nullable(),
change: z.enum(JOURNEY_HEADER_CHANGES),
trips: z.array(journeyHeaderTripSchema).max(JOURNEY_HEADER_LIMITS.trips),
/** What the journal holds: what a deletion takes with it, what an unlinked trip leaves behind. */
entries: cardCountSchema.nullable(),
photos: cardCountSchema.nullable(),
/** Places of the linked trips that come in as suggestions; null when unknown. */
suggestions: cardCountSchema.nullable(),
});
export type JourneyHeaderCard = z.infer<typeof journeyHeaderCardSchema>;
@@ -0,0 +1,57 @@
import { idSchema } from '../../common/primitives.schema';
import { cardCountSchema, cardDateSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* Photos of a journal as the assistant chat shows a change of them: one put
* on an entry or taken off it, photos moved from one entry to another, an
* entry's photos in a new order (the first is its cover), a caption changed,
* photos added from a library. A photo travels as its TREK photo id, which
* the client turns into TREK's own thumbnail address.
*/
/** How much a card carries; the server clips to the same numbers. */
export const JOURNEY_PHOTOS_LIMITS = { photos: 8, caption: 160, title: 100 } as const;
export const JOURNEY_PHOTOS_MODES = ['link', 'unlink', 'move', 'order', 'caption', 'add'] as const;
/** An entry the photos leave or reach. */
export const journeyPhotosEntrySchema = z.object({
entryId: idSchema.nullable(),
title: cardText(JOURNEY_PHOTOS_LIMITS.title).nullable(),
date: cardDateSchema.nullable(),
});
export type JourneyPhotosEntry = z.infer<typeof journeyPhotosEntrySchema>;
export const journeyPhotoLookSchema = z.object({
/** The TREK photo, for its thumbnail. */
photoId: idSchema,
video: z.boolean(),
caption: cardText(JOURNEY_PHOTOS_LIMITS.caption).nullable(),
});
export type JourneyPhotoLook = z.infer<typeof journeyPhotoLookSchema>;
export const journeyPhotosCardSchema = z.object({
kind: z.literal('journeyPhotos'),
journeyId: idSchema,
mode: z.enum(JOURNEY_PHOTOS_MODES),
/** The entry the photos leave (a move, an unlink). */
from: journeyPhotosEntrySchema.nullable(),
/** The entry the photos reach or whose photos change (a link, a move, a new order, an add). */
to: journeyPhotosEntrySchema.nullable(),
/** In the order the change leaves them; for a new order, the first is the entry's cover. */
photos: z.array(journeyPhotoLookSchema).max(JOURNEY_PHOTOS_LIMITS.photos),
/** Photos the change concerns that the card does not carry. */
more: cardCountSchema,
/** A move that leaves the photos on the first entry as well. */
kept: z.boolean(),
/** A caption change, old to new; null on every other change. */
caption: z
.object({
before: cardText(JOURNEY_PHOTOS_LIMITS.caption).nullable(),
after: cardText(JOURNEY_PHOTOS_LIMITS.caption).nullable(),
})
.nullable(),
});
export type JourneyPhotosCard = z.infer<typeof journeyPhotosCardSchema>;
@@ -0,0 +1,49 @@
import { journeyEntriesCardSchema } from './journey-entries.card';
import { journeyHeaderCardSchema } from './journey-header.card';
import { journeyPhotosCardSchema } from './journey-photos.card';
export * from './journey-entries.card';
export * from './journey-header.card';
export * from './journey-photos.card';
/**
* What the travel journal brings to the assistant chat: the kinds of card it draws,
* the verbs of its change cards and what an applied change of its
* touches, beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else.
*/
export const JOURNEY_CARD_SCHEMAS = [
journeyEntriesCardSchema,
journeyHeaderCardSchema,
journeyPhotosCardSchema,
] as const;
/**
* An entry written, changed or deleted, the entries put in a new order; a journal started, renamed, given
* another status or other settings, deleted; a trip linked or unlinked; its
* suggestions brought back; the user's own view of it changed; a photo put on
* an entry, taken off, moved, put in order, captioned or added.
*/
export const JOURNEY_VERB_KEYS = [
'addJournalEntry',
'updateJournalEntry',
'removeJournalEntry',
'reorderJournalEntries',
'createJournal',
'renameJournal',
'setJournalStatus',
'updateJournalSettings',
'deleteJournal',
'linkJournalTrip',
'unlinkJournalTrip',
'restoreJournalSuggestions',
'setJournalPreferences',
'linkJournalPhoto',
'unlinkJournalPhoto',
'moveJournalPhotos',
'orderJournalPhotos',
'captionJournalPhoto',
'addJournalPhotos',
] as const;
/** An entry of a journal, or the journal itself; the receipt opens it there. */
export const JOURNEY_APPLIED_ENTITIES = ['journey_entry', 'journey'] as const;
@@ -0,0 +1,121 @@
import { idSchema } from '../../common/primitives.schema';
import { cardHexColorSchema, cardPersonSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* A packing list in the assistant chat: the trip's, the part a tour points
* at, or a template about to be added. It is grouped the way the packing
* list shows it, by category or by bag; a bag overview is the same card with
* the bags as groups and no item rows. On a change card the rows carry what
* the change does to them (`change`, and the old value of every field it
* touches), on an answer `change` is `none`.
*/
const gramsSchema = z.number().int().min(0).max(1_000_000);
const checklistCountSchema = z.number().int().min(0).max(5_000);
/**
* The index of a category in the order its list first shows it; the client
* maps it onto the list's own colours, so the chat's dot matches the panel's.
* Null where the card does not know the category yet (the hash colour then).
*/
export const checklistColorSlotSchema = z.number().int().min(0).max(999);
/** The value a field held before a change, as stored (an ISO date, a colour, grams, a name). */
export const checklistBeforeSchema = z.string().max(120).nullable();
export const PACKING_ROW_CHANGES = ['none', 'add', 'update', 'check', 'uncheck', 'remove', 'share'] as const;
export const PACKING_ITEM_FIELDS = ['name', 'category', 'quantity', 'packed', 'weight', 'bag', 'tier'] as const;
export const PACKING_BAG_FIELDS = ['name', 'color', 'limit', 'owner'] as const;
export const PACKING_TIERS = ['common', 'personal', 'shared'] as const;
/** A bag on the list (`id:12`) or one a pending import creates (`new:0`). */
export const packingBagKeySchema = z.string().regex(/^(id:\d{1,12}|new:\d{1,2})$/);
export const packingCardBagSchema = z.object({
key: packingBagKeySchema,
id: idSchema.nullable(),
name: cardText(100),
/** Null while a create waits for the server to pick it. */
color: cardHexColorSchema.nullable(),
/** What the bag weighs with every member's items in it (#2191). */
weightGrams: gramsSchema.nullable(),
limitGrams: gramsSchema.nullable(),
owner: cardPersonSchema.nullable(),
members: z.array(cardPersonSchema).max(6),
membersRemoved: z.array(cardPersonSchema).max(6),
change: z.enum(['none', 'add', 'update', 'remove', 'members']),
changed: z.array(z.object({ field: z.enum(PACKING_BAG_FIELDS), before: checklistBeforeSchema })).max(4),
/** For a bag about to be deleted: the items that land in "Unassigned". */
movesOut: checklistCountSchema,
});
export type PackingCardBag = z.infer<typeof packingCardBagSchema>;
export const packingCardItemSchema = z.object({
/** Null while a create waits. */
id: idSchema.nullable(),
name: cardText(200),
quantity: z.number().int().min(1).max(999),
/** All of it once ticked, the partial count before that (#2296). */
packed: z.number().int().min(0).max(999),
checked: z.boolean(),
/** Unit weight times quantity; null where none is recorded. */
weightGrams: gramsSchema.nullable(),
/** One of the card's `bags`; null for an item in no bag. */
bagKey: packingBagKeySchema.nullable(),
tier: z.enum(PACKING_TIERS),
sharedWith: z.array(cardPersonSchema).max(4),
change: z.enum(PACKING_ROW_CHANGES),
changed: z.array(z.object({ field: z.enum(PACKING_ITEM_FIELDS), before: checklistBeforeSchema })).max(7),
});
export type PackingCardItem = z.infer<typeof packingCardItemSchema>;
export const packingCardGroupSchema = z.object({
key: z.discriminatedUnion('by', [
z.object({
by: z.literal('category'),
/** Null: the items without a category, which the list files under its default one. */
name: cardText(100).nullable(),
slot: checklistColorSlotSchema.nullable(),
}),
/** Null: the pile in no bag. */
z.object({ by: z.literal('bag'), bagKey: packingBagKeySchema.nullable() }),
]),
/** Who looks after the category. */
assignees: z.array(cardPersonSchema).max(6),
/** Who a change of the category's people takes off it. */
assigneesRemoved: z.array(cardPersonSchema).max(6),
items: z.array(packingCardItemSchema).max(40),
/** The group's items on the list, shown or not. */
count: checklistCountSchema,
packed: checklistCountSchema,
});
export type PackingCardGroup = z.infer<typeof packingCardGroupSchema>;
export const packingListCardSchema = z.object({
kind: z.literal('packingList'),
source: z.discriminatedUnion('type', [
z.object({ type: z.literal('trip') }),
z.object({
type: z.literal('tour'),
placeId: idSchema,
name: cardText(200),
category: cardText(200).nullable(),
}),
z.object({
type: z.literal('template'),
templateId: idSchema,
name: cardText(100),
itemCount: checklistCountSchema,
}),
]),
groupBy: z.enum(['category', 'bag']),
/** How much of the list is packed; answers only. */
progress: z.object({ packed: checklistCountSchema, total: checklistCountSchema }).nullable(),
bags: z.array(packingCardBagSchema).max(20),
groups: z.array(packingCardGroupSchema).max(12),
/** Groups past the twelve shown. */
moreGroups: checklistCountSchema,
});
export type PackingListCard = z.infer<typeof packingListCardSchema>;
@@ -0,0 +1,161 @@
import { packingListItemsRequestSchema } from '../../packing/packing.schema';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { packingListCardSchema } from './packing-list.card';
import { todoListCardSchema } from './todo-list.card';
import { describe, expect, it } from 'vitest';
/**
* PKCARD-001 to PKCARD-008: the packing and to-do cards of the assistant
* chat. Both kinds join the card union; every field is bounded; a bag is
* named by a key, a colour only as `#rrggbb`, a person never with an address,
* a date only as `YYYY-MM-DD`; and the list read they come from takes its
* filters in a closed shape.
*/
const ANA = { id: 2, name: 'Ana', avatarKey: 'ana.png' };
const item = (over: Record<string, unknown> = {}) => ({
id: 7,
name: 'Rain jacket',
quantity: 1,
packed: 0,
checked: false,
weightGrams: 480,
bagKey: 'id:3',
tier: 'common',
sharedWith: [],
change: 'none',
changed: [],
...over,
});
const bag = (over: Record<string, unknown> = {}) => ({
key: 'id:3',
id: 3,
name: 'Carry-on',
color: '#6366f1',
weightGrams: 6200,
limitGrams: 8000,
owner: ANA,
members: [ANA],
membersRemoved: [],
change: 'none',
changed: [],
movesOut: 0,
...over,
});
const packing = (over: Record<string, unknown> = {}) => ({
kind: 'packingList',
source: { type: 'trip' },
groupBy: 'category',
progress: { packed: 1, total: 3 },
bags: [bag()],
groups: [
{
key: { by: 'category', name: 'Clothes', slot: 0 },
assignees: [ANA],
assigneesRemoved: [],
items: [item()],
count: 3,
packed: 1,
},
],
moreGroups: 0,
...over,
});
/** The packing card with one row in its one group. */
const withRow = (row: unknown) => packing({ groups: [{ ...packing().groups[0], items: [row] }] });
const todo = (over: Record<string, unknown> = {}) => ({
id: 9,
name: 'Book the ferry',
note: 'Check the early sailing first',
checked: false,
dueDate: '2026-06-12',
dueDayId: 31,
priority: 1,
assignee: ANA,
change: 'none',
changed: [],
...over,
});
const todos = (items: unknown[] = [todo()]) => ({
kind: 'todoList',
progress: { open: 2, done: 1, overdue: 1 },
groups: [{ category: 'Bookings', slot: 0, assignees: [], assigneesRemoved: [], items, count: 2, open: 2 }],
moreGroups: 0,
});
describe('packing and to-do cards', () => {
it('PKCARD-001: a packing list, a bag overview, a tour and a template source all read as cards of the union', () => {
expect(trekCardSchema.parse(packing()).kind).toBe('packingList');
const bags = packing({ groupBy: 'bag', progress: null, groups: [] });
expect(packingListCardSchema.safeParse(bags).success).toBe(true);
const tour = { type: 'tour', placeId: 11, name: 'Ridge', category: 'Hiking gear' };
expect(packingListCardSchema.safeParse(packing({ source: tour })).success).toBe(true);
const template = { type: 'template', templateId: 4, name: 'Beach week', itemCount: 24 };
expect(packingListCardSchema.safeParse(packing({ source: template, groups: [] })).success).toBe(true);
const pile = { key: { by: 'bag', bagKey: null }, assignees: [], assigneesRemoved: [], items: [], count: 2 };
expect(packingListCardSchema.safeParse(packing({ groups: [{ ...pile, packed: 0 }] })).success).toBe(true);
});
it('PKCARD-002: bags are named by key, a waiting one as new:N; any other key is refused', () => {
const waiting = bag({ key: 'new:0', id: null, color: null });
expect(packingListCardSchema.safeParse(packing({ bags: [waiting] })).success).toBe(true);
for (const key of ['3', 'id:', 'new:123', 'bag:3']) {
expect(packingListCardSchema.safeParse(packing({ bags: [bag({ key })] })).success, key).toBe(false);
}
});
it('PKCARD-003: a colour is only #rrggbb and a person never carries an address', () => {
expect(packingListCardSchema.safeParse(packing({ bags: [bag({ color: '#abc' })] })).success).toBe(false);
const url = { ...ANA, avatarKey: 'https://example.com/a.png' };
expect(packingListCardSchema.safeParse(packing({ bags: [bag({ owner: url })] })).success).toBe(false);
expect(todoListCardSchema.safeParse(todos([todo({ assignee: url })])).success).toBe(false);
});
it('PKCARD-004: counts stay in bounds: no more than 999 packed, no item without a name', () => {
for (const row of [item({ packed: 1000 }), item({ name: '' }), item({ quantity: 0 })]) {
expect(packingListCardSchema.safeParse(withRow(row)).success).toBe(false);
}
const many = packing({ groups: Array(13).fill(packing().groups[0]) });
expect(packingListCardSchema.safeParse(many).success).toBe(false);
});
it('PKCARD-005: a change row says what it does and what each touched field held before', () => {
const changed = item({ change: 'update', changed: [{ field: 'bag', before: 'Daypack' }] });
expect(packingListCardSchema.safeParse(withRow(changed)).success).toBe(true);
const odd = item({ change: 'update', changed: [{ field: 'colour', before: null }] });
expect(packingListCardSchema.safeParse(withRow(odd)).success).toBe(false);
});
it('PKCARD-006: a to-do list reads as a card, a tick keeping whether it was done; a local date is refused', () => {
expect(trekCardSchema.parse(todos()).kind).toBe('todoList');
expect(todoListCardSchema.safeParse(todos([todo({ dueDate: '12.06.2026' })])).success).toBe(false);
expect(todoListCardSchema.safeParse(todos([todo({ priority: 4 })])).success).toBe(false);
const plain = todo({ dueDate: null, dueDayId: null, note: null });
expect(todoListCardSchema.safeParse(todos([plain])).success).toBe(true);
const ticked = todo({ change: 'check', checked: true, changed: [{ field: 'done', before: '0' }] });
expect(todoListCardSchema.safeParse(todos([ticked])).success).toBe(true);
});
it('PKCARD-007: a broken stored card reads as null instead of breaking the message', () => {
expect(storedTrekCardSchema.parse(packing({ groupBy: 'weight' }))).toBeNull();
expect(storedTrekCardSchema.parse(todos([todo({ change: 'archive' })]))).toBeNull();
});
it('PKCARD-008: the list read takes a category, a bag or none, a packed state and a grouping, nothing else', () => {
expect(packingListItemsRequestSchema.parse({ bag_id: null, status: 'open', group_by: 'bag' })).toEqual({
bag_id: null,
status: 'open',
group_by: 'bag',
});
expect(packingListItemsRequestSchema.safeParse({ status: 'done' }).success).toBe(false);
expect(packingListItemsRequestSchema.safeParse({ bag_id: 0 }).success).toBe(false);
expect(packingListItemsRequestSchema.safeParse({ category: '' }).success).toBe(false);
});
});
@@ -0,0 +1,18 @@
import { packingListCardSchema } from './packing-list.card';
import { todoListCardSchema } from './todo-list.card';
export * from './packing-list.card';
export * from './todo-list.card';
/**
* What the packing and to-do lists bring to the assistant chat: the kinds of card they draw,
* the verbs of their change cards and what an applied change of theirs
* touches, beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else. Their changes name the generic
* verbs with the tool's own label; a bag is the one thing they touch that the
* core has no name for.
*/
export const PACKING_CARD_SCHEMAS = [packingListCardSchema, todoListCardSchema] as const;
export const PACKING_VERB_KEYS = [] as const;
export const PACKING_APPLIED_ENTITIES = ['packing_bag'] as const;
@@ -0,0 +1,51 @@
import { idSchema } from '../../common/primitives.schema';
import { cardCurrencySchema, cardDateSchema, cardPersonSchema, cardText } from './card-parts';
import { expenseChangeSchema } from './expenses.card';
import { z } from 'zod';
/**
* Settle-up payments between the travellers, as the Costs page lists them
* under its payment history: who paid whom, how much, on which day, with the
* note it carries. One card serves the list (`list_settlements`) and every
* change to one payment; a waiting change names what it replaces in `before`.
*/
/** Payments one card lists; the rest are counted in `more`. */
export const PAYMENT_ROWS_MAX = 12;
/** What one payment moved: always more than nothing. */
export const cardPaymentMoneySchema = z.object({
amount: z.number().positive().max(1e9),
currency: cardCurrencySchema,
});
/** The values a waiting update of a payment replaces, each null where it stays. */
export const cardPaymentBeforeSchema = z.object({
from: cardPersonSchema.nullable(),
to: cardPersonSchema.nullable(),
amount: cardPaymentMoneySchema.nullable(),
});
export const cardPaymentSchema = z.object({
/** Null while a new payment waits for its decision. */
id: idSchema.nullable(),
from: cardPersonSchema,
to: cardPersonSchema,
amount: cardPaymentMoneySchema,
/** The day it was paid, else the day it was recorded. */
date: cardDateSchema.nullable(),
note: cardText(120).nullable(),
before: cardPaymentBeforeSchema.nullable(),
change: expenseChangeSchema,
});
export const paymentsCardSchema = z.object({
kind: z.literal('payments'),
rows: z.array(cardPaymentSchema).min(1).max(PAYMENT_ROWS_MAX),
more: z.number().int().min(0).max(100_000),
});
export type PaymentsCard = z.infer<typeof paymentsCardSchema>;
export type CardPayment = z.infer<typeof cardPaymentSchema>;
export type CardPaymentMoney = z.infer<typeof cardPaymentMoneySchema>;
@@ -0,0 +1,42 @@
import { idSchema } from '../../common/primitives.schema';
import { MAX_TRIP_DAYS } from '../../trip/trip.schema';
import { cardText } from './card-parts';
import { z } from 'zod';
/**
* The rules a road trip drives by, as a held change sets them: the driving
* settings it changes, each from its old value to its new one, or where it
* makes a day end (at a stop, part way along a drive, or back to the
* automatic end). The client names each setting the way the planner's
* settings name it, so a setting this build does not know reads by its key.
*/
/** A setting's value as the planner stores it: a clock, a number, a switch, a choice; null when it is not set. */
const settingValueSchema = z.union([z.string().max(40), z.number().min(0).max(100_000), z.boolean()]).nullable();
export const roadtripRulesCardSchema = z.object({
kind: z.literal('roadtripRules'),
settings: z
.array(
z.object({
key: z.string().regex(/^roadtrip_[a-z0-9_]{1,40}$/),
before: settingValueSchema,
after: settingValueSchema,
}),
)
.max(24),
dayEnd: z
.object({
dayId: idSchema.nullable(),
dayNumber: z.number().int().min(1).max(MAX_TRIP_DAYS),
// At the stop `from`; `percent` along the drive from `from` to `to`; or the automatic end again.
mode: z.enum(['stop', 'along', 'auto']),
from: cardText(80).nullable(),
to: cardText(80).nullable(),
percent: z.number().int().min(0).max(100).nullable(),
})
.nullable(),
});
export type RoadtripRulesCard = z.infer<typeof roadtripRulesCardSchema>;
export type RoadtripSettingChange = RoadtripRulesCard['settings'][number];
+138
View File
@@ -0,0 +1,138 @@
import { idSchema } from '../../common/primitives.schema';
import { roadtripStopTypeSchema } from '../../place/place.schema';
import { MAX_TRIP_DAYS } from '../../trip/trip.schema';
import { cardClockSchema, cardDateSchema, cardLatSchema, cardLngSchema, cardPointSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* A road trip's drive as calculate_roadtrip worked it out: the totals, a
* strip of its days and, for each day, the stops the planner's rail lists, in
* the shape the rail reads them, so the chat draws the very rows the planner
* draws. The server builds it from the tool's raw answer and fits it under
* MAX_CARD_CHARS: a long trip keeps its first days and counts the rest
* (`moreDays`), a long day its first stops (`moreStops`), and the lines of
* the drive are thinned until the card fits.
*/
/** The days a card holds in full; the rest are counted in `moreDays`. */
export const ROADTRIP_CARD_DAYS_MAX = 14;
/** The stops of one day a card holds; the rest are counted in `moreStops`. */
export const ROADTRIP_CARD_STOPS_MAX = 16;
/** The driven pieces of one day; a ride between two terminals splits a day's line. */
export const ROADTRIP_CARD_DAY_LINES_MAX = 4;
/** The points of one driven piece. */
export const ROADTRIP_CARD_LINE_POINTS_MAX = 64;
/** The points of every line of the card together. */
export const ROADTRIP_CARD_POINTS_MAX = 400;
const metres = z.number().min(0).max(5e7);
const seconds = z.number().min(0).max(1e7);
const minutes = z.number().int().min(0).max(100_000);
const dayNumber = z.number().int().min(1).max(MAX_TRIP_DAYS);
/** A driven piece of a day, `[lat, lng]` points at five decimals. */
export const roadtripCardLineSchema = z.array(cardPointSchema).min(2).max(ROADTRIP_CARD_LINE_POINTS_MAX);
/** One stop of a day as the planner's rail reads it, with its schedule entry and what is wrong about it. */
export const roadtripCardStopSchema = z.object({
// Null for a ride's terminal or a hire car's desk, which are no places of the trip.
placeId: idSchema.nullable(),
// Null for a booked night at a day's edge and for a terminal: neither is an assignment.
assignmentId: idSchema.nullable(),
name: cardText(80),
lat: cardLatSchema,
lng: cardLngSchema,
stopType: roadtripStopTypeSchema.nullable(),
// A time pinned on the stop, and the time the drive leaves it at.
time: cardClockSchema.nullable(),
leaveAt: cardClockSchema.nullable(),
dwellMinutes: z.number().int().min(0).max(10_080).nullable(),
offRoadM: z.number().int().min(0).max(100_000).nullable(),
// The stop's own fill figure; null follows the trip's setting.
fillPercent: z.number().int().min(0).max(100).nullable(),
// The booked night's stop on its check-in day.
night: z.object({ checkIn: cardClockSchema.nullable() }).nullable(),
// A marker the daily travel times put where a day ends or resumes.
autoNight: z.object({ phase: z.enum(['start', 'end']), fromDayNumber: dayNumber }).nullable(),
bookend: z
.object({
phase: z.enum(['morning', 'evening']),
reservationId: idSchema.nullable(),
checkingIn: z.boolean(),
checkingOut: z.boolean(),
checkIn: cardClockSchema.nullable(),
checkOut: cardClockSchema.nullable(),
})
.nullable(),
carrier: z
.object({
reservationId: idSchema,
type: z.string().min(1).max(20),
role: z.enum(['departure', 'arrival', 'pickup', 'return']),
title: cardText(80),
code: z.string().min(1).max(8).nullable(),
at: cardClockSchema.nullable(),
})
.nullable(),
// The schedule's entry for the stop.
arrival: cardClockSchema.nullable(),
departure: cardClockSchema.nullable(),
anchored: z.boolean(),
dayOffset: z.number().int().min(0).max(60),
late: z.array(z.object({ code: z.enum(['late', 'missedLeave']), minutes })).max(2),
// About the drive LEAVING this stop.
findings: z
.array(
z.object({
code: z.enum(['leg', 'range']),
overMinutes: minutes.nullable(),
sinceKm: z.number().min(0).max(40_000).nullable(),
}),
)
.max(2),
});
/** One day of the drive. `legs[i]` runs from `stops[i]` to `stops[i + 1]`; null where it is not routed. */
export const roadtripCardDaySchema = z.object({
dayId: idSchema,
dayNumber,
date: cardDateSchema.nullable(),
title: cardText(80).nullable(),
distanceM: metres,
durationS: seconds,
stops: z.array(roadtripCardStopSchema).max(ROADTRIP_CARD_STOPS_MAX),
moreStops: z.number().int().min(0).max(1000),
legs: z
.array(z.object({ distanceM: metres, durationS: seconds, mode: z.string().min(1).max(40) }).nullable())
.max(ROADTRIP_CARD_STOPS_MAX - 1),
dayOver: z.object({ minutes, limitMinutes: z.number().int().min(1).max(1440) }).nullable(),
avoidMissed: z.array(z.enum(['motorway', 'toll', 'ferry'])).max(3),
// Where the range runs out, counted from the last fill.
dryKm: z.number().min(0).max(40_000).nullable(),
// The driven pieces only: a ride's straight jump between its terminals is left out.
lines: z.array(roadtripCardLineSchema).max(ROADTRIP_CARD_DAY_LINES_MAX),
});
export const roadtripCardSchema = z.object({
kind: z.literal('roadtrip'),
complete: z.boolean(),
problem: z.enum(['routing', 'coordinates', 'dayWindow']).nullable(),
// The settings a preview tried without saving them; empty for the saved drive.
previewKeys: z.array(z.string().regex(/^roadtrip_[a-z0-9_]{1,40}$/)).max(12),
vehicle: z.enum(['combustion', 'electric']).nullable(),
defaultFill: z.number().int().min(1).max(100).nullable(),
// The trip's own setting, so the sketch colours its days the way the map does.
dayColors: z.boolean(),
distanceM: metres,
durationS: seconds,
stopCount: z.number().int().min(0).max(10_000),
chargingCount: z.number().int().min(0).max(10_000),
days: z.array(roadtripCardDaySchema).min(1).max(ROADTRIP_CARD_DAYS_MAX),
moreDays: z.number().int().min(0).max(1000),
quietDays: z.number().int().min(0).max(1000),
undatedRides: z.number().int().min(0).max(100),
});
export type RoadtripCard = z.infer<typeof roadtripCardSchema>;
export type RoadtripCardDay = z.infer<typeof roadtripCardDaySchema>;
export type RoadtripCardStop = z.infer<typeof roadtripCardStopSchema>;
@@ -0,0 +1,241 @@
import { ASSISTANT_CHANGE_VERB_KEYS, assistantAppliedSchema } from '../assistant.schema';
import { MAX_CARD_CHARS } from './card-parts';
import { chargingCardSchema } from './charging.card';
import { corridorCardSchema } from './corridor.card';
import { dayRouteCardSchema } from './day-route.card';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { roadtripRulesCardSchema } from './roadtrip-rules.card';
import { ROADTRIP_CARD_DAYS_MAX, roadtripCardSchema, type RoadtripCardStop } from './roadtrip.card';
import { ROADTRIP_VERB_KEYS } from './roadtrip.contract';
import { transitCardSchema } from './transit.card';
import { describe, expect, it } from 'vitest';
const stop = (name: string, extra: Partial<RoadtripCardStop> = {}): RoadtripCardStop => ({
placeId: 7,
assignmentId: 70,
name,
lat: 48.13743,
lng: 11.57549,
stopType: null,
time: null,
leaveAt: null,
dwellMinutes: 30,
offRoadM: null,
fillPercent: null,
night: null,
autoNight: null,
bookend: null,
carrier: null,
arrival: '08:00',
departure: '08:30',
anchored: false,
dayOffset: 0,
late: [],
findings: [],
...extra,
});
const day = (dayId: number) => ({
dayId,
dayNumber: dayId,
date: '2026-10-01',
title: null,
distanceM: 152_000,
durationS: 5880,
stops: [stop('Munich'), stop('Verona', { placeId: 8, assignmentId: 80, arrival: '15:20', departure: null })],
moreStops: 0,
legs: [{ distanceM: 152_000, durationS: 5880, mode: 'driving' }],
dayOver: null,
avoidMissed: [],
dryKm: null,
lines: [
[
[48.13743, 11.57549],
[45.43839, 10.99162],
],
],
});
const drive = {
kind: 'roadtrip',
complete: true,
problem: null,
previewKeys: [],
vehicle: 'electric',
defaultFill: 80,
dayColors: true,
distanceM: 152_000,
durationS: 5880,
stopCount: 2,
chargingCount: 0,
days: [day(1)],
moreDays: 0,
quietDays: 0,
undatedRides: 0,
};
describe('road trip cards', () => {
it('RTCARD-010: a drive with its days, stops and lines reads, and is one of the union', () => {
expect(roadtripCardSchema.safeParse(drive).success).toBe(true);
expect(trekCardSchema.safeParse(drive).success).toBe(true);
});
it('RTCARD-011: a drive past its bounds reads as no card instead of breaking the message', () => {
const days = Array.from({ length: ROADTRIP_CARD_DAYS_MAX + 1 }, (_, index) => day(index + 1));
expect(roadtripCardSchema.safeParse({ ...drive, days }).success).toBe(false);
expect(storedTrekCardSchema.parse({ ...drive, days })).toBeNull();
expect(storedTrekCardSchema.parse({ ...drive, days: [] })).toBeNull();
const badClock = { ...drive, days: [{ ...day(1), stops: [stop('Munich', { arrival: '25:00' })] }] };
expect(roadtripCardSchema.safeParse(badClock).success).toBe(false);
const oneLinePoint = { ...drive, days: [{ ...day(1), lines: [[[48, 11]]] }] };
expect(roadtripCardSchema.safeParse(oneLinePoint).success).toBe(false);
});
it('RTCARD-012: a terminal, a booked night and a day marker are stops of their own shape', () => {
const terminal = stop('Munich Airport', {
placeId: null,
assignmentId: null,
carrier: { reservationId: 4, type: 'flight', role: 'departure', title: 'LH 1840', code: 'MUC', at: '11:05' },
});
const night = stop('Hotel Adler', {
assignmentId: null,
stopType: 'hotel',
bookend: {
phase: 'evening',
reservationId: null,
checkingIn: true,
checkingOut: false,
checkIn: '15:00',
checkOut: null,
},
});
const marker = stop('Brenner', { autoNight: { phase: 'end', fromDayNumber: 1 } });
const card = { ...drive, days: [{ ...day(1), stops: [terminal, night, marker], legs: [null, null] }] };
expect(roadtripCardSchema.safeParse(card).success).toBe(true);
const typeless = { ...terminal, carrier: { ...terminal.carrier, type: '' } };
expect(roadtripCardSchema.safeParse({ ...drive, days: [{ ...day(1), stops: [typeless] }] }).success).toBe(false);
});
it('RTCARD-013: a corridor search, a charger, connections and a day route read, each within its bounds', () => {
const corridor = {
kind: 'corridor',
dayId: 3,
dayNumber: 2,
category: 'charging',
widthKm: 5,
hits: [
{
ref: 'call_1:0',
name: 'Ionity Holzkirchen',
brand: 'Ionity',
lat: 47.88,
lng: 11.7,
alongKm: 31.4,
offKm: 0.42,
between: ['Munich', 'Verona'],
sockets: [{ type: 'ccs', kw: 350, count: 6 }],
},
],
more: 0,
searched: { done: 6, total: 9 },
partial: true,
};
expect(corridorCardSchema.safeParse(corridor).success).toBe(true);
expect(corridorCardSchema.safeParse({ ...corridor, category: 'museum' }).success).toBe(false);
const charging = {
kind: 'charging',
placeId: 7,
name: 'Ionity Holzkirchen',
station: null,
lat: 47.88,
lng: 11.7,
status: 'ok',
stale: false,
available: 4,
total: 6,
checkedAt: '2026-10-01T09:38:00Z',
updatedAt: null,
energy: { amount: 0.59, currency: 'EUR' },
otherPrices: 1,
source: 'MobiData BW',
license: 'CC BY 4.0',
};
expect(chargingCardSchema.safeParse(charging).success).toBe(true);
expect(chargingCardSchema.safeParse({ ...charging, checkedAt: '2026-10-01 09:38' }).success).toBe(false);
const leg = {
mode: 'RAIL',
line: 'RE 4',
lineColor: '#ff0000',
lineTextColor: null,
from: { name: 'Munich Hbf', time: '08:04', track: '12' },
to: { name: 'Rosenheim', time: '08:41', track: null },
durationS: 2220,
stops: 3,
headsign: 'Salzburg',
agency: null,
};
const itinerary = {
date: '2026-10-01',
start: '08:04',
end: '08:41',
endDayOffset: 0,
durationS: 2220,
transfers: 0,
walkS: 0,
legs: [leg],
};
const transit = { kind: 'transit', from: 'Munich', to: 'Rosenheim', dayId: null, more: 0, dropped: 0 };
expect(transitCardSchema.safeParse({ ...transit, itineraries: [itinerary] }).success).toBe(true);
const shortColour = { ...itinerary, legs: [{ ...leg, lineColor: '#f00' }] };
expect(transitCardSchema.safeParse({ ...transit, itineraries: [shortColour] }).success).toBe(false);
const route = {
kind: 'dayRoute',
dayId: 3,
dayNumber: 2,
stops: [{ placeId: 7, name: 'Munich', lat: 48.1, lng: 11.6, added: false }],
vias: [{ lat: 47.5, lng: 11.2, after: 0, state: 'moved', from: [47.4, 11.1] }],
afterName: 'Munich',
track: null,
unresolved: [],
};
expect(dayRouteCardSchema.safeParse(route).success).toBe(true);
const lostVia = { ...route, vias: [{ ...route.vias[0], state: 'lost' }] };
expect(dayRouteCardSchema.safeParse(lostVia).success).toBe(false);
});
it('RTCARD-014: the road trip adds its verbs and its applied entity to the shared enums', () => {
for (const verb of ROADTRIP_VERB_KEYS) expect(ASSISTANT_CHANGE_VERB_KEYS).toContain(verb);
const applied = { toolCallId: 'call_1', entity: 'roadtrip', ids: [5], dayId: 3, undoUntil: null };
expect(assistantAppliedSchema.parse(applied).entity).toBe('roadtrip');
});
it('RTCARD-016: the rules a change sets read with their values as stored, and a key that is no setting does not', () => {
const rules = {
kind: 'roadtripRules',
settings: [
{ key: 'roadtrip_day_start', before: '08:00', after: '09:30' },
{ key: 'roadtrip_hotel_bookends', before: null, after: true },
{ key: 'roadtrip_leg_minutes', before: 120, after: 0 },
],
dayEnd: { dayId: 3, dayNumber: 2, mode: 'along', from: 'Garmisch', to: 'Innsbruck', percent: 40 },
};
expect(roadtripRulesCardSchema.safeParse(rules).success).toBe(true);
expect(trekCardSchema.safeParse({ ...rules, dayEnd: null }).success).toBe(true);
const foreign = { ...rules, settings: [{ key: 'endpoint_url', before: null, after: 'x' }] };
expect(roadtripRulesCardSchema.safeParse(foreign).success).toBe(false);
const auto = { ...rules, dayEnd: { ...rules.dayEnd, mode: 'never' } };
expect(roadtripRulesCardSchema.safeParse(auto).success).toBe(false);
});
it('RTCARD-015: the fullest drive the bounds allow is a card the server can still check under the size cap', () => {
// The bounds alone do not hold a drive under MAX_CARD_CHARS; the server's builder fits it.
const days = Array.from({ length: ROADTRIP_CARD_DAYS_MAX }, (_, index) => day(index + 1));
const full = { ...drive, days };
expect(roadtripCardSchema.safeParse(full).success).toBe(true);
expect(JSON.stringify(full).length).toBeLessThan(MAX_CARD_CHARS);
});
});
@@ -0,0 +1,48 @@
import { chargingCardSchema } from './charging.card';
import { corridorCardSchema } from './corridor.card';
import { dayRouteCardSchema } from './day-route.card';
import { roadtripRulesCardSchema } from './roadtrip-rules.card';
import { roadtripCardSchema } from './roadtrip.card';
import { transitCardSchema } from './transit.card';
export * from './charging.card';
export * from './corridor.card';
export * from './day-route.card';
export * from './roadtrip-rules.card';
export * from './roadtrip.card';
export * from './transit.card';
/**
* What the road trip brings to the assistant chat: the kinds of card it draws,
* the verbs of its change cards and what an applied change of its
* touches, beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else.
*/
export const ROADTRIP_CARD_SCHEMAS = [
roadtripCardSchema,
corridorCardSchema,
chargingCardSchema,
transitCardSchema,
dayRouteCardSchema,
roadtripRulesCardSchema,
] as const;
/**
* A via point sent into a day's drive, a chain of them laid at once, one
* moved, one taken out, the vias of a day pinned again to its stops; the
* driving settings changed; where a day ends set; a Google Maps route taken
* in as stops; a transit connection added.
*/
export const ROADTRIP_VERB_KEYS = [
'addRouteVia',
'shapeRoute',
'moveRouteVia',
'removeRouteVia',
'repinRouteVias',
'updateDriveSettings',
'setDayBoundary',
'importRoute',
'addTransit',
] as const;
/** The road trip of a trip: its vias, its settings and its day endings, shown on the plan by their day. */
export const ROADTRIP_APPLIED_ENTITIES = ['roadtrip'] as const;
@@ -0,0 +1,36 @@
import { cardCurrencySchema, cardPersonSchema } from './card-parts';
import { z } from 'zod';
/**
* Settle up as the Costs page shows it: the payments that would square the
* trip (who pays whom), each traveller's balance (positive is owed money,
* negative owes it), how many payments were already recorded, and the
* entries no exchange rate converts yet, which count in no figure. Every
* amount is in `currency`.
*/
/** Suggested payments one card names; the rest are counted in `moreFlows`. */
export const SETTLEMENT_FLOWS_MAX = 12;
/** Balances one card names; the rest are counted in `moreBalances`. */
export const SETTLEMENT_BALANCES_MAX = 20;
export const settlementCardSchema = z.object({
kind: z.literal('settlement'),
currency: cardCurrencySchema,
flows: z
.array(z.object({ from: cardPersonSchema, to: cardPersonSchema, amount: z.number().positive().max(1e9) }))
.max(SETTLEMENT_FLOWS_MAX),
moreFlows: z.number().int().min(0).max(1000),
balances: z
.array(z.object({ person: cardPersonSchema, balance: z.number().min(-1e9).max(1e9) }))
.max(SETTLEMENT_BALANCES_MAX),
moreBalances: z.number().int().min(0).max(1000),
/** Payments already recorded. */
recorded: z.number().int().min(0).max(100_000),
unconverted: z.object({
entries: z.number().int().min(0).max(100_000),
currencies: z.array(cardCurrencySchema).max(6),
}),
});
export type SettlementCard = z.infer<typeof settlementCardSchema>;
@@ -0,0 +1,59 @@
import { idSchema } from '../../common/primitives.schema';
import { cardDateSchema, cardPersonSchema, cardText } from './card-parts';
import { checklistBeforeSchema, checklistColorSlotSchema } from './packing-list.card';
import { z } from 'zod';
/**
* The trip's to-dos in the assistant chat, grouped by their list (category)
* the way the to-do panel shows them. On a change card the rows carry what
* the change does to them and the old value of every field it touches; on an
* answer `change` is `none`.
*/
const todoCountSchema = z.number().int().min(0).max(5_000);
export const TODO_ROW_CHANGES = ['none', 'add', 'update', 'check', 'uncheck', 'remove'] as const;
/** `done` is kept by a tick only (`'1'` or `'0'`), for the way back; it is never drawn as a fact. */
export const TODO_FIELDS = ['name', 'note', 'category', 'dueDate', 'priority', 'assignee', 'done'] as const;
export const todoCardItemSchema = z.object({
/** Null while a create waits. */
id: idSchema.nullable(),
name: cardText(300),
/** The first line of the description. */
note: cardText(160).nullable(),
checked: z.boolean(),
dueDate: cardDateSchema.nullable(),
/** The trip day on the due date, so the date can show that day in the plan. */
dueDayId: idSchema.nullable(),
/** 0 for none, 1 the highest. */
priority: z.number().int().min(0).max(3),
assignee: cardPersonSchema.nullable(),
change: z.enum(TODO_ROW_CHANGES),
changed: z.array(z.object({ field: z.enum(TODO_FIELDS), before: checklistBeforeSchema })).max(7),
});
export type TodoCardItem = z.infer<typeof todoCardItemSchema>;
export const todoCardGroupSchema = z.object({
/** Null: the to-dos on no list. */
category: cardText(100).nullable(),
slot: checklistColorSlotSchema.nullable(),
/** Who a list's new to-dos go to by default. */
assignees: z.array(cardPersonSchema).max(6),
assigneesRemoved: z.array(cardPersonSchema).max(6),
items: z.array(todoCardItemSchema).max(40),
/** The group's to-dos, shown or not. */
count: todoCountSchema,
open: todoCountSchema,
});
export type TodoCardGroup = z.infer<typeof todoCardGroupSchema>;
export const todoListCardSchema = z.object({
kind: z.literal('todoList'),
/** Overdue against the day of the read; answers only. */
progress: z.object({ open: todoCountSchema, done: todoCountSchema, overdue: todoCountSchema }).nullable(),
groups: z.array(todoCardGroupSchema).max(12),
moreGroups: todoCountSchema,
});
export type TodoListCard = z.infer<typeof todoListCardSchema>;
@@ -0,0 +1,37 @@
import { idSchema } from '../../common/primitives.schema';
import { tourMaxHikingDifficultySchema, tourTypeKeySchema } from '../../tours/tours.schema';
import { cardText } from './card-parts';
import { z } from 'zod';
/**
* The saved tours of a trip, or of one of its days, as rows like the Tours
* sidebar shows them: the activity, the name, time, distance and climb, the
* stages of a tour over several days, and the days it is on.
*/
/** The most rows one card lists; `more` counts the rest. */
export const TOUR_LIST_ROWS = 12;
export const tourListRowSchema = z.object({
placeId: idSchema,
name: cardText(120),
activity: tourTypeKeySchema,
limit: tourMaxHikingDifficultySchema.nullable(),
distanceM: z.number().int().min(0).max(5_000_000).nullable(),
ascentM: z.number().int().min(0).max(100_000).nullable(),
minutes: z.number().int().min(0).max(86_400).nullable(),
stages: z.number().int().min(2).max(60).nullable(),
/** The numbers of the trip days it is on, in day order. */
days: z.array(z.number().int().min(1).max(999)).max(10),
});
export type TourListRow = z.infer<typeof tourListRowSchema>;
export const tourListCardSchema = z.object({
kind: z.literal('tourList'),
/** The day the list was asked for; null for the whole trip. */
dayId: idSchema.nullable(),
more: z.number().int().min(0).max(10_000),
rows: z.array(tourListRowSchema).min(1).max(TOUR_LIST_ROWS),
});
export type TourListCard = z.infer<typeof tourListCardSchema>;
@@ -0,0 +1,197 @@
import { storedTrekCardSchema, trekCardSchema } from './index';
import { TOUR_LIST_ROWS, tourListCardSchema } from './tour-list.card';
import { TOUR_ROUTE_LIMITS, tourRouteCardSchema, type TourRouteCard, type TourRouteStop } from './tour-route.card';
import { describe, expect, it } from 'vitest';
function stop(atM: number, extra: Partial<TourRouteStop> = {}): TourRouteStop {
return {
role: 'via',
kind: null,
name: null,
lat: 47.6,
lng: 11.3,
atM,
offM: null,
minutes: null,
clock: null,
stayMinutes: null,
stageEnd: false,
flag: null,
...extra,
};
}
/** A routed hike with every part filled once. */
function hike(extra: Partial<TourRouteCard> = {}): TourRouteCard {
return {
kind: 'tourRoute',
source: 'proposal',
activity: 'hike',
placeId: null,
name: 'Hochfelln from Bergen',
label: 'short and steep',
distanceM: 8200,
ascentM: 640,
descentM: 640,
minEleM: 560,
maxEleM: 1670,
minutes: 200,
minutesBasis: 'din33466',
limit: 3,
grades: { highest: 3, unknownShare: 0.2 },
routed: true,
problem: null,
line: [
[47.6, 11.3, 560],
[47.61, 11.31, 1670],
],
stretches: [{ facet: 'sac', fromM: 0, toM: 4000, step: 3 }],
stops: [stop(0, { role: 'start', clock: '08:00' }), stop(4100, { role: 'end', kind: 'peak', name: 'Hochfelln' })],
stages: null,
skiScheme: null,
schedule: {
date: '2026-10-14',
dayId: 31,
dayNumber: 2,
start: '08:00',
arrive: '11:20',
nextDay: false,
sunrise: '06:58',
sunset: '18:41',
latestStart: null,
weather: 'forecast',
hours: [{ hour: 8, main: 'Clear', tempC: 12, rainPct: null, windKmh: 10 }],
},
warnings: [{ kind: 'thunder', at: '11:00', count: null }],
previous: null,
...extra,
};
}
describe('tourRouteCardSchema', () => {
it('TOURCARD-001: a routed hike parses and joins the card union', () => {
expect(tourRouteCardSchema.safeParse(hike()).success).toBe(true);
expect(trekCardSchema.safeParse(hike()).success).toBe(true);
});
it('TOURCARD-002: refuses a line, stops or stretches past their bounds', () => {
const point: [number, number, number | null] = [47.6, 11.3, null];
const line = Array.from({ length: TOUR_ROUTE_LIMITS.line + 1 }, () => point);
expect(tourRouteCardSchema.safeParse(hike({ line })).success).toBe(false);
const stops = Array.from({ length: TOUR_ROUTE_LIMITS.stops + TOUR_ROUTE_LIMITS.along + 1 }, (_, i) => stop(i));
expect(tourRouteCardSchema.safeParse(hike({ stops })).success).toBe(false);
const stretches = Array.from({ length: TOUR_ROUTE_LIMITS.stretches + 1 }, (_, i) => ({
facet: 'sac' as const,
fromM: i,
toM: i + 1,
step: 2,
}));
expect(tourRouteCardSchema.safeParse(hike({ stretches })).success).toBe(false);
// At the bounds it still parses.
expect(tourRouteCardSchema.safeParse(hike({ line: line.slice(1), stops: stops.slice(1) })).success).toBe(true);
});
it('TOURCARD-003: an unknown facet, problem or stop kind fails, a height with decimals too', () => {
const odd = { facet: 'colour', fromM: 0, toM: 1 } as unknown as TourRouteCard['stretches'][number];
expect(tourRouteCardSchema.safeParse(hike({ stretches: [odd] })).success).toBe(false);
const why = { why: 'weird', position: null, snappedM: null } as unknown as TourRouteCard['problem'];
expect(tourRouteCardSchema.safeParse(hike({ problem: why })).success).toBe(false);
const kind = stop(0, { kind: 'castle' as unknown as TourRouteStop['kind'] });
expect(tourRouteCardSchema.safeParse(hike({ stops: [kind] })).success).toBe(false);
expect(tourRouteCardSchema.safeParse(hike({ line: [[47.6, 11.3, 560.5]] })).success).toBe(false);
});
it('TOURCARD-004: a straight card without figures parses, as a held change planned on apply', () => {
const straight = hike({
source: 'pending',
label: null,
distanceM: null,
ascentM: null,
descentM: null,
minEleM: null,
maxEleM: null,
minutes: null,
minutesBasis: null,
grades: null,
routed: false,
problem: { why: 'not_planned', position: null, snappedM: null },
line: [
[47.6, 11.3, null],
[47.61, 11.31, null],
],
stretches: [],
schedule: null,
warnings: [],
});
expect(tourRouteCardSchema.safeParse(straight).success).toBe(true);
});
it('TOURCARD-005: ski stretches, marks, a failed-legs warning and the line before a change parse', () => {
const ski = hike({
activity: 'ski',
source: 'plan',
skiScheme: 'north_america',
stretches: [
{ facet: 'ski', fromM: 0, toM: 900, kind: 'run', difficulty: 'intermediate' },
{ facet: 'mark', fromM: 900, toM: 1500, kind: 'lift' },
],
warnings: [{ kind: 'legs_failed', at: null, count: 2 }],
previous: {
line: [
[47.6, 11.3],
[47.62, 11.32],
],
distanceM: 9000,
ascentM: null,
minutes: 210,
},
});
expect(tourRouteCardSchema.safeParse(ski).success).toBe(true);
});
it('TOURCARD-006: extra keys are dropped on read, a broken card reads as null', () => {
const parsed = storedTrekCardSchema.parse({ ...hike(), later: 'field' });
expect(parsed).not.toHaveProperty('later');
expect(storedTrekCardSchema.parse({ ...hike(), routed: 'yes' })).toBeNull();
});
});
describe('tourRouteCardSchema: bike tours and runs', () => {
it('TOURCARD-008: a bike tour or a run names its profile, a run its pace; a card drawn before reads without both', () => {
const bike = hike({
activity: 'bike',
routingProfile: 'gravel',
minutesBasis: 'router',
limit: null,
grades: null,
});
expect(tourRouteCardSchema.parse(bike).routingProfile).toBe('gravel');
const run = hike({ activity: 'run', routingProfile: 'trail', minutesBasis: 'pace', paceSecondsPerKm: 330 });
expect(tourRouteCardSchema.parse(run).paceSecondsPerKm).toBe(330);
expect(tourRouteCardSchema.parse(hike()).routingProfile).toBeUndefined();
expect(tourRouteCardSchema.safeParse(hike({ routingProfile: 'tandem' as never })).success).toBe(false);
expect(tourRouteCardSchema.safeParse(hike({ paceSecondsPerKm: 5 })).success).toBe(false);
});
});
describe('tourListCardSchema', () => {
const row = {
placeId: 61,
name: 'Herzogstand',
activity: 'hike' as const,
limit: 2,
distanceM: 9800,
ascentM: 520,
minutes: 225,
stages: null,
days: [2],
};
it('TOURCARD-007: a list parses with one to twelve rows, not none and not more', () => {
expect(tourListCardSchema.safeParse({ kind: 'tourList', dayId: null, more: 0, rows: [row] }).success).toBe(true);
expect(tourListCardSchema.safeParse({ kind: 'tourList', dayId: 31, more: 0, rows: [] }).success).toBe(false);
const rows = Array.from({ length: TOUR_LIST_ROWS + 1 }, () => row);
expect(tourListCardSchema.safeParse({ kind: 'tourList', dayId: null, more: 0, rows }).success).toBe(false);
});
});
@@ -0,0 +1,194 @@
import { idSchema } from '../../common/primitives.schema';
import { skiColourSchemeSchema, skiRunDifficultySchema, skiSegmentKindSchema } from '../../ski/ski-route.schema';
import { HIKE_UNROUTED_REASONS } from '../../tours/hike-plan.schema';
import { HIKE_WARNING_KINDS } from '../../tours/hike-schedule';
import { tourPoiCategorySchema } from '../../tours/tour-poi-category';
import {
BIKE_PROFILES,
RUN_PROFILES,
tourMaxHikingDifficultySchema,
tourTypeKeySchema,
} from '../../tours/tours.schema';
import { cardClockSchema, cardDateSchema, cardLatSchema, cardLngSchema, cardPointSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* A tour's route as the chat draws it: a hike, a city walk, a paddle or a ski
* plan the assistant proposed, a held change that will create or change one,
* or a saved tour it read. One kind for every line, so a sketch, a height
* profile, the stops by how far along they lie, the day with its sun and
* weather and what to look out for read the same whatever the activity.
* Positions are metres along the whole route; the line is thinned for
* drawing and every height is whole metres.
*/
/** How much one card carries at most. */
export const TOUR_ROUTE_LIMITS = {
line: 300,
stops: 30,
along: 12,
stretches: 80,
hours: 18,
warnings: 6,
previous: 200,
} as const;
const L = TOUR_ROUTE_LIMITS;
const metres = z.number().int().min(0).max(5_000_000);
const climb = z.number().int().min(0).max(100_000);
const height = z.number().int().min(-500).max(9_000);
const minutes = z.number().int().min(0).max(86_400);
const sacStep = z.number().int().min(1).max(6);
/** A point of the line, `[lat, lng, height]` at five decimals; every height is null when one is missing. */
export type TourRoutePoint = [number, number, number | null];
// Re-typed on the way out like cardPointSchema, for the builds without strictNullChecks.
export const tourRoutePointSchema = z
.tuple([cardLatSchema, cardLngSchema, height.nullable()])
.transform(([lat, lng, metres]): TourRoutePoint => [lat, lng, metres]);
/** What a stop is beyond its role: a kind of place along a hike, its highest point, a city walk's station. */
export const TOUR_ROUTE_STOP_KINDS = ['highest', 'station'] as const;
/** Why a city walk's station is flagged: closed when it is reached, late for an appointment, past the time frame. */
export const TOUR_ROUTE_STOP_FLAGS = ['closed', 'late', 'after_frame'] as const;
export const tourRouteStopSchema = z.object({
role: z.enum(['start', 'via', 'end', 'along']),
kind: z.union([tourPoiCategorySchema, z.enum(TOUR_ROUTE_STOP_KINDS)]).nullable(),
name: cardText(80).nullable(),
lat: cardLatSchema,
lng: cardLngSchema,
atM: metres,
/** A place along the way: how far off it, in metres. */
offM: z.number().int().min(0).max(2_000).nullable(),
/** The walking minutes from the start to it. */
minutes: minutes.nullable(),
/** When it is reached on the day's schedule. */
clock: cardClockSchema.nullable(),
stayMinutes: minutes.nullable(),
stageEnd: z.boolean(),
flag: z.enum(TOUR_ROUTE_STOP_FLAGS).nullable(),
});
export type TourRouteStop = z.infer<typeof tourRouteStopSchema>;
/** A stretch drawn dotted: carried, white water, a gap in the data, a ferry, a lift, a via ferrata, drawn freely. */
export const TOUR_ROUTE_MARKS = ['portage', 'rapids', 'gap', 'ferry', 'lift', 'ferrata', 'free'] as const;
/** A stretch of the route with something to tell: its SAC grade, a ski run or trail, or a mark. */
export const tourRouteStretchSchema = z.discriminatedUnion('facet', [
z.object({ facet: z.literal('sac'), fromM: metres, toM: metres, step: sacStep }),
z.object({
facet: z.literal('ski'),
fromM: metres,
toM: metres,
kind: skiSegmentKindSchema,
difficulty: skiRunDifficultySchema.nullable(),
}),
z.object({ facet: z.literal('mark'), fromM: metres, toM: metres, kind: z.enum(TOUR_ROUTE_MARKS) }),
]);
export type TourRouteStretch = z.infer<typeof tourRouteStretchSchema>;
/** What to look out for: the day's weather and light, and legs of a plan that could not be planned. */
export const TOUR_WARNING_KINDS = [...HIKE_WARNING_KINDS, 'legs_failed'] as const;
/**
* Why a route is drawn straight between its stops: the hike planner's
* reasons, a city walk whose only way runs by boat, or a held change whose
* way is planned only once it is applied.
*/
export const TOUR_ROUTE_PROBLEMS = [...HIKE_UNROUTED_REASONS, 'ferry_only', 'not_planned'] as const;
/** The profile a bike tour or a run is planned for, as the Tours tab names it. */
export const TOUR_ROUTE_PROFILES = [...BIKE_PROFILES, ...RUN_PROFILES] as const;
export const tourRouteScheduleSchema = z.object({
date: cardDateSchema,
dayId: idSchema.nullable(),
dayNumber: z.number().int().min(1).max(999).nullable(),
start: cardClockSchema.nullable(),
arrive: cardClockSchema.nullable(),
nextDay: z.boolean(),
sunrise: cardClockSchema.nullable(),
sunset: cardClockSchema.nullable(),
latestStart: cardClockSchema.nullable(),
weather: z.enum(['forecast', 'climate']).nullable(),
hours: z
.array(
z.object({
hour: z.number().int().min(0).max(23),
main: cardText(20),
tempC: z.number().int().min(-80).max(60),
/** Null where the weather knows no likelihood (last year's day, a past day): never read as 0 %. */
rainPct: z.number().int().min(0).max(100).nullable(),
windKmh: z.number().int().min(0).max(400).nullable(),
}),
)
.max(L.hours),
});
export type TourRouteSchedule = z.infer<typeof tourRouteScheduleSchema>;
export const tourRouteCardSchema = z.object({
kind: z.literal('tourRoute'),
/** proposal: a way proposed; plan: a paddle or ski plan; pending: a held change; saved: a tour of the trip. */
source: z.enum(['proposal', 'plan', 'pending', 'saved']),
activity: tourTypeKeySchema,
placeId: idSchema.nullable(),
name: cardText(120).nullable(),
/** A way's own words when several are compared ("short and steep"). */
label: cardText(40).nullable(),
distanceM: metres.nullable(),
ascentM: climb.nullable(),
descentM: climb.nullable(),
minEleM: height.nullable(),
maxEleM: height.nullable(),
minutes: minutes.nullable(),
/** pace: a run's distance at the runner's pace. */
minutesBasis: z.enum(['din33466', 'router', 'planned', 'stations', 'piste', 'pace']).nullable(),
/**
* A bike tour's or a run's profile (road, gravel, trail ...); null for every
* other activity. Left out by a card drawn before it was sent.
*/
routingProfile: z.enum(TOUR_ROUTE_PROFILES).nullable().optional(),
/** A run's pace in seconds per kilometre; null without one. Left out like the profile. */
paceSecondsPerKm: z.number().int().min(60).max(3_600).nullable().optional(),
/** The hiking limit the way was planned under, a setting rather than a grade of the path. */
limit: tourMaxHikingDifficultySchema.nullable(),
grades: z.object({ highest: sacStep.nullable(), unknownShare: z.number().min(0).max(1) }).nullable(),
/** False: the stops joined straight, drawn dashed, without a profile. */
routed: z.boolean(),
problem: z
.object({
why: z.enum(TOUR_ROUTE_PROBLEMS),
position: z.number().int().positive().nullable(),
snappedM: z.number().int().min(0).max(1_000_000).nullable(),
})
.nullable(),
line: z.array(tourRoutePointSchema).max(L.line),
stretches: z.array(tourRouteStretchSchema).max(L.stretches),
/** In the order they lie along the way. */
stops: z.array(tourRouteStopSchema).max(L.stops + L.along),
stages: z.number().int().min(2).max(60).nullable(),
skiScheme: skiColourSchemeSchema.nullable(),
schedule: tourRouteScheduleSchema.nullable(),
warnings: z
.array(
z.object({
kind: z.enum(TOUR_WARNING_KINDS),
at: cardClockSchema.nullable(),
count: z.number().int().min(1).max(50).nullable(),
}),
)
.max(L.warnings),
/** A held change of a saved tour's way: the way it has now, to draw faintly beside the new one. */
previous: z
.object({
line: z.array(cardPointSchema).min(2).max(L.previous),
distanceM: metres,
ascentM: climb.nullable(),
minutes: minutes.nullable(),
})
.nullable(),
});
export type TourRouteCard = z.infer<typeof tourRouteCardSchema>;
@@ -0,0 +1,45 @@
import { tourListCardSchema } from './tour-list.card';
import { tourRouteCardSchema } from './tour-route.card';
export * from './tour-list.card';
export * from './tour-route.card';
/**
* What the tours bring to the assistant chat: the kinds of card they draw,
* the verbs of their change cards and what an applied change of theirs
* touches, beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else.
*/
export const TOUR_CARD_SCHEMAS = [tourRouteCardSchema, tourListCardSchema] as const;
/** addTour, updateTour and importTour sit in the core list already. */
/** A station of a city walk checked off on its day: visited, skipped, or the mark taken back. */
export const TOUR_VERB_KEYS = [
'markVisited',
'markSkipped',
'markPlanned',
// A recorded track put on a tour as the way it was done, or taken off it.
'assignTrack',
'unassignTrack',
// A tour left out of the user's activity sums, or counted again.
'excludeTour',
'countTour',
// A tour pointed at its trip's packing list, or let go of it.
'linkPacking',
'unlinkPacking',
// A saved tour turned round or taken back to its start, copied, or its line drawn in another colour.
'reverseTour',
'closeLoop',
'copyTour',
'setRouteColor',
// The writes of a ski or paddle tour of its own, and a planned import taken back to its recording.
'classifySki',
'setPaddlePlan',
'decideObstacles',
'restoreTrack',
// A found place taken into a saved tour as a stop, or taken out again (P6).
'addTourStop',
'removeTourStop',
] as const;
/** 'tour' is a core entity already. */
export const TOUR_APPLIED_ENTITIES = [] as const;
@@ -0,0 +1,65 @@
import { idSchema } from '../../common/primitives.schema';
import { cardClockSchema, cardDateSchema, cardHexColorSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* Public transport connections between two places: the ones a search found,
* or the one a held create_transit_journey adds. Clocks are the local time
* at each stop as the provider wrote it; a connection that lands on a later
* day says by how many (`endDayOffset`).
*/
/** The connections a card lists; the rest are counted in `more`. */
export const TRANSIT_CARD_ITINERARIES_MAX = 4;
/** The legs of one connection a card lists. */
export const TRANSIT_CARD_LEGS_MAX = 12;
const seconds = z.number().min(0).max(1e7);
const transitCardStopSchema = z.object({
name: cardText(80),
time: cardClockSchema.nullable(),
track: cardText(12).nullable(),
});
export const transitCardItinerarySchema = z.object({
date: cardDateSchema,
start: cardClockSchema,
end: cardClockSchema,
endDayOffset: z.number().int().min(0).max(3),
durationS: seconds,
transfers: z.number().int().min(0).max(20),
walkS: seconds,
legs: z
.array(
z.object({
mode: z.string().regex(/^[A-Z_]{1,40}$/),
line: cardText(20).nullable(),
lineColor: cardHexColorSchema.nullable(),
lineTextColor: cardHexColorSchema.nullable(),
from: transitCardStopSchema,
to: transitCardStopSchema,
durationS: seconds,
stops: z.number().int().min(0).max(500),
headsign: cardText(80).nullable(),
agency: cardText(60).nullable(),
}),
)
.min(1)
.max(TRANSIT_CARD_LEGS_MAX),
});
export const transitCardSchema = z.object({
kind: z.literal('transit'),
from: cardText(80),
to: cardText(80),
// The day a held journey is added to; null for a search.
dayId: idSchema.nullable(),
itineraries: z.array(transitCardItinerarySchema).min(1).max(TRANSIT_CARD_ITINERARIES_MAX),
more: z.number().int().min(0).max(100),
// Connections the provider offered that could not be checked, so none of them is shown.
dropped: z.number().int().min(0).max(100),
});
export type TransitCard = z.infer<typeof transitCardSchema>;
export type TransitCardItinerary = z.infer<typeof transitCardItinerarySchema>;
@@ -0,0 +1,39 @@
import { storedTrekCardSchema, trekCardSchema } from './index';
import { tripChatCardSchema } from './trip-chat.card';
import { describe, expect, it } from 'vitest';
const card = {
kind: 'tripChat',
trip: { id: 5, title: 'Tokyo 2026', startDate: '2026-11-02', endDate: '2026-11-12', phase: 'next', placeCount: 34 },
question: 'What is still missing on day 3?',
} as const;
describe('tripChatCardSchema', () => {
it('TRIPCHAT-001: is part of the card union and reads as itself', () => {
expect(trekCardSchema.parse(card)).toEqual(card);
expect(storedTrekCardSchema.parse(card)).toEqual(card);
});
it('TRIPCHAT-002: takes a trip without dates, places or a question', () => {
const bare = {
kind: 'tripChat',
trip: { id: 9, title: 'Someday', startDate: null, endDate: null, phase: 'undated', placeCount: null },
question: null,
};
expect(tripChatCardSchema.parse(bare)).toEqual(bare);
});
it('TRIPCHAT-003: refuses an unknown phase, a bad date, an empty title or an overlong question', () => {
expect(tripChatCardSchema.safeParse({ ...card, trip: { ...card.trip, phase: 'soon' } }).success).toBe(false);
expect(tripChatCardSchema.safeParse({ ...card, trip: { ...card.trip, startDate: '2.11.2026' } }).success).toBe(
false,
);
expect(tripChatCardSchema.safeParse({ ...card, trip: { ...card.trip, title: '' } }).success).toBe(false);
expect(tripChatCardSchema.safeParse({ ...card, question: 'x'.repeat(501) }).success).toBe(false);
});
it('TRIPCHAT-004: a stored card with a broken trip is left out, not the message around it', () => {
expect(storedTrekCardSchema.parse({ ...card, trip: { id: 0 } })).toBeNull();
});
});
@@ -0,0 +1,30 @@
import { idSchema } from '../../common/primitives.schema';
import { cardCountSchema, cardDateSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* A trip the chat outside any one trip offers to go on with in that trip's own
* chat: the conversation there knows the trip's days and places and can change
* them, which the chat on the dashboard does not. The question is what the
* user asked about the trip, handed over so it waits there ready to send.
*/
/** Where the trip stands today: under way, the next one to start, later, behind, or without dates. */
export const TRIP_CHAT_PHASES = ['now', 'next', 'upcoming', 'past', 'undated'] as const;
export type TripChatPhase = (typeof TRIP_CHAT_PHASES)[number];
export const tripChatCardSchema = z.object({
kind: z.literal('tripChat'),
trip: z.object({
id: idSchema,
title: cardText(200),
startDate: cardDateSchema.nullable(),
endDate: cardDateSchema.nullable(),
phase: z.enum(TRIP_CHAT_PHASES),
placeCount: cardCountSchema.nullable(),
}),
/** The question to ask in the trip's chat, in the user's words; null when there is none to hand over. */
question: cardText(500).nullable(),
});
export type TripChatCard = z.infer<typeof tripChatCardSchema>;
@@ -0,0 +1,88 @@
import { ASSISTANT_CHANGE_VERB_KEYS, assistantAppliedSchema } from '../assistant.schema';
import { storedTrekCardSchema, trekCardSchema } from './index';
import { VACAY_CARD_MAX_DATES, VACAY_CARD_MAX_DAYS, vacayCardSchema, type VacayCard } from './vacay.card';
import { VACAY_APPLIED_ENTITIES, VACAY_VERB_KEYS } from './vacay.contract';
import { describe, expect, it } from 'vitest';
/** A change card of one day off, as the server builds it. */
const card = (): VacayCard => ({
kind: 'vacay',
months: [{ year: 2026, month: 10 }],
weekStart: 1,
weekendDays: [0, 6],
people: [{ id: 7, name: 'Ana', avatarKey: null, color: '#6366f1' }],
days: [{ date: '2026-10-26', personId: 7, fraction: 1, kind: 'vacation' }],
company: [{ date: '2026-10-30', fraction: 0.5 }],
holidays: [{ date: '2026-10-03', name: 'Tag der Deutschen Einheit', color: null }],
tripDates: ['2026-10-27'],
proposal: {
date: '2026-10-27',
personId: 7,
kind: 'vacation',
fraction: 1,
outcome: 'add',
before: null,
periodYear: 2026,
notes: [],
deltas: [{ personId: 7, year: 2026, days: 1 }],
},
balances: [
{
personId: 7,
year: 2026,
total: 30,
used: 12.5,
comp: 0,
totalAfter: null,
windowStart: '2026-01-01',
windowEnd: '2027-01-01',
},
],
otherDays: 0,
});
describe('the vacation card', () => {
it('VACAYCARD-001: a change card and an answer card read as themselves in the union', () => {
expect(trekCardSchema.parse(card())).toEqual(card());
const answer = { ...card(), proposal: null, months: [] };
expect(storedTrekCardSchema.parse(answer)).toEqual(answer);
});
it('VACAYCARD-002: a colour that is no hex, half a half day or an outcome it does not know reads as no card', () => {
const people = [{ id: 7, name: 'Ana', avatarKey: null, color: 'url(x)' }];
expect(storedTrekCardSchema.parse({ ...card(), people })).toBeNull();
const days = [{ date: '2026-10-26', personId: 7, fraction: 0.25, kind: 'vacation' }];
expect(storedTrekCardSchema.parse({ ...card(), days })).toBeNull();
const proposal = { ...card().proposal, outcome: 'swap' };
expect(storedTrekCardSchema.parse({ ...card(), proposal })).toBeNull();
});
it('VACAYCARD-003: the lists are bounded, and a field a later build adds is dropped on read', () => {
const many = Array.from({ length: VACAY_CARD_MAX_DAYS + 1 }, () => card().days[0]);
expect(vacayCardSchema.safeParse({ ...card(), days: many }).success).toBe(false);
const months = Array.from({ length: 4 }, () => ({ year: 2026, month: 1 }));
expect(vacayCardSchema.safeParse({ ...card(), months }).success).toBe(false);
// Three long months of trip days and company holidays fit; one date more does not.
const dates = (count: number) => Array.from({ length: count }, () => '2026-10-27');
expect(vacayCardSchema.safeParse({ ...card(), tripDates: dates(VACAY_CARD_MAX_DATES) }).success).toBe(true);
expect(vacayCardSchema.safeParse({ ...card(), tripDates: dates(VACAY_CARD_MAX_DATES + 1) }).success).toBe(false);
const company = dates(VACAY_CARD_MAX_DATES).map((date) => ({ date, fraction: 1 }));
expect(vacayCardSchema.safeParse({ ...card(), company }).success).toBe(true);
expect(storedTrekCardSchema.parse({ ...card(), later: true })).toEqual(card());
});
it('VACAYCARD-005: the carried-over days and the year asked for are optional, so older cards still read', () => {
const balances = [{ ...card().balances[0], carried: 2 }];
expect(vacayCardSchema.parse({ ...card(), balances, year: 2026 })).toMatchObject({ balances, year: 2026 });
expect(vacayCardSchema.safeParse({ ...card(), year: 1999 }).success).toBe(false);
const proposal = { ...card().proposal, kind: 'company', personId: null, notes: ['companyOff'] };
expect(vacayCardSchema.safeParse({ ...card(), proposal }).success).toBe(true);
});
it('VACAYCARD-004: its verbs and its entity join the shared enums', () => {
for (const verb of VACAY_VERB_KEYS) expect(ASSISTANT_CHANGE_VERB_KEYS).toContain(verb);
const applied = { toolCallId: 'c1', entity: VACAY_APPLIED_ENTITIES[0], ids: [], dayId: null, undoUntil: null };
expect(assistantAppliedSchema.parse(applied).entity).toBe('vacay');
});
});
+129
View File
@@ -0,0 +1,129 @@
import { idSchema } from '../../common/primitives.schema';
import { cardDateSchema, cardHexColorSchema, cardPersonSchema, cardText } from './card-parts';
import { z } from 'zod';
/**
* Vacation days on a month calendar, with the days left. An answer card shows
* what a read found (the days off of a year, the days left, the public
* holidays); a change card shows the one day a held write would take or give
* back, on its month, with the leave before it. The people are the vacation
* plan's, which need not be the trip's: a fused plan holds partners too.
*/
const fractionSchema = z.union([z.literal(0.5), z.literal(1)]);
const yearSchema = z.number().int().min(2000).max(2100);
/** Days are counted in halves, so a count is a multiple of 0.5. */
const daysSchema = z.number().min(0).max(1000);
/** What a day off is: leave that counts, a comp day that does not, or a holiday the company gives everyone. */
export const VACAY_DAY_KINDS = ['vacation', 'comp', 'company'] as const;
/** What a held toggle would do to its day. */
export const VACAY_PROPOSAL_OUTCOMES = ['add', 'remove', 'convert', 'blocked'] as const;
/** What a held toggle should know about its day before it is applied. */
export const VACAY_PROPOSAL_NOTES = [
'weekendBlocked',
'weekend',
'publicHoliday',
'companyHoliday',
'companyHalf',
'notInPlan',
'companyOff',
] as const;
/** Someone of the vacation plan: their own colour colours their days. */
export const vacayCardPersonSchema = cardPersonSchema.extend({ color: cardHexColorSchema.nullable() });
/** A logged day off of one person. */
export const vacayCardDaySchema = z.object({
date: cardDateSchema,
personId: idSchema,
fraction: fractionSchema,
kind: z.enum(['vacation', 'comp']),
});
/** A public holiday, in its calendar's colour when the plan has one. */
export const vacayCardHolidaySchema = z.object({
date: cardDateSchema,
name: cardText(80),
color: cardHexColorSchema.nullable(),
});
/** The day a held write would change, and what that does to the days left. */
export const vacayCardProposalSchema = z.object({
date: cardDateSchema,
/** Null for a company holiday, which is the whole plan's. */
personId: idSchema.nullable(),
kind: z.enum(VACAY_DAY_KINDS),
fraction: fractionSchema,
outcome: z.enum(VACAY_PROPOSAL_OUTCOMES),
/** What the day was before, when it was logged already. */
before: z.object({ fraction: fractionSchema, kind: z.enum(VACAY_DAY_KINDS) }).nullable(),
/** The leave year the day counts in, which runs from the person's own start day. */
periodYear: yearSchema.nullable(),
notes: z.array(z.enum(VACAY_PROPOSAL_NOTES)).max(VACAY_PROPOSAL_NOTES.length),
/** The change to each person's used days in a leave year; a company holiday can give several people days back. */
deltas: z.array(z.object({ personId: idSchema, year: yearSchema, days: z.number().min(-1).max(1) })).max(8),
});
/** One person's leave in one leave year, as it stands before the change. */
export const vacayCardBalanceSchema = z.object({
personId: idSchema,
year: yearSchema,
/** The allowance with what was carried over. */
total: daysSchema,
/** What was carried over into the year, so the allowance alone is `total - carried`; absent on older cards. */
carried: daysSchema.optional(),
used: daysSchema,
comp: daysSchema,
/** The new total a change of the allowance would give; null for anything else. */
totalAfter: daysSchema.nullable(),
windowStart: cardDateSchema,
windowEnd: cardDateSchema,
});
/**
* The bounds keep the heaviest card (three busy months of a plan of eight)
* under MAX_CARD_CHARS; the server keeps the days of the months it shows
* first and drops the rest.
*/
export const VACAY_CARD_MAX_DAYS = 150;
export const VACAY_CARD_MAX_HOLIDAYS = 30;
/** Every date of the three months a card shows at most: the trip days and the company holidays. */
export const VACAY_CARD_MAX_DATES = 93;
export const vacayCardSchema = z.object({
kind: z.literal('vacay'),
/** The months the calendar shows, in order; none for a card of days left only. */
months: z.array(z.object({ year: yearSchema, month: z.number().int().min(1).max(12) })).max(3),
/** The first column: 0 for Sunday, 1 for Monday. */
weekStart: z.union([z.literal(0), z.literal(1)]),
/** The weekdays that count as weekend, 0 for Sunday. */
weekendDays: z.array(z.number().int().min(0).max(6)).max(7),
people: z.array(vacayCardPersonSchema).max(8),
/** The logged days inside `months`. */
days: z.array(vacayCardDaySchema).max(VACAY_CARD_MAX_DAYS),
company: z.array(z.object({ date: cardDateSchema, fraction: fractionSchema })).max(VACAY_CARD_MAX_DATES),
holidays: z.array(vacayCardHolidaySchema).max(VACAY_CARD_MAX_HOLIDAYS),
/** The dated days of this trip inside `months`. */
tripDates: z.array(cardDateSchema).max(VACAY_CARD_MAX_DATES),
/** A change card's one day; null on an answer. */
proposal: vacayCardProposalSchema.nullable(),
balances: z.array(vacayCardBalanceSchema).max(8),
/** The days off of the signed-in user in the year outside `months`. */
otherDays: daysSchema,
/** The leave year a read of the days off asked for, which Vacay opens on; absent elsewhere. */
year: yearSchema.optional(),
});
export type VacayCard = z.infer<typeof vacayCardSchema>;
export type VacayCardPerson = z.infer<typeof vacayCardPersonSchema>;
export type VacayCardDay = z.infer<typeof vacayCardDaySchema>;
export type VacayCardHoliday = z.infer<typeof vacayCardHolidaySchema>;
export type VacayCardProposal = z.infer<typeof vacayCardProposalSchema>;
export type VacayCardBalance = z.infer<typeof vacayCardBalanceSchema>;
export type VacayProposalNote = (typeof VACAY_PROPOSAL_NOTES)[number];
export type VacayProposalOutcome = (typeof VACAY_PROPOSAL_OUTCOMES)[number];
export type VacayDayKind = (typeof VACAY_DAY_KINDS)[number];
@@ -0,0 +1,22 @@
import { vacayCardSchema } from './vacay.card';
export * from './vacay.card';
/**
* What the vacation planner brings to the assistant chat: the kinds of card it draws,
* the verbs of its change cards and what an applied change of its
* touches, beyond the core ones. cards/index.ts and assistant.schema.ts
* spread these into the card union and the shared enums, so a new kind, verb
* or entity is added here and nowhere else.
*/
export const VACAY_CARD_SCHEMAS = [vacayCardSchema] as const;
/** A day off taken, given back or changed, a company holiday set, the allowance changed. */
export const VACAY_VERB_KEYS = [
'addVacationDay',
'removeVacationDay',
'changeVacationDay',
'setCompanyHoliday',
'setVacationAllowance',
] as const;
/** A day or the allowance of the vacation plan: the receipt opens the vacation planner. */
export const VACAY_APPLIED_ENTITIES = ['vacay'] as const;
+16
View File
@@ -33,6 +33,22 @@ describe('markRegionRequestSchema', () => {
});
describe('createBucketItemRequestSchema', () => {
it('accepts a region of the item country and refuses any other (#1901)', () => {
expect(
createBucketItemRequestSchema.safeParse({ name: 'Bayern', country_code: 'DE', region_code: 'DE-BY' }).success,
).toBe(true);
expect(
createBucketItemRequestSchema.safeParse({ name: 'Bayern', country_code: 'de', region_code: 'de-by' }).success,
).toBe(true);
expect(
createBucketItemRequestSchema.safeParse({ name: 'Berlin', country_code: 'FR', region_code: 'DE-BE' }).success,
).toBe(false);
expect(createBucketItemRequestSchema.safeParse({ name: 'Berlin', region_code: 'DE-BE' }).success).toBe(false);
expect(
createBucketItemRequestSchema.safeParse({ name: 'X', country_code: 'DE', region_code: 'not a code' }).success,
).toBe(false);
});
it('requires a name; coordinates and metadata optional/nullable', () => {
expect(createBucketItemRequestSchema.safeParse({ name: 'Tokyo' }).success).toBe(true);
expect(
+23 -8
View File
@@ -21,14 +21,29 @@ export const markRegionRequestSchema = z.object({
});
export type MarkRegionRequest = z.infer<typeof markRegionRequestSchema>;
export const createBucketItemRequestSchema = z.object({
name: z.string().min(1),
lat: z.number().nullable().optional(),
lng: z.number().nullable().optional(),
country_code: z.string().nullable().optional(),
notes: z.string().nullable().optional(),
target_date: z.string().nullable().optional(),
});
export const createBucketItemRequestSchema = z
.object({
name: z.string().min(1),
lat: z.number().nullable().optional(),
lng: z.number().nullable().optional(),
country_code: z.string().nullable().optional(),
notes: z.string().nullable().optional(),
target_date: z.string().nullable().optional(),
// A state or province wished for (#1901), ISO 3166-2 like "DE-BY". It belongs to
// the item's country, so it comes with one and starts with it.
region_code: z
.string()
.max(12)
.regex(/^[A-Za-z]{2}-[A-Za-z0-9]{1,8}$/)
.nullable()
.optional(),
})
.refine(
(b) =>
!b.region_code ||
(!!b.country_code && b.region_code.toUpperCase().startsWith(`${b.country_code.toUpperCase()}-`)),
{ message: 'region_code must belong to country_code', path: ['region_code'] },
);
export type CreateBucketItemRequest = z.infer<typeof createBucketItemRequestSchema>;
export const updateBucketItemRequestSchema = z.object({
+47
View File
@@ -0,0 +1,47 @@
import { passwordProblem, passwordRuleStates, validatePassword, PASSWORD_RULES } from './password-policy';
import { describe, expect, it } from 'vitest';
describe('password policy (#1200)', () => {
it('names each rule a password meets', () => {
expect(passwordRuleStates('')).toEqual({ length: false, upper: false, lower: false, digit: false, special: false });
expect(passwordRuleStates('Abcdefg1!')).toEqual({
length: true,
upper: true,
lower: true,
digit: true,
special: true,
});
expect(passwordRuleStates('abcdefgh')).toMatchObject({
length: true,
upper: false,
lower: true,
digit: false,
special: false,
});
expect(PASSWORD_RULES).toEqual(['length', 'upper', 'lower', 'digit', 'special']);
});
it('reports the first problem in the order the server checks', () => {
expect(passwordProblem('Ab1!')).toBe('tooShort');
expect(passwordProblem('aaaaaaaaaa')).toBe('repetitive');
expect(passwordProblem('Passw0rd')).toBe('common');
expect(passwordProblem('abcdefgh1')).toBe('weak');
expect(passwordProblem('Abcdefg1!')).toBeNull();
});
it('keeps the reasons the API has always answered with', () => {
expect(validatePassword('Ab1!')).toEqual({ ok: false, reason: 'Password must be at least 8 characters' });
expect(validatePassword('aaaaaaaaaa')).toEqual({ ok: false, reason: 'Password is too repetitive' });
expect(validatePassword('changeme')).toEqual({
ok: false,
reason: 'Password is too common. Please choose a unique password.',
});
expect(validatePassword('abcdefgh1')).toEqual({
ok: false,
reason:
'Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character',
});
expect(validatePassword('Abcdefg1!')).toEqual({ ok: true });
});
});
+79
View File
@@ -0,0 +1,79 @@
/**
* The password policy, one copy for the server that enforces it and the forms
* that check it while the user types (#1200). A rule changed here changes in
* both places at once; a hand-kept copy in the client would drift.
*/
export const PASSWORD_MIN_LENGTH = 8;
const COMMON_PASSWORDS = new Set([
'password',
'12345678',
'123456789',
'1234567890',
'password1',
'qwerty123',
'iloveyou',
'admin123',
'letmein12',
'welcome1',
'monkey123',
'dragon12',
'master12',
'qwerty12',
'abc12345',
'trustno1',
'baseball',
'football',
'shadow12',
'michael1',
'jennifer',
'superman',
'abcdefgh',
'abcd1234',
'password123',
'admin1234',
'changeme',
'welcome123',
'passw0rd',
'p@ssword',
]);
/** The rules a form lists under a new password, each one met or not. */
export const PASSWORD_RULES = ['length', 'upper', 'lower', 'digit', 'special'] as const;
export type PasswordRule = (typeof PASSWORD_RULES)[number];
export function passwordRuleStates(password: string): Record<PasswordRule, boolean> {
return {
length: password.length >= PASSWORD_MIN_LENGTH,
upper: /[A-Z]/.test(password),
lower: /[a-z]/.test(password),
digit: /[0-9]/.test(password),
special: /[^A-Za-z0-9]/.test(password),
};
}
/** Why a password is refused, as a code a form can translate; null when it passes. */
export type PasswordProblem = 'tooShort' | 'repetitive' | 'common' | 'weak';
export function passwordProblem(password: string): PasswordProblem | null {
if (password.length < PASSWORD_MIN_LENGTH) return 'tooShort';
if (/^(.)\1+$/.test(password)) return 'repetitive';
if (COMMON_PASSWORDS.has(password.toLowerCase())) return 'common';
const rules = passwordRuleStates(password);
if (!rules.upper || !rules.lower || !rules.digit || !rules.special) return 'weak';
return null;
}
const SERVER_REASONS: Record<PasswordProblem, string> = {
tooShort: 'Password must be at least 8 characters',
repetitive: 'Password is too repetitive',
common: 'Password is too common. Please choose a unique password.',
weak: 'Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character',
};
/** The server's answer: the same checks, with the English reasons the API has always sent. */
export function validatePassword(password: string): { ok: boolean; reason?: string } {
const problem = passwordProblem(password);
return problem ? { ok: false, reason: SERVER_REASONS[problem] } : { ok: true };
}
+302
View File
@@ -0,0 +1,302 @@
import { compareCodeUnits } from '../../common/compare';
import { formatBookDate } from '../book-text';
import {
MAX_PATH_POINTS,
MAX_PATH_SEGMENTS,
MAX_SPREAD_ELEMENTS,
type BookElement,
type BookMetric,
type BookSpread,
} from '../book.schema';
import type { JourneyStats } from '../journey-stats.schema';
import {
ACCENT,
badgeEl,
bleedFrame,
countriesEl,
mapEl,
photo,
shape,
statsEl,
text,
type NewId,
} from './auto-elements';
import type { AutoEntry, AutoInput } from './auto-types';
/**
* The pages of a book that are not one entry's: the cover, the list of bare
* stops, the journey at a glance, the countries and the back cover.
*/
/** What one station row costs (its date, its name and the rule under it), and the heading above the list. */
const STATION_ELEMENTS = 3;
const STATIONS_HEADING = 2;
/**
* How many stations one page holds: thirteen is where the type gets too
* tight, and a spread is two of these pages under `MAX_SPREAD_ELEMENTS`.
*/
const ROWS_THE_CAP_ALLOWS = Math.floor((MAX_SPREAD_ELEMENTS - STATIONS_HEADING) / STATION_ELEMENTS / 2);
export const STATIONS_PER_PAGE = Math.min(13, ROWS_THE_CAP_ALLOWS);
/** The span line's printed separator (an em dash), kept as the Studio has always set it. */
const SPAN_JOIN = ' \u2014 ';
export function coverSpread(input: AutoInput, newId: NewId): BookSpread {
const { page } = input;
const m = 18;
const els: BookElement[] = [];
const light = input.coverPhotoId != null;
if (input.coverPhotoId != null) {
els.push(photo(newId, bleedFrame(page, false), input.coverPhotoId, { focalY: 0.42 }));
// A scrim so the title survives whatever the photo does underneath it, faded rather than a flat panel.
const scrim = {
x: -page.bleed,
y: page.pageHeight * 0.38,
w: page.pageWidth + page.bleed * 2,
h: page.pageHeight * 0.62 + page.bleed,
};
els.push(shape(newId, scrim, '#000000', { opacity: 0.72, gradient: 'down' }));
}
const titleStyle = {
size: 34,
weight: 700 as const,
leading: 1.05,
tracking: -0.02,
color: light ? '#ffffff' : '#111111',
binding: { source: 'journey.title' as const },
};
const titleFrame = { x: m, y: page.pageHeight - m - 46, w: page.pageWidth - m * 2, h: 30 };
els.push(text(newId, titleFrame, input.title, titleStyle));
if (input.subtitle) {
const subStyle = {
size: 12,
weight: 400 as const,
color: light ? '#ffffff' : '#444444',
opacity: light ? 0.85 : 1,
binding: { source: 'journey.subtitle' as const },
};
const subFrame = { x: m, y: page.pageHeight - m - 12, w: page.pageWidth - m * 2, h: 8 };
els.push(text(newId, subFrame, input.subtitle, subStyle));
}
const background = input.coverPhotoId != null ? null : '#f4f2ee';
return { id: newId('sp'), role: 'cover', background, elements: els, parked: [], entryId: null };
}
/**
* The stops that had nothing to say, as a list: two columns of date and
* place, which is what an itinerary looks like in every printed travel book.
* Consecutive ones only, so the book stays in the order it happened.
*/
export function stationsSpread(entries: AutoEntry[], input: AutoInput, newId: NewId): BookSpread {
const { page } = input;
const W = page.pageWidth;
const H = page.pageHeight;
const m = 18;
const els: BookElement[] = [];
els.push(shape(newId, { x: m, y: m + 12, w: 14, h: 0.5 }, ACCENT));
const headStyle = { size: 8, weight: 600 as const, tracking: 0.16, color: '#8a8578' };
els.push(text(newId, { x: m, y: m + 18, w: W - m * 2, h: 8 }, input.stationsLabel.toUpperCase(), headStyle));
const columns = [entries.slice(0, STATIONS_PER_PAGE), entries.slice(STATIONS_PER_PAGE, STATIONS_PER_PAGE * 2)];
const top = m + 34;
const step = Math.min(13, (H - top - m) / Math.max(1, STATIONS_PER_PAGE));
columns.forEach((column, side) => {
const x = side * W + m;
const w = W - m * 2;
column.forEach((entry, i) => {
const y = top + i * step;
const date = formatBookDate(entry.date, input.locale);
if (date) {
// Set in small caps, so not the journal's words: a bound element has to hold exactly its source.
const dateStyle = { size: 7, weight: 600 as const, tracking: 0.1, color: '#a09a8e' };
els.push(text(newId, { x, y, w: w * 0.32, h: 5 }, date.toUpperCase(), dateStyle));
}
const name = entry.title || entry.location || '';
if (name) {
const nameStyle = {
size: 11,
weight: 600 as const,
color: '#141414',
binding: { source: 'entry.title' as const, entryId: entry.id },
};
els.push(text(newId, { x: x + w * 0.34, y: y - 1.5, w: w * 0.66, h: 7 }, name, nameStyle));
}
// A hairline under each row, the way a printed itinerary rules its lines.
els.push(shape(newId, { x, y: y + step - 4.5, w, h: 0.15 }, '#ddd8cf'));
});
});
return { id: newId('sp'), role: 'inner', background: '#faf8f4', elements: els, parked: [], entryId: null };
}
/** The stop that ended up furthest from the first one. */
function furthestPoint(stats: JourneyStats) {
const home = stats.points[0];
if (!home) return null;
let best = home;
let bestD = 0;
for (const p of stats.points) {
const d = Math.hypot(p.lat - home.lat, (p.lng - home.lng) * Math.cos((home.lat * Math.PI) / 180));
if (d > bestD) {
bestD = d;
best = p;
}
}
return best;
}
/** Metres as the books print them, "1,189 km", in the book's own language. */
function formatKm(metres: number, locale: string): string {
return `${Math.round(metres / 1000).toLocaleString(locale)} km`;
}
/** Which figures are worth the space: everything the journey actually has, at most six. */
export function summaryMetrics(stats: JourneyStats): BookMetric[] {
const all: [BookMetric, number][] = [
['distance', stats.distance],
['days', stats.days],
['steps', stats.steps],
['photos', stats.photos],
['countries', stats.countries.length],
['furthest', stats.furthest],
];
return all
.filter(([, v]) => v > 0)
.map(([k]) => k)
.slice(0, 6);
}
/** The furthest point, drawn: two dots, a line and a distance. */
function furthestMarks(
input: AutoInput,
stats: JourneyStats,
newId: NewId,
at: { x: number; w: number },
): BookElement[] {
const home = stats.points[0];
const far = furthestPoint(stats);
if (!(stats.furthest > 0 && home && far && far !== home)) return [];
const H = input.page.pageHeight;
const y = H - 18 - 26;
const lineW = at.w - 16;
const rx = at.x;
const els: BookElement[] = [shape(newId, { x: rx + 8, y, w: lineW, h: 0.3 }, '#cfc9bd')];
for (const t of [0, 1]) {
const dot = { x: rx + 8 + lineW * t - 1.4, y: y - 1.25, w: 2.8, h: 2.8 };
els.push(shape(newId, dot, t === 0 ? '#8a8578' : ACCENT, { shape: 'ellipse' }));
}
const chip = { x: rx + 8 + lineW * 0.5 - 17, y: y - 11, w: 34, h: 8 };
const km = { text: formatKm(stats.furthest, input.locale) };
els.push(badgeEl(newId, chip, 'distance', km, { style: 'chip', textScale: 0.7 }));
const label = { size: 6.5, weight: 600 as const, tracking: 0.1, color: '#8a8578' };
els.push(text(newId, { x: rx + 4, y: y + 4, w: lineW * 0.5, h: 5 }, (home.label || '').toUpperCase(), label));
const farFrame = { x: rx + 4 + lineW * 0.5, y: y + 4, w: lineW * 0.5 + 4, h: 5 };
els.push(text(newId, farFrame, (far.label || '').toUpperCase(), { ...label, align: 'right' }));
return els;
}
/**
* The journey at a glance: the route drawn on the left, what it came to on the
* right. Omitted rather than left empty when there is nothing to draw.
*/
export function summarySpread(input: AutoInput, newId: NewId): BookSpread | null {
const stats = input.stats;
if (!stats) return null;
// Something has to be worth printing. One stop is a pin, not a journey.
if (stats.points.length < 2 && !stats.distance && !stats.days) return null;
const { page } = input;
const W = page.pageWidth;
const H = page.pageHeight;
const m = 18;
const els: BookElement[] = [];
if (stats.points.length >= 2) {
const path = (input.path ?? []).slice(0, MAX_PATH_SEGMENTS).map((seg) => seg.slice(0, MAX_PATH_POINTS));
els.push(mapEl(newId, { x: m, y: m, w: W - m * 2, h: H - m * 2 }, stats, { path }));
}
const metrics = summaryMetrics(stats);
const rx = W + m;
const colW = W - m * 2;
els.push(shape(newId, { x: rx, y: m + 14, w: colW * 0.16, h: 0.5 }, ACCENT));
const headStyle = { size: 9, weight: 700 as const, tracking: 0.18, color: '#141414' };
els.push(text(newId, { x: rx, y: m + 20, w: colW, h: 7 }, input.summaryLabel.toUpperCase(), headStyle));
if (metrics.length) els.push(statsEl(newId, { x: rx, y: m + 36, w: colW, h: H * 0.42 }, stats, metrics, 'grid'));
els.push(...furthestMarks(input, stats, newId, { x: rx, w: colW }));
return { id: newId('sp'), role: 'inner', background: null, elements: els, parked: [], entryId: null };
}
/** Pale outlines on near-black, names above them: the page people photograph. Two countries or more. */
export function countriesSpread(input: AutoInput, names: string[], newId: NewId): BookSpread | null {
const stats = input.stats;
if (!stats || stats.countries.length < 2) return null;
const { page } = input;
const W = page.pageWidth;
const H = page.pageHeight;
const m = 20;
const rows = stats.countries.length;
// Tall enough to breathe, but never taller than the page it sits on.
const height = Math.min(H - m * 2 - 24, Math.max(H * 0.4, rows * 26));
const ink = '#f2efe9';
const headStyle = { size: 9, weight: 700 as const, tracking: 0.2, align: 'center' as const, color: ink };
const headFrame = { x: W + m, y: m + 16, w: W - m * 2, h: 8 };
const head = text(newId, headFrame, input.countriesLabel.toUpperCase(), headStyle);
const frame = { x: W + m, y: (H - height) / 2 + 10, w: W - m * 2, h: height };
const outlines = countriesEl(newId, frame, stats, names, { color: ink, accent: ink });
return {
id: newId('sp'),
role: 'inner',
background: '#12161d',
elements: [head, outlines],
parked: [],
entryId: null,
};
}
/** The back cover: quiet on purpose, the last thing a reader sees should be a full stop. */
export function backSpread(input: AutoInput, newId: NewId): BookSpread {
const { page } = input;
const m = 18;
const els: BookElement[] = [];
const dates = input.entries
.map((e) => e.date)
.filter((d): d is string => !!d)
.sort(compareCodeUnits);
const first = dates[0];
const last = dates[dates.length - 1];
const ends = first && last ? [formatBookDate(first, input.locale), formatBookDate(last, input.locale)] : [];
const span = ends.filter(Boolean).join(SPAN_JOIN);
els.push(shape(newId, bleedFrame(page, false), '#141414'));
const titleStyle = {
size: 15,
weight: 600 as const,
align: 'center' as const,
color: '#ffffff',
tracking: -0.01,
binding: { source: 'journey.title' as const },
};
const titleFrame = { x: m, y: page.pageHeight * 0.5 - 16, w: page.pageWidth - m * 2, h: 12 };
els.push(text(newId, titleFrame, input.title, titleStyle));
if (span) {
const spanStyle = { size: 8.5, align: 'center' as const, color: '#ffffff', opacity: 0.55 };
els.push(text(newId, { x: m, y: page.pageHeight * 0.5, w: page.pageWidth - m * 2, h: 6 }, span, spanStyle));
}
// The closing tally, as a figures element: it takes its labels from the Studio's translations.
if (input.stats) {
const tally: [BookMetric, number][] = [
['days', input.stats.days],
['places', input.stats.places],
['photos', input.stats.photos],
];
const closing = tally.filter(([, v]) => v > 0).map(([k]) => k);
if (closing.length) {
const quiet = { showIcons: false, color: '#ffffff', accent: '#ffffff', opacity: 0.55, textScale: 0.8 };
const frame = { x: m, y: page.pageHeight * 0.5 + 6, w: page.pageWidth - m * 2, h: 22 };
els.push(statsEl(newId, frame, input.stats, closing, 'row', quiet));
}
}
return { id: newId('sp'), role: 'back', background: '#141414', elements: els, parked: [], entryId: null };
}
+231
View File
@@ -0,0 +1,231 @@
import { bookElementId } from '../book-ids';
import { blankBook, blankSpread } from '../book-pages';
import { MAX_BOOK_TITLE, MAX_SPREADS, type BookDocument, type BookPageSetup, type BookSpread } from '../book.schema';
import type { JourneyStats } from '../journey-stats.schema';
import {
STATIONS_PER_PAGE,
backSpread,
countriesSpread,
coverSpread,
stationsSpread,
summarySpread,
} from './auto-book-spreads';
import { countryNames, isPano, type NewId } from './auto-elements';
import {
bandSpread,
gallerySpread,
immersiveSpread,
panelSpread,
panoSpread,
placeSpread,
storySpread,
type EntryContext,
} from './auto-spreads';
import { applyAutoTemplate, autoTemplateFit } from './auto-template-apply';
import { AUTO_TEMPLATES } from './auto-templates.data';
import type { AutoEntry, AutoInput, AutoPhoto } from './auto-types';
/**
* The auto mode: turn a journey into a book.
*
* The one rule that shapes everything else is that this produces an ordinary
* document. There is no "auto layout" state that locks, no template engine
* that re-runs behind the user's back: it lays the pages out once, and from
* that moment every element is as editable as one dragged in by hand.
*
* Templates are chosen by what the material actually is: how many photos the
* entry has, whether they are portrait or landscape, how much story there is
* to set. Moved here from the Studio (client/src/components/Studio/autoLayout.ts)
* so the Studio and the server's design tool lay a book out the same way;
* `auto-layout.parity.spec.ts` holds the move to the old code's output.
*/
const idsOf = (input: AutoInput): NewId => input.newId ?? bookElementId;
/**
* Whether an entry has anything to fill a spread with. A journey built from a
* trip starts as one skeleton entry per stop: a date, a place name, nothing
* else. Those share a list rather than taking a spread each.
*/
export function autoEntryHasSubstance(entry: AutoEntry): boolean {
return entry.photos.length > 0 || !!(entry.story || '').trim();
}
/**
* A hand-drawn template for this entry, if one of them fits. Tried before the
* layouts written as code: a page somebody designed beats a page a function
* reasoned its way to. Rotated by position so a run of similar entries does
* not come out as a run of identical pages.
*/
function templateSpread(entry: AutoEntry, input: AutoInput, index: number, newId: NewId): BookSpread | null {
const templates = input.templates ?? AUTO_TEMPLATES;
const scored = templates
.map((t) => ({ t, fit: autoTemplateFit(t, entry) }))
.filter((x) => x.fit >= 0)
.sort((a, b) => b.fit - a.fit);
const best = scored[0];
if (!best) return null;
// Everything within a few points of the best is equally suitable, so the position picks between them.
const equals = scored.filter((x) => x.fit >= best.fit - 5);
const pick = equals[index % equals.length] ?? best;
const ctx = { page: input.page, locale: input.locale, stats: input.stats, dayLabel: input.dayLabel, newId };
return applyAutoTemplate(pick.t, entry, ctx);
}
/**
* One entry, one spread: a drawn template when one fits, else one of the
* layouts written as code, by contents first (a panorama wants the fold, a
* stop with nothing said about it wants the place page) and then by position.
* The full-bleed page is kept to every sixth and never the first.
*/
function entrySpread(entry: AutoEntry, input: AutoInput, index: number, newId: NewId): BookSpread {
const hand = index % 2 === 0 ? 'left' : 'right';
const photos = entry.photos.slice(0, 5);
const withPhotos = { ...entry, photos };
const c: EntryContext = { entry: withPhotos, input, index, hand, newId };
const story = (entry.story || '').trim();
const fromTemplate = templateSpread(withPhotos, input, index, newId);
if (fromTemplate) return fromTemplate;
if (photos.length === 0 && !story) return placeSpread(c);
const first = photos[0];
if (first && isPano(first)) return panoSpread(c);
switch (index % 6) {
case 0:
return photos.length > 1 ? gallerySpread(c) : storySpread(c);
case 1:
return panelSpread(c);
case 2:
return photos.length > 2 ? bandSpread(c) : storySpread(c);
case 3:
return photos.length ? immersiveSpread(c) : panelSpread(c);
case 4:
return photos.length > 1 ? bandSpread(c) : panelSpread(c);
default:
return photos.length > 1 ? gallerySpread(c) : storySpread(c);
}
}
/**
* The page setup for a book that opens on a single page: the first page
* inside the covers is page 1 (#2317). Nothing else of the setup is touched.
*/
function withFirstPage(page: BookPageSetup): BookPageSetup {
return { ...page, pageNumbers: { ...page.pageNumbers, startAt: 1 } };
}
/** The spreads the entries make: one each for entries with substance, a shared list for runs of bare ones. */
function entrySpreads(input: AutoInput, newId: NewId): BookSpread[] {
const out: BookSpread[] = [];
let laid = 0;
let run: AutoEntry[] = [];
const flushRun = () => {
for (let i = 0; i < run.length; i += STATIONS_PER_PAGE * 2) {
out.push(stationsSpread(run.slice(i, i + STATIONS_PER_PAGE * 2), input, newId));
}
run = [];
};
for (const entry of input.entries) {
if (autoEntryHasSubstance(entry)) {
flushRun();
out.push(entrySpread(entry, input, laid++, newId));
} else {
run.push(entry);
}
}
flushRun();
return out;
}
/**
* The whole book: the cover, the first page, the journey at a glance and its
* countries (both left out when the journey has nothing to say with them),
* the entries in the order they happened, the last page and the back cover.
*/
export function buildBook(input: AutoInput): BookDocument {
const newId = idsOf(input);
const spreads: BookSpread[] = [coverSpread(input, newId), blankSpread('first', newId)];
const summary = summarySpread(input, newId);
if (summary) spreads.push(summary);
const countries = countriesSpread(input, countryNames(input), newId);
if (countries) spreads.push(countries);
spreads.push(...entrySpreads(input, newId));
spreads.push(blankSpread('last', newId), backSpread(input, newId));
return {
version: 1,
title: input.title.slice(0, MAX_BOOK_TITLE),
page: withFirstPage(input.page),
spreads: spreads.slice(0, MAX_SPREADS),
};
}
/**
* A book nobody has laid out yet: what a journey with no book opens on. The
* layout is offered, not applied; the same blank book `create_book` writes.
*/
export function emptyBook(input: AutoInput): BookDocument {
return blankBook({ title: input.title, page: input.page, newId: idsOf(input) });
}
/**
* Lay one spread out again, from the entry it came from, keeping its id so the
* pages rail does not jump. Null for a spread that has no entry behind it (the
* covers, the summary, anything added by hand): there is nothing to rebuild it
* from, and replacing it with a blank page would be worse than refusing.
*/
export function relayoutSpread(spread: BookSpread, input: AutoInput): BookSpread | null {
if (spread.role !== 'inner' || spread.entryId == null) return null;
const entry = input.entries.find((e) => e.id === spread.entryId);
if (!entry) return null;
const index = input.entries.indexOf(entry);
return { ...entrySpread(entry, input, index < 0 ? 0 : index, idsOf(input)), id: spread.id };
}
/**
* Hand the journey's loose gallery photos to the entries. Photos that already
* sit on an entry stay there; the rest are shared out in order, so a book
* built from a journey whose pictures all live in the gallery still gets
* pictures on its pages.
*/
export function distributeGallery(entries: AutoEntry[], gallery: readonly AutoPhoto[]): AutoEntry[] {
const taken = new Set(entries.flatMap((e) => e.photos.map((p) => p.photoId)));
const loose = gallery.filter((p) => !taken.has(p.photoId));
if (!loose.length || !entries.length) return entries;
const per = Math.max(1, Math.floor(loose.length / entries.length));
let i = 0;
return entries.map((e, idx) => {
if (e.photos.length >= 4) return e;
const want = Math.min(4 - e.photos.length, idx === entries.length - 1 ? loose.length - i : per);
const slice = loose.slice(i, i + Math.max(0, want));
i += slice.length;
return { ...e, photos: [...e.photos, ...slice] };
});
}
/**
* Give every entry what the journey's figures know about its stop: the
* coordinates and country its place resolved to, and which day of the
* journey it is. Matched by date first and by name second, because a day
* usually has one stop and two stops on one day are told apart by name.
*/
export function autoEntriesWithStops(entries: readonly AutoEntry[], stats: JourneyStats | null): AutoEntry[] {
const points = stats?.points ?? [];
const dayCount = stats?.days ?? null;
// Calendar days counted in UTC: a local midnight would lose a day across a change to summer time.
const first = stats?.start ? Date.parse(`${stats.start}T00:00:00Z`) : Number.NaN;
return entries.map((entry) => {
const byDate = points.find((p) => p.date && entry.date && p.date === entry.date);
const point = byDate ?? points.find((p) => p.label && entry.location && p.label === entry.location);
const at = entry.date ? Date.parse(`${entry.date}T00:00:00Z`) : Number.NaN;
const known = Number.isFinite(at) && Number.isFinite(first);
const dayNumber = known ? Math.floor((at - first) / 86_400_000) + 1 : null;
return {
...entry,
lat: point?.lat ?? null,
lng: point?.lng ?? null,
country: point?.country ?? null,
dayNumber: dayNumber && dayNumber > 0 ? dayNumber : null,
dayCount,
};
});
}
+177
View File
@@ -0,0 +1,177 @@
import { bookSpreadSchema, type BookDocument, type BookSpread } from '../book.schema';
import { matchDecoratedTemplate } from '../templates/template-match';
import { bookThemeOf } from '../theme/book-theme';
import { emptyBook } from './auto-book';
import {
AUTO_DEFAULT_THEME,
autoDesignedBook,
autoRelayoutKind,
autoRelayoutSpread,
type AutoDesignedInput,
} from './auto-designed';
import type { AutoPhoto } from './auto-types';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
/** The Studio's Auto layout on the designed templates: the whole book, and one spread again. */
interface Fixture {
input: AutoDesignedInput;
gallery?: AutoPhoto[];
}
const here = (file: string) => fileURLToPath(new URL(file, import.meta.url));
const fixtures = JSON.parse(readFileSync(here('./auto-layout.parity-inputs.json'), 'utf8')) as Record<string, Fixture>;
const fx = fixtures.A as Fixture;
const counter = () => {
let n = 0;
return (p: string) => `${p}-a${++n}`;
};
const input = (): AutoDesignedInput => ({ ...fx.input, gallery: fx.gallery, newId: counter() });
const book = (seed = 1, theme = bookThemeOf('riso')) => autoDesignedBook(emptyBook(input()), input(), { theme, seed });
/** The index of the first page of a kind, or -1. */
const indexOf = (doc: BookDocument, kind: ReturnType<typeof autoRelayoutKind>) =>
doc.spreads.findIndex((s) => autoRelayoutKind(s) === kind);
describe('the Studio auto layout on the designed templates', () => {
it("AUTODES-001: keeps the book's page format and its theme object, one of its own included", () => {
const own = {
...bookThemeOf('postcard'),
id: null,
palette: { ...bookThemeOf('postcard').palette, ink: '#203040' },
};
const start = { ...emptyBook(input()), page: { ...fx.input.page, pageWidth: 200, pageHeight: 250 } };
const doc = autoDesignedBook(start, input(), { theme: own, seed: 3 });
expect(doc.page.pageWidth).toBe(200);
expect(doc.page.pageHeight).toBe(250);
expect(doc.theme).toEqual(own);
expect(autoDesignedBook(null, input()).theme?.id).toBe(AUTO_DEFAULT_THEME);
});
it('AUTODES-002: another seed lays another book, the same seed the same', () => {
const ids = (doc: BookDocument) => doc.spreads.map((s) => matchDecoratedTemplate(s, doc.page)?.id ?? '-').join();
expect(ids(book(1))).toBe(ids(book(1)));
expect([2, 3, 4, 5].some((seed) => ids(book(seed)) !== ids(book(1)))).toBe(true);
});
it("AUTODES-003: this spread keeps the page's id and lays an entry's page on another template than its own and its neighbours'", () => {
const doc = book();
const at = doc.spreads.findIndex(
(s, i) => autoRelayoutKind(s) === 'entry' && matchDecoratedTemplate(doc.spreads[i] as BookSpread, doc.page),
);
const before = doc.spreads[at] as BookSpread;
const next = autoRelayoutSpread(doc, at, input(), { seed: 1 });
expect(next?.id).toBe(before.id);
expect(next?.entryId).toBe(before.entryId);
expect(bookSpreadSchema.safeParse(next).success).toBe(true);
const was = [at - 1, at, at + 1].map(
(i) => doc.spreads[i] && matchDecoratedTemplate(doc.spreads[i] as BookSpread, doc.page)?.id,
);
expect(was).not.toContain(matchDecoratedTemplate(next as BookSpread, doc.page)?.id);
const photos = (s: BookSpread) =>
[...s.elements, ...s.parked].flatMap((e) => (e.kind === 'photo' && e.photoId != null ? [e.photoId] : [])).sort();
expect(photos(next as BookSpread)).toEqual(photos(before));
});
it('AUTODES-004: pressed again and again, an entry page keeps moving on', () => {
let doc = book();
const at = indexOf(doc, 'entry');
const seen = new Set<string>();
for (let n = 0; n < 4; n++) {
const next = autoRelayoutSpread(doc, at, input(), { seed: n });
if (!next) throw new Error('an entry page lays again');
seen.add(matchDecoratedTemplate(next, doc.page)?.id ?? 'composed');
doc = { ...doc, spreads: doc.spreads.map((s, i) => (i === at ? next : s)) };
}
expect(seen.size).toBeGreaterThan(1);
});
it('AUTODES-005: cycles the cover through the covers of its archetype and then its kin', () => {
let doc = book();
const seen: string[] = [];
for (let n = 0; n < 6; n++) {
const next = autoRelayoutSpread(doc, 0, input(), { seed: 1 });
if (!next) throw new Error('the cover lays again');
expect(next.id).toBe(doc.spreads[0]?.id);
seen.push(matchDecoratedTemplate(next, doc.page)?.id ?? '-');
doc = { ...doc, spreads: doc.spreads.map((s, i) => (i === 0 ? next : s)) };
}
expect(new Set(seen).size).toBeGreaterThan(3);
expect(seen.some((id) => id.startsWith('riso-'))).toBe(true);
});
it('AUTODES-006: cycles the summary and the countries through their looks', () => {
const doc = book();
const summary = indexOf(doc, 'summary');
const looks: string[] = [];
let cur = doc;
for (let n = 0; n < 3; n++) {
const next = autoRelayoutSpread(cur, summary, input()) as BookSpread;
const stats = next.elements.find((e) => e.kind === 'stats' && e.metrics.length > 2);
looks.push(stats?.kind === 'stats' ? (stats.look ?? 'classic') : '-');
cur = { ...cur, spreads: cur.spreads.map((s, i) => (i === summary ? next : s)) };
}
expect(new Set(looks).size).toBe(3);
expect(looks).not.toContain('classic');
const countries = indexOf(doc, 'countries');
const again = autoRelayoutSpread(doc, countries, input()) as BookSpread;
const look = (s: BookSpread) => s.elements.flatMap((e) => (e.kind === 'countries' ? [e.look] : []))[0];
expect(look(again)).not.toBe(look(doc.spreads[countries] as BookSpread));
});
it('AUTODES-007: a page the engine did not make is not laid again', () => {
const doc = book();
const back = doc.spreads.findIndex((s) => s.role === 'back');
expect(autoRelayoutSpread(doc, back, input())).toBeNull();
const stations = doc.spreads.findIndex(
(s) => s.role === 'inner' && s.entryId === null && autoRelayoutKind(s) === null,
);
if (stations >= 0) expect(autoRelayoutSpread(doc, stations, input())).toBeNull();
expect(autoRelayoutSpread(doc, 999, input())).toBeNull();
});
it('AUTODES-008: keeps a locked element where it is', () => {
const doc = book();
const at = indexOf(doc, 'entry');
const page = doc.spreads[at] as BookSpread;
const lockedEl = { ...(page.elements[0] as BookSpread['elements'][number]), locked: true };
const locked = { ...page, elements: [lockedEl, ...page.elements.slice(1)] };
const withLock = { ...doc, spreads: doc.spreads.map((s, i) => (i === at ? locked : s)) };
const next = autoRelayoutSpread(withLock, at, input());
expect(next?.elements).toContainEqual(lockedEl);
});
it('AUTODES-009: the whole book keeps a stored page that holds a lock', () => {
const doc = book();
const at = indexOf(doc, 'entry');
const page = doc.spreads[at] as BookSpread;
const locked = { ...page, elements: page.elements.map((e, i) => (i === 0 ? { ...e, locked: true } : e)) };
const again = autoDesignedBook({ ...doc, spreads: doc.spreads.map((s, i) => (i === at ? locked : s)) }, input(), {
theme: doc.theme,
seed: 9,
});
expect(again.spreads).toContainEqual(locked);
});
it('AUTODES-010: an old Auto layout summary is laid again in a new look', () => {
const doc = book();
const summary = indexOf(doc, 'summary');
const old = doc.spreads[summary] as BookSpread;
const classic = {
...old,
elements: old.elements.map((e) => (e.kind === 'stats' ? { ...e, look: undefined } : e)),
} as BookSpread;
const next = autoRelayoutSpread(
{ ...doc, spreads: doc.spreads.map((s, i) => (i === summary ? classic : s)) },
summary,
input(),
);
const looks = next?.elements.flatMap((e) => (e.kind === 'stats' ? [e.look] : []));
expect(looks?.length).toBeGreaterThan(0);
expect(looks?.every((l) => l && l !== 'classic')).toBe(true);
});
});
+225
View File
@@ -0,0 +1,225 @@
import { layoutAroundLocks } from '../book-layout-locks';
import type { BookCountryLook, BookDocument, BookElement, BookSpread, BookStatsLook } from '../book.schema';
import { designBook, templatedSetting, type BookDesignInput, type TemplatedSetting } from '../design/design-book';
import type { BookDesignDirectivesInput } from '../design/design-directives.schema';
import { ARCHETYPE_KIN, type TemplatePickCtx } from '../design/design-template-pick';
import { layEntryPage, type LaidPage, type PageStory } from '../design/design-templated';
import {
COUNTRY_CYCLE,
SUMMARY_CYCLE,
composeTravelCountries,
composeTravelSummary,
coverOnTemplate,
} from '../design/design-templated-framing';
import { decoratedTemplatesFor } from '../templates/template-catalogue';
import { templatePhotoSlots } from '../templates/template-format';
import { matchDecoratedTemplate } from '../templates/template-match';
import { bookThemeOf } from '../theme/book-theme';
import type { BookTheme, BookThemeId } from '../theme/book-theme.schema';
import { isPortrait } from './auto-elements';
import type { AutoEntry, AutoInput, AutoPhoto } from './auto-types';
/**
* The Studio's Auto layout on the designed templates.
*
* "The whole book" is the design engine laying the book on the Studio's
* decorated templates (`designBook` with `layouts: 'templates'`), in the
* book's own theme, keeping every page that holds a locked element. "This
* spread" lays one page again on another template than the one on screen and
* its neighbours: an entry's page on the next best spread for its photos and
* words, the cover on the next cover of its archetype and then of its kin,
* the summary and the countries in their next look. The old Auto layout
* (`buildBook`, `relayoutSpread`) stays as it was, the design engine's
* classic style.
*/
/** The theme a book without one is laid in: calm, linen, serif. */
export const AUTO_DEFAULT_THEME: BookThemeId = 'fabric-classic';
/** The journey as the Studio's Auto layout takes it: the entries with their stops, and the loose gallery. */
export interface AutoDesignedInput extends AutoInput {
gallery?: readonly AutoPhoto[];
}
export interface AutoDesignedOptions {
/** The book's theme, a recoloured one of its own included; the default theme without one. */
theme?: BookTheme | null;
/** Another seed lays another book; the same one the same. */
seed?: number;
}
const designInput = (input: AutoDesignedInput, theme: BookTheme | null | undefined): BookDesignInput => ({
...input,
candidates: [],
photos: [],
theme: theme ?? bookThemeOf(AUTO_DEFAULT_THEME),
});
const directivesOf = (theme: BookTheme | null | undefined, seed: number | undefined): BookDesignDirectivesInput => ({
style: theme?.id ?? AUTO_DEFAULT_THEME,
layouts: 'templates',
keep: 'locked',
...(seed === undefined ? {} : { seed }),
});
/** The whole book laid on the designed templates over the stored one, its page format kept. */
export function autoDesignedBook(
doc: BookDocument | null,
input: AutoDesignedInput,
opts: AutoDesignedOptions = {},
): BookDocument {
const page = doc?.page ?? input.page;
return designBook(doc, designInput({ ...input, page }, opts.theme), directivesOf(opts.theme, opts.seed)).doc;
}
/** What "this spread" can lay again: an entry's page, the cover, the summary, the countries; null for the rest. */
export type AutoRelayoutKind = 'entry' | 'cover' | 'summary' | 'countries';
/** The kind of page a spread of the book is for "this spread", or null for one the engine did not make. */
export function autoRelayoutKind(spread: BookSpread | undefined): AutoRelayoutKind | null {
if (!spread) return null;
if (spread.role === 'cover') return 'cover';
if (spread.role !== 'inner') return null;
if (spread.entryId != null) return 'entry';
const has = (kind: BookElement['kind']) => spread.elements.some((e) => e.kind === kind);
if (has('stats') && has('map')) return 'summary';
if (has('countries') && !has('stats')) return 'countries';
return null;
}
/** The photos a page holds, on it and parked with it, in order. */
function photosOn(spread: BookSpread, entries: readonly AutoEntry[]): AutoPhoto[] {
const known = new Map(entries.flatMap((e) => e.photos.map((p) => [p.photoId, p] as const)));
return [...spread.elements, ...spread.parked].flatMap((e) =>
e.kind === 'photo' && e.photoId != null
? [known.get(e.photoId) ?? { photoId: e.photoId, width: null, height: null }]
: [],
);
}
/** The story a page of this entry sets, and whether it is the whole of it. */
function storyOn(spread: BookSpread, entryId: number): PageStory {
for (const e of spread.elements) {
if (e.kind === 'text' && e.binding?.source === 'entry.story' && e.binding.entryId === entryId && e.text.trim()) {
return { words: e.text, whole: !e.overridden };
}
}
return null;
}
/** The templates of the page before and after this one, never to be laid here. */
function neighbours(doc: BookDocument, index: number): string[] {
return [doc.spreads[index - 1], doc.spreads[index + 1]].flatMap((s) =>
s ? (matchDecoratedTemplate(s, doc.page)?.id ?? []) : [],
);
}
/** Templates tried for a page whose story would be cut, before one that cuts it is taken. */
const STORY_TRIES = 4;
/** An entry's page on the best template but the one on screen and its neighbours'. */
function relayEntry(s: TemplatedSetting, doc: BookDocument, index: number, free: BookSpread): BookSpread | null {
const entry = s.placed.find((e) => e.id === free.entryId);
const own = doc.spreads[index];
if (!entry || !own) return null;
const current = matchDecoratedTemplate(own, doc.page)?.id;
const around = neighbours(doc, index);
const avoid = [...(current ? [current] : []), ...around];
const page = { photos: photosOn(free, s.placed), story: storyOn(free, entry.id), entries: s.placed };
const pick = (more: readonly string[]): TemplatePickCtx => ({
archetype: s.archetype,
page: s.c.page,
theme: s.c.look.theme,
history: around.slice(0, 1),
calm: s.calm,
seed: s.c.directives.seed ?? 0,
key: `relay:${entry.id}`,
avoid: [...avoid, ...more],
});
let laid: LaidPage | null = null;
const tried: string[] = [];
for (let n = 0; n < STORY_TRIES; n++) {
const next = layEntryPage(s.c, entry, page, pick(tried));
laid ??= next;
if (!next.rest || !next.template) {
laid = next;
break;
}
tried.push(next.template.id);
}
if (!laid) return null;
return { ...s.finish(laid.spread, !!laid.template).spread, entryId: entry.id };
}
/** The cover on the next cover template of its archetype, then of its kin, for the photos there are. */
function relayCover(s: TemplatedSetting, doc: BookDocument, index: number, input: AutoDesignedInput) {
const own = doc.spreads[index];
if (!own) return null;
const others = doc.spreads.flatMap((sp) => (sp === own ? [] : photosOn(sp, s.placed)));
const photos = [...new Map([...photosOn(own, s.placed), ...others].map((p) => [p.photoId, p])).values()].slice(0, 8);
const order = [s.archetype, ...ARCHETYPE_KIN[s.archetype]].flatMap((a) => decoratedTemplatesFor('single', a));
const fits = order.filter(
(t) => templatePhotoSlots(t) <= photos.length && (photos.length > 0 || !templatePhotoSlots(t)),
);
if (!fits.length) return null;
const current = matchDecoratedTemplate(own, doc.page)?.id;
const at = fits.findIndex((t) => t.id === current);
// A cover the engine cannot read takes the first of the archetype's, a portrait one for a tall photo first.
const tall = photos[0] && isPortrait(photos[0]) ? fits.find((t) => /-portrait$|^cutout-/.test(t.id)) : undefined;
const tpl = at >= 0 ? fits[(at + 1) % fits.length] : (tall ?? fits[0]);
if (!tpl) return null;
const ownTitle = doc.title !== input.title ? doc.title : undefined;
const words = { title: input.title, subtitle: input.subtitle, ownTitle };
return s.finish(coverOnTemplate(s.c, words, { photos, entries: s.placed }, tpl), true).spread;
}
/** The look after this one in its cycle; the first for a look outside it (the classic one). */
function nextLook<T extends string>(cycle: readonly T[], look: string | undefined): T {
const at = look ? cycle.indexOf(look as T) : -1;
return cycle[(at + 1) % cycle.length] as T;
}
/** The summary or the countries in their next look. */
function relayTravel(s: TemplatedSetting, free: BookSpread, kind: 'summary' | 'countries'): BookSpread | null {
if (kind === 'summary') {
const stats = free.elements.find((e) => e.kind === 'stats' && e.metrics.length > 2);
const look = stats?.kind === 'stats' ? stats.look : undefined;
const next = composeTravelSummary(s.c, nextLook<BookStatsLook>(SUMMARY_CYCLE, look));
return next ? s.finish(next).spread : null;
}
const country = free.elements.find((e) => e.kind === 'countries');
const look = country?.kind === 'countries' ? country.look : undefined;
const next = composeTravelCountries(s.c, nextLook<BookCountryLook>(COUNTRY_CYCLE, look));
return next ? s.finish(next).spread : null;
}
/**
* One page of the book laid again on the designed templates, around its
* locked elements, its id kept: null for a page the engine did not make
* (stops, the first and last page, the back, a page made by hand), or when
* the page and its locks would not fit.
*/
export function autoRelayoutSpread(
doc: BookDocument,
index: number,
input: AutoDesignedInput,
opts: Pick<AutoDesignedOptions, 'seed'> = {},
): BookSpread | null {
const spread = doc.spreads[index];
const kind = autoRelayoutKind(spread);
if (!spread || !kind) return null;
const setting = templatedSetting(
doc,
designInput({ ...input, page: doc.page }, doc.theme),
directivesOf(doc.theme, opts.seed),
);
return layoutAroundLocks(spread, (free) => {
const next =
kind === 'entry'
? relayEntry(setting, doc, index, free)
: kind === 'cover'
? relayCover(setting, doc, index, input)
: relayTravel(setting, free, kind);
return next ? { ...next, id: spread.id } : null;
});
}
+381
View File
@@ -0,0 +1,381 @@
import { bookDateMarkValue, formatBookCoords } from '../book-text';
import {
MAX_BOOK_COUNTRIES,
MAX_COUNTRY_NAME,
MAX_MAP_POINTS,
MAX_MAP_POINT_LABEL,
MAX_TEXT_LENGTH,
type BookElement,
type BookFrame,
type BookMetric,
type BookPageSetup,
type BookSpread,
} from '../book.schema';
import type { JourneyStats } from '../journey-stats.schema';
import type { AutoEntry, AutoInput, AutoPhoto } from './auto-types';
/**
* The parts the auto layout builds its pages from: a text, a picture, a
* shape, the travel elements and the small marks a printed travel page is
* made of. The same parts a person reaches for in the Studio, so what the
* layout produces can be taken apart and rearranged like anything else.
*
* The colours are print ink, not app chrome: a book is printed once and read
* on paper, and the renderer has no theme to ask.
*/
/** Mints an id for an element or a page. */
export type NewId = (prefix: string) => string;
type Of<K extends BookElement['kind']> = Partial<Extract<BookElement, { kind: K }>>;
export const isPortrait = (p: AutoPhoto) => (p.width && p.height ? p.height > p.width * 1.08 : false);
export const isPano = (p: AutoPhoto) => (p.width && p.height ? p.width > p.height * 2 : false);
/** Near-black ink, and the one warm accent the travel marks share. */
const INK = '#1a1a1a';
export const ACCENT = '#c2410c';
/** Near-black with a blue cast, the colour these books lay a page in. */
export const PANEL_INK = '#12161d';
/** Type on a panel, and the paper colour of the quiet pages. */
export const PANEL_TYPE = '#f2efe9';
export const CREAM = '#faf8f4';
export function text(newId: NewId, frame: BookFrame, value: string, opts: Of<'text'> = {}): BookElement {
return {
id: newId('t'),
kind: 'text',
frame,
rotation: 0,
opacity: 1,
locked: false,
text: value.slice(0, MAX_TEXT_LENGTH),
font: 'sans',
size: 11,
weight: 400,
italic: false,
align: 'left',
leading: 1.45,
tracking: 0,
color: INK,
binding: null,
overridden: false,
...opts,
} as BookElement;
}
/**
* A picture, or the place one goes. `photoId` null is an empty frame, which
* the renderer draws as an outline and which takes a photo by drag.
*/
export function photo(newId: NewId, frame: BookFrame, photoId: number | null, opts: Of<'photo'> = {}): BookElement {
return {
id: newId('p'),
kind: 'photo',
frame,
rotation: 0,
opacity: 1,
locked: false,
photoId,
fit: 'cover',
focalX: 0.5,
focalY: 0.5,
radius: 0,
filter: 'none',
mask: null,
frameStyle: 'none',
...opts,
} as BookElement;
}
export function shape(newId: NewId, frame: BookFrame, fill: string | null, opts: Of<'shape'> = {}): BookElement {
return {
id: newId('s'),
kind: 'shape',
frame,
rotation: 0,
opacity: 1,
locked: false,
shape: 'rect',
fill,
gradient: 'none',
stroke: null,
strokeWidth: 0,
radius: 0,
...opts,
} as BookElement;
}
/** What every travel element the layout places starts from: ink, not the app's orange. */
const travelBase = {
rotation: 0,
opacity: 1,
locked: false,
font: 'sans' as const,
color: INK,
accent: INK,
textScale: 1,
stale: false,
};
/** The figures a stats element carries, keyed by metric. */
export function statsValues(stats: JourneyStats): Record<BookMetric, number> {
return {
distance: stats.distance,
days: stats.days,
steps: stats.steps,
photos: stats.photos,
countries: stats.countries.length,
places: stats.places,
furthest: stats.furthest,
};
}
export function statsEl(
newId: NewId,
frame: BookFrame,
stats: JourneyStats,
metrics: BookMetric[],
layout: 'grid' | 'row' | 'column' = 'grid',
opts: Of<'stats'> = {},
): BookElement {
return {
...travelBase,
id: newId('st'),
kind: 'stats',
frame,
metrics,
layout,
showIcons: true,
units: 'metric',
values: statsValues(stats),
...opts,
} as BookElement;
}
export function mapEl(newId: NewId, frame: BookFrame, stats: JourneyStats, opts: Of<'map'> = {}): BookElement {
const points = stats.points.slice(0, MAX_MAP_POINTS).map((pt) => ({
lat: pt.lat,
lng: pt.lng,
label: pt.label.slice(0, MAX_MAP_POINT_LABEL),
photoId: pt.photoId ?? null,
}));
return {
...travelBase,
id: newId('mp'),
kind: 'map',
frame,
style: 'minimal',
showLand: true,
showRoute: true,
showPins: true,
showLabels: false,
// The drawn line: the contract stays plain so old books do not change, and new books look like a book.
routeStyle: 'drawn',
routeArc: 'bow',
routeDash: 'arcs',
pinStyle: 'photo',
countries: stats.countries.slice(0, MAX_BOOK_COUNTRIES).map((c) => c.code),
points,
path: [],
roads: [],
fitPadding: 0.5,
fitToCountries: true,
clip: 'rect',
...opts,
} as BookElement;
}
export function countriesEl(
newId: NewId,
frame: BookFrame,
stats: JourneyStats,
names: string[],
opts: Of<'countries'> = {},
): BookElement {
return {
...travelBase,
id: newId('co'),
kind: 'countries',
frame,
codes: stats.countries.slice(0, MAX_BOOK_COUNTRIES).map((c) => c.code),
names: names.slice(0, MAX_BOOK_COUNTRIES).map((n) => n.slice(0, MAX_COUNTRY_NAME)),
layout: 'list',
showOutline: true,
showFlag: false,
showName: true,
align: 'center',
...opts,
} as BookElement;
}
type AutoBadgeVariant = 'flag' | 'date' | 'day' | 'coords' | 'country' | 'distance';
export function badgeEl(
newId: NewId,
frame: BookFrame,
variant: AutoBadgeVariant,
value: { text?: string; sub?: string; code?: string | null },
opts: Of<'badge'> = {},
): BookElement {
return {
...travelBase,
id: newId('bd'),
kind: 'badge',
frame,
variant,
text: value.text ?? '',
sub: value.sub ?? '',
code: value.code ?? null,
style: 'plain',
// Built by hand rather than parsed, so the contract's defaults do not apply.
autoColor: true,
showIcon: true,
showLabel: true,
autoIconColor: true,
iconColor: INK,
...opts,
} as BookElement;
}
/** A country's flag with its name beside it, the frame cut to the words. */
export function flagRow(newId: NewId, frame: BookFrame, code: string | null, name: string): BookElement | null {
if (!code && !name) return null;
const cut = { ...frame, w: Math.min(frame.w, 14 + name.length * 1.7) };
return badgeEl(newId, cut, 'flag', { text: name.toUpperCase(), code }, { style: 'plain', textScale: 0.85 });
}
/** Where on earth this is, set small under the name. */
export function coordsMark(
newId: NewId,
frame: BookFrame,
lat: number | null | undefined,
lng: number | null | undefined,
): BookElement | null {
if (lat == null || lng == null) return null;
return badgeEl(newId, frame, 'coords', { text: formatBookCoords(lat, lng) }, { style: 'plain', textScale: 0.7 });
}
/**
* The "DAY 5" chip, its words made by `bookDayText`. Small, solid, and the
* only filled shape on most pages.
*/
export function dayChip(newId: NewId, frame: BookFrame, text: string) {
return badgeEl(newId, frame, 'day', { text }, { style: 'chip', textScale: 0.75 });
}
/** A rule along the foot with a dot showing how far into the journey this is. */
export function progressRule(
newId: NewId,
at: { x: number; y: number; w: number },
day: number | null | undefined,
total: number | null | undefined,
): BookElement[] {
if (!day || !total || total < 2) return [];
const { x, y, w } = at;
const t = Math.min(1, Math.max(0, (day - 1) / (total - 1)));
const dot = 2.2;
const dotFrame = { x: x + w * t - dot / 2, y: y - dot / 2 + 0.15, w: dot, h: dot };
return [shape(newId, { x, y, w, h: 0.3 }, '#cfc9bd'), shape(newId, dotFrame, ACCENT, { shape: 'ellipse' })];
}
/** The country's outline, printed pale behind everything else. */
export function countryWatermark(newId: NewId, frame: BookFrame, code: string | null | undefined): BookElement | null {
if (!code) return null;
return {
...travelBase,
id: newId('wm'),
kind: 'countries',
frame,
codes: [code],
names: [''],
layout: 'column',
showOutline: true,
showFlag: false,
showName: false,
align: 'center',
opacity: 0.1,
} as BookElement;
}
/** The stop on a small map of its own, the way an entry page opens: the country whole with a dot in it. */
export function placeMap(
newId: NewId,
frame: BookFrame,
entry: AutoEntry,
stats: JourneyStats | null,
): BookElement | null {
if (entry.lat == null || entry.lng == null) return null;
return {
...travelBase,
id: newId('mp'),
kind: 'map',
frame,
points: [{ lat: entry.lat, lng: entry.lng, label: entry.location ?? '', photoId: null }],
countries: entry.country ? [entry.country] : (stats?.countries.map((c) => c.code) ?? []),
style: 'minimal',
source: 'vector',
tileUrl: '',
attribution: '',
zoom: 5,
// The plain treatment: one dot on a country outline, a bowed casing would be decoration.
routeStyle: 'plain',
routeArc: 'straight',
routeDash: 'solid',
pinStyle: 'dot',
path: [],
roads: [],
fitPadding: 0.5,
fitToCountries: true,
clip: 'rect',
showLand: true,
showRoute: false,
showPins: true,
showLabels: false,
// weight and tripId are left to the schema's defaults when the book is saved, as the client's layout always did;
// the parity fixture pins this output byte for byte.
} as unknown as BookElement;
}
/** The day of the month as a numeral with its month beneath: a mark rather than a line of information. */
export function dateMark(newId: NewId, iso: string | null, locale: string, frame: BookFrame): BookElement | null {
const value = bookDateMarkValue(iso, locale);
return value ? badgeEl(newId, frame, 'date', value, { style: 'stacked' }) : null;
}
/** A full-bleed frame: out past the trim on every side the page is cut on. */
export function bleedFrame(page: BookPageSetup, spread: boolean): BookFrame {
const w = spread ? page.pageWidth * 2 : page.pageWidth;
return { x: -page.bleed, y: -page.bleed, w: w + page.bleed * 2, h: page.pageHeight + page.bleed * 2 };
}
/** The country a stop is in, named in the book's language. */
export function countryOf(entry: AutoEntry, input: AutoInput): string {
if (!entry.country) return '';
const named = input.stats?.countries.find((c) => c.code === entry.country);
try {
return new Intl.DisplayNames([input.locale], { type: 'region' }).of(entry.country) ?? named?.name ?? '';
} catch {
return named?.name ?? '';
}
}
/**
* Country names in the book's language: the API answers in English, and
* `Intl.DisplayNames` is the same CLDR data Atlas uses for regions.
*/
export function countryNames(input: AutoInput): string[] {
const codes = input.stats?.countries ?? [];
let display: Intl.DisplayNames | null = null;
try {
display = new Intl.DisplayNames([input.locale], { type: 'region' });
} catch {
display = null;
}
return codes.map((c) => display?.of(c.code.toUpperCase()) || c.name || c.code.toUpperCase());
}
/** An inner spread made from one entry. */
export function sheet(newId: NewId, els: BookElement[], entry: AutoEntry, background: string): BookSpread {
return { id: newId('sp'), role: 'inner', background, elements: els, parked: [], entryId: entry.id };
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,115 @@
{
"A/stops": "2e748932e79afc89",
"A/empty": "3919f57127dd39a9",
"A/full/head": "e030d61f8d2aa9c5",
"A/full/spread/0": "6036ca6b48d6e248",
"A/full/spread/1": "bf4b62404c36aa0e",
"A/full/spread/2": "688f4ce239f0eb65",
"A/full/spread/3": "3bc5ecd3ad02ad83",
"A/full/spread/4": "6fdb7d865a3534c5",
"A/full/spread/5": "79c58347ba49449c",
"A/full/relayout/5": "f498524e1bd83d73",
"A/full/spread/6": "92fffefa67d34ef2",
"A/full/relayout/6": "b0e25102bc3c6386",
"A/full/spread/7": "97dc9b4c168d097e",
"A/full/relayout/7": "b0f02d030b894d85",
"A/full/spread/8": "9713baa4e2b220cb",
"A/full/relayout/8": "9713baa4e2b220cb",
"A/full/spread/9": "d9543f86494f2314",
"A/full/relayout/9": "d9543f86494f2314",
"A/full/spread/10": "4158ebac72aa2f82",
"A/full/relayout/10": "4158ebac72aa2f82",
"A/full/spread/11": "9095fefd6605bd3a",
"A/full/relayout/11": "9095fefd6605bd3a",
"A/full/spread/12": "c607b733a886819d",
"A/full/relayout/12": "c607b733a886819d",
"A/full/spread/13": "eeb52e441b993de2",
"A/full/relayout/13": "1a69cae26847c6b3",
"A/full/spread/14": "25220218e93c4852",
"A/full/relayout/14": "25220218e93c4852",
"A/full/spread/15": "d23c193b720e5459",
"A/full/spread/16": "2458025780d8cbf3",
"A/full/spread/17": "01c48fbcefa1c067",
"A/plain/head": "e030d61f8d2aa9c5",
"A/plain/spread/0": "6036ca6b48d6e248",
"A/plain/spread/1": "bf4b62404c36aa0e",
"A/plain/spread/2": "688f4ce239f0eb65",
"A/plain/spread/3": "3bc5ecd3ad02ad83",
"A/plain/spread/4": "6fdb7d865a3534c5",
"A/plain/spread/5": "77241c40787fee23",
"A/plain/relayout/5": "dea1552bb3b68330",
"A/plain/spread/6": "71f875eca927c88d",
"A/plain/relayout/6": "a8ee238a620ce6e6",
"A/plain/spread/7": "eb8defdfae4221c7",
"A/plain/relayout/7": "eb8defdfae4221c7",
"A/plain/spread/8": "34f52cbb4583cf5a",
"A/plain/relayout/8": "36678c06b8189638",
"A/plain/spread/9": "18bff409b40a33d1",
"A/plain/relayout/9": "00d3d7a2c6d38d11",
"A/plain/spread/10": "7b58974d5d38a5c0",
"A/plain/relayout/10": "738530d637d0b8b6",
"A/plain/spread/11": "7a3bf522f37acca3",
"A/plain/relayout/11": "539de849990c2012",
"A/plain/spread/12": "746c3194e39f13cb",
"A/plain/relayout/12": "80100245e192c30d",
"A/plain/spread/13": "bf5ded4681177685",
"A/plain/relayout/13": "ae0a4713176adbc9",
"A/plain/spread/14": "5c92185debe40114",
"A/plain/relayout/14": "e1d6c0ad1c25caf0",
"A/plain/spread/15": "d23c193b720e5459",
"A/plain/spread/16": "2458025780d8cbf3",
"A/plain/spread/17": "01c48fbcefa1c067",
"B/stops": "ac515f9a6b3dfd0c",
"B/empty": "1a5f7b789f489fd2",
"B/full/head": "d55061263739b77a",
"B/full/spread/0": "ac843317bb8d097c",
"B/full/spread/1": "bf4b62404c36aa0e",
"B/full/spread/2": "1af653e4557c90b9",
"B/full/spread/3": "b094a0b5aa67b2c0",
"B/full/relayout/3": "c0f3d2e84826b420",
"B/full/spread/4": "8563f01a381c3b8b",
"B/full/spread/5": "2458025780d8cbf3",
"B/full/spread/6": "345c342e7364131e",
"B/plain/head": "d55061263739b77a",
"B/plain/spread/0": "ac843317bb8d097c",
"B/plain/spread/1": "bf4b62404c36aa0e",
"B/plain/spread/2": "1af653e4557c90b9",
"B/plain/spread/3": "7f57a8719bee79ca",
"B/plain/relayout/3": "08b7ac0438ad42e6",
"B/plain/spread/4": "8563f01a381c3b8b",
"B/plain/spread/5": "2458025780d8cbf3",
"B/plain/spread/6": "345c342e7364131e",
"C/stops": "9b6e31f71aa4ba65",
"C/distribute": "acc3f467a2ffd1e8",
"C/empty": "0f842f6edbdcbf6e",
"C/full/head": "0ffba0f701b7ccaa",
"C/full/spread/0": "ee87e9e195e1edde",
"C/full/spread/1": "bf4b62404c36aa0e",
"C/full/spread/2": "b40cfdb0e5bea780",
"C/full/relayout/2": "b40cfdb0e5bea780",
"C/full/spread/3": "8eb39a4e9d726f5e",
"C/full/relayout/3": "8eb39a4e9d726f5e",
"C/full/spread/4": "5a037193ef347c07",
"C/full/relayout/4": "5a037193ef347c07",
"C/full/spread/5": "b6dedb14199ad559",
"C/full/relayout/5": "b6dedb14199ad559",
"C/full/spread/6": "0debcd2babd7ee6b",
"C/full/relayout/6": "0debcd2babd7ee6b",
"C/full/spread/7": "2458025780d8cbf3",
"C/full/spread/8": "13fbd1cbc3c4ab3a",
"C/plain/head": "0ffba0f701b7ccaa",
"C/plain/spread/0": "ee87e9e195e1edde",
"C/plain/spread/1": "bf4b62404c36aa0e",
"C/plain/spread/2": "c02ef3d3190977de",
"C/plain/relayout/2": "c02ef3d3190977de",
"C/plain/spread/3": "43f652c83b8e9a6e",
"C/plain/relayout/3": "43f652c83b8e9a6e",
"C/plain/spread/4": "51e4f11ba222dc88",
"C/plain/relayout/4": "51e4f11ba222dc88",
"C/plain/spread/5": "5d6770cfbb726b8e",
"C/plain/relayout/5": "5d6770cfbb726b8e",
"C/plain/spread/6": "a1562a8d610bee5f",
"C/plain/relayout/6": "a1562a8d610bee5f",
"C/plain/spread/7": "2458025780d8cbf3",
"C/plain/spread/8": "13fbd1cbc3c4ab3a"
}
@@ -0,0 +1,156 @@
import { designBook } from '../design/design-book';
import type { JourneyStats } from '../journey-stats.schema';
import { autoEntriesWithStops, buildBook, distributeGallery, emptyBook, relayoutSpread } from './auto-book';
import type { AutoEntry, AutoInput, AutoPhoto } from './auto-types';
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
/**
* The auto layout moved here from the Studio still lays a journey out exactly
* as the Studio's own copy did.
*
* `auto-layout.parity.json` holds a digest of every result the old client
* functions gave on the three journeys in `auto-layout.parity-inputs.json`:
* every spread of `buildBook` with the drawn templates and with none, every
* entry spread laid out again, the empty book, the gallery shared out, and the
* stops matched to the entries. Taken from the client code before it was
* deleted. Ids the call mints are random and read as `#new`. A deliberate
* change to a layout changes its digests: say so in the change and write the
* new ones.
*/
interface Fixture {
input: AutoInput;
gallery?: AutoPhoto[];
}
const here = (file: string) => fileURLToPath(new URL(file, import.meta.url));
const fixtures = JSON.parse(readFileSync(here('./auto-layout.parity-inputs.json'), 'utf8')) as Record<string, Fixture>;
const expected = JSON.parse(readFileSync(here('./auto-layout.parity.json'), 'utf8')) as Record<string, string>;
function canonical(value: unknown): string {
const walk = (v: unknown, key?: string): unknown => {
if (Array.isArray(v)) return v.map((x) => walk(x));
if (v && typeof v === 'object') {
const o = v as Record<string, unknown>;
return Object.fromEntries(
Object.keys(o)
.sort()
.map((k) => [k, walk(o[k], k)]),
);
}
if (key === 'id' && typeof v === 'string') return '#new';
return v;
};
return JSON.stringify(walk(value));
}
const digest = (v: unknown) => createHash('sha256').update(canonical(v)).digest('hex').slice(0, 16);
/** An entry as the journey has it, before the stops are matched to it. */
const bare = (e: AutoEntry): AutoEntry => ({
id: e.id,
title: e.title,
story: e.story,
location: e.location,
date: e.date,
photos: e.photos,
});
function cases(): Map<string, string> {
const out = new Map<string, string>();
for (const [name, fx] of Object.entries(fixtures)) {
const put = (key: string, v: unknown) => out.set(`${name}/${key}`, digest(v));
put('stops', autoEntriesWithStops(fx.input.entries.map(bare), fx.input.stats));
const entries = fx.gallery ? distributeGallery(fx.input.entries, fx.gallery) : fx.input.entries;
if (fx.gallery) put('distribute', entries);
const input = { ...fx.input, entries };
put('empty', emptyBook(input));
const layouts = (tag: string, templates: AutoInput['templates']) => {
const run = { ...input, templates };
const doc = buildBook(run);
put(`${tag}/head`, { version: doc.version, title: doc.title, page: doc.page, count: doc.spreads.length });
doc.spreads.forEach((s, i) => {
put(`${tag}/spread/${i}`, s);
const again = relayoutSpread(s, run);
if (again) put(`${tag}/relayout/${i}`, again);
});
};
// With the drawn templates, and with none: the layouts written as code.
layouts('full', undefined);
layouts('plain', []);
}
return out;
}
describe('the auto layout moved from the Studio', () => {
const actual = cases();
it('AUTOPAR-001: covers the same cases the client code was measured on', () => {
expect([...actual.keys()].sort()).toEqual(Object.keys(expected).sort());
expect(actual.size).toBeGreaterThan(100);
});
it('AUTOPAR-002: lays out every fixture journey exactly as the client code did', () => {
const differ = [...actual].filter(([key, value]) => expected[key] !== value).map(([key]) => key);
expect(differ).toEqual([]);
});
it('AUTOPAR-003: mints its ids with the function it is given', () => {
let n = 0;
const fx = fixtures.A as Fixture;
const doc = buildBook({ ...fx.input, newId: (p) => `${p}-c${++n}` });
const ids = doc.spreads.flatMap((s) => [s.id, ...s.elements.map((e) => e.id)]);
expect(ids.every((id) => /-c\d+$/.test(id))).toBe(true);
expect(new Set(ids).size).toBe(ids.length);
});
it('AUTOPAR-004: counts the day of an entry in calendar days, a change to summer time between', () => {
const stats: JourneyStats = {
journeyId: 1,
distance: 0,
days: 10,
steps: 1,
photos: 0,
places: 1,
furthest: 0,
countries: [],
points: [],
trips: [],
excluded: [],
start: '2026-03-27',
end: '2026-04-05',
};
const entry: AutoEntry = {
id: 1,
title: 'Spring',
story: null,
location: null,
date: '2026-03-30',
photos: [],
lat: null,
lng: null,
country: null,
dayNumber: null,
dayCount: null,
pros: [],
cons: [],
};
expect(autoEntriesWithStops([entry], stats)[0]).toMatchObject({ dayNumber: 4, dayCount: 10 });
});
it('AUTOPAR-010: the classic design is the Auto layout, page for page', () => {
for (const [name, fx] of Object.entries(fixtures)) {
const input = { ...fx.input, gallery: fx.gallery, candidates: [], photos: [] };
const result = designBook(null, input, { style: 'classic' });
const doc = result.doc;
const head = { version: doc.version, title: doc.title, page: doc.page, count: doc.spreads.length };
expect(digest(head)).toBe(expected[`${name}/full/head`]);
doc.spreads.forEach((s, i) => expect(digest(s)).toBe(expected[`${name}/full/spread/${i}`]));
expect(result.plan.map((r) => r.action).every((a) => a === 'insert')).toBe(true);
}
});
});
+444
View File
@@ -0,0 +1,444 @@
import { formatBookDate } from '../book-text';
import { bookDayText } from '../book-travel';
import type { BookElement, BookSpread } from '../book.schema';
import {
ACCENT,
CREAM,
PANEL_INK,
PANEL_TYPE,
bleedFrame,
coordsMark,
countryOf,
countryWatermark,
dateMark,
dayChip,
flagRow,
isPortrait,
photo,
placeMap,
progressRule,
shape,
sheet,
text,
type NewId,
} from './auto-elements';
import type { AutoEntry, AutoInput, AutoPhoto } from './auto-types';
/**
* ── The entry spreads ────────────────────────────────────────────────────
*
* Seven layouts rather than one, chosen by what the entry actually has and
* alternating as the book goes on. A book where every spread is built the same
* way reads as a template even when each page is fine on its own.
*
* A printed travel book is built out of areas: a page laid solid in ink with
* pale type on it, a band down the outer edge, a picture that overruns the
* panel it sits against, a box ruled around a block of text. The document
* paints in array order, so a panel pushed first is a panel everything else
* lands on.
*/
/** Which page the picture is on. Alternating keeps the book moving. */
type Hand = 'left' | 'right';
export interface EntryContext {
entry: AutoEntry;
input: AutoInput;
/** Position in the book, for alternating the layouts. */
index: number;
hand: Hand;
newId: NewId;
}
/** An entry's photos, read where the caller has already made sure there is a first one. */
const withHero = (photos: AutoPhoto[]) => photos as [AutoPhoto, ...AutoPhoto[]];
const storyOf = (entry: AutoEntry) => (entry.story || '').trim();
/** The date and place line's printed separator (a middle dot), kept as the Studio has always set it. */
const META_JOIN = ' \u00b7 ';
/** A whole page laid in colour, bleeding off its three outer edges. */
function pagePanel(ctx: EntryContext, side: Hand, fill: string): BookElement {
const { page } = ctx.input;
const b = page.bleed;
const frame = {
x: side === 'left' ? -b : page.pageWidth,
y: -b,
w: page.pageWidth + b,
h: page.pageHeight + b * 2,
};
return shape(ctx.newId, frame, fill);
}
/** A band down the outer edge: the cheapest mark that says "designed". */
function edgeBand(ctx: EntryContext, side: Hand, fill: string, width: number): BookElement {
const { page } = ctx.input;
const b = page.bleed;
const frame = {
x: side === 'left' ? -b : page.pageWidth * 2 - width,
y: -b,
w: width + b,
h: page.pageHeight + b * 2,
};
return shape(ctx.newId, frame, fill);
}
interface HeadingStyle {
size?: number;
ink?: string;
muted?: string;
}
/** The heading block: rule, date line, title. Returns where it ended. */
function headingBlock(
ctx: EntryContext,
els: BookElement[],
at: { x: number; y: number; w: number },
opts: HeadingStyle = {},
): number {
const { entry, input, newId } = ctx;
const { x, y, w } = at;
const size = opts.size ?? 22;
const ink = opts.ink ?? '#141414';
const muted = opts.muted ?? '#8a8578';
const heading = entry.title || entry.location || '';
const meta = [formatBookDate(entry.date, input.locale), entry.location].filter(Boolean).join(META_JOIN);
let cy = y;
if (meta || heading) els.push(shape(newId, { x, y: cy - 6, w: Math.min(14, w * 0.18), h: 0.5 }, ACCENT));
if (meta) {
// Two facts run together and upper-cased: neither is bound, since the journal holds neither like this.
const style = { size: 7.5, weight: 600 as const, tracking: 0.14, color: muted };
els.push(text(newId, { x, y: cy, w, h: 5 }, meta.toUpperCase(), style));
cy += 8;
}
if (heading) {
const style = {
size,
weight: 700 as const,
leading: 1.1,
tracking: -0.02,
color: ink,
binding: { source: 'entry.title' as const, entryId: entry.id },
};
els.push(text(newId, { x, y: cy, w, h: size * 0.6 }, heading, style));
cy += size * 0.75;
}
return cy;
}
/** The foot: the day chip above the dot of the rule that says how far in this is. */
function footMarks(ctx: EntryContext, els: BookElement[], at: { x: number; y: number; w: number }): void {
const { entry, input, newId } = ctx;
const { x, y, w } = at;
els.push(...progressRule(newId, at, entry.dayNumber, entry.dayCount));
const day = entry.dayNumber;
const total = entry.dayCount;
if (!day) return;
const t = total && total > 1 ? Math.min(1, Math.max(0, (day - 1) / (total - 1))) : 0;
const cw = 24;
const cx = Math.min(x + w - cw, Math.max(x, x + w * t - cw / 2));
els.push(dayChip(newId, { x: cx, y: y - 11, w: cw, h: 7 }, bookDayText(input.dayLabel, day)));
}
/** The story, bound to the entry, set in a column. */
function storyText(ctx: EntryContext, frame: BookElement['frame'], size: number, leading: number, color: string) {
const binding = { source: 'entry.story' as const, entryId: ctx.entry.id };
return text(ctx.newId, frame, storyOf(ctx.entry), { size, leading, color, binding });
}
/** The country's flag and name, where the entry knows its country. */
function flagOf(ctx: EntryContext, frame: BookElement['frame']): BookElement | null {
return flagRow(ctx.newId, frame, ctx.entry.country ?? null, countryOf(ctx.entry, ctx.input));
}
/**
* A stop, with nothing written about it yet: the country pale behind, the
* name large, the coordinates beneath it, and the picture page waiting as a
* frame.
*/
export function placeSpread(ctx: EntryContext): BookSpread {
const { entry, input, hand, newId } = ctx;
const { page } = input;
const H = page.pageHeight;
const m = 18;
const els: BookElement[] = [];
const photoPage = hand === 'left' ? 0 : page.pageWidth;
const textPage = hand === 'left' ? page.pageWidth : 0;
const tx = textPage + m;
const colW = page.pageWidth - m * 2;
const wm = countryWatermark(newId, { x: tx, y: H * 0.22, w: colW, h: H * 0.4 }, entry.country);
if (wm) els.push(wm);
const flag = flagOf(ctx, { x: tx, y: m + 4, w: colW * 0.7, h: 7 });
if (flag) els.push(flag);
const name = entry.title || entry.location || '';
if (name) {
const style = {
size: 26,
weight: 700 as const,
tracking: -0.02,
color: '#141414',
binding: { source: 'entry.title' as const, entryId: entry.id },
};
els.push(text(newId, { x: tx, y: H * 0.42, w: colW, h: 20 }, name, style));
}
const coords = coordsMark(newId, { x: tx, y: H * 0.42 + 22, w: colW, h: 6 }, entry.lat, entry.lng);
if (coords) els.push(coords);
footMarks(ctx, els, { x: tx, y: H - m - 6, w: colW });
// The picture page: one frame, edge to edge, waiting.
els.push(photo(newId, { x: photoPage + m, y: m, w: page.pageWidth - m * 2, h: H - m * 2 }, null));
return sheet(newId, els, entry, '#faf8f4');
}
/**
* A day that was written about: words on one page, one picture on the other,
* running off three edges and stopping dead on the gutter.
*/
export function storySpread(ctx: EntryContext): BookSpread {
const { entry, input, hand, newId } = ctx;
const { page } = input;
const H = page.pageHeight;
const m = 18;
const els: BookElement[] = [];
const hero = entry.photos[0];
const textPage = hand === 'left' ? page.pageWidth : 0;
const tx = textPage + m;
const colW = page.pageWidth - m * 2;
const onLeft = hand === 'left';
if (hero) {
const frame = {
x: onLeft ? -page.bleed : page.pageWidth,
y: -page.bleed,
w: page.pageWidth + page.bleed,
h: H + page.bleed * 2,
};
els.push(photo(newId, frame, hero.photoId, { focalX: isPortrait(hero) ? 0.5 : 0.55 }));
if (hero.caption) {
const at = { x: (onLeft ? 0 : page.pageWidth) + m, y: H - m - 6, w: page.pageWidth * 0.6, h: 5 };
const style = {
size: 7.5,
weight: 500 as const,
color: '#ffffff',
opacity: 0.9,
binding: { source: 'photo.caption' as const, entryId: entry.id, photoId: hero.photoId },
};
els.push(text(newId, at, hero.caption, style));
}
} else {
// No photograph yet, but the page it will sit on is already the page.
const frame = { x: (onLeft ? 0 : page.pageWidth) + m, y: m, w: page.pageWidth - m * 2, h: H - m * 2 };
els.push(photo(newId, frame, null));
}
// A small map of the stop, top of the text page: the mark that says where.
const map = placeMap(newId, { x: tx, y: m, w: 26, h: 20 }, entry, input.stats);
if (map) els.push(map);
const flag = flagOf(ctx, { x: tx + (map ? 32 : 0), y: m + 6, w: colW - (map ? 32 : 0), h: 7 });
if (flag) els.push(flag);
const cy = headingBlock(ctx, els, { x: tx, y: m + 34, w: colW }, { size: 20 });
const body = { x: tx, y: cy + 3, w: colW, h: H - cy - m - 34 };
if (storyOf(entry)) els.push(storyText(ctx, body, 10, 1.62, '#2a2a2a'));
const mark = dateMark(newId, entry.date, input.locale, { x: tx, y: H - m - 30, w: 26, h: 20 });
if (mark) els.push(mark);
footMarks(ctx, els, { x: tx, y: H - m - 4, w: colW });
return sheet(newId, els, entry, '#ffffff');
}
/** A panorama across the fold, with the day underneath it: the gutter as an asset. */
export function panoSpread(ctx: EntryContext): BookSpread {
const { entry, input, newId } = ctx;
const { page } = input;
const W = page.pageWidth * 2;
const H = page.pageHeight;
const m = 18;
const gut = 6;
const els: BookElement[] = [];
const [hero, ...rest] = withHero(entry.photos);
const band = { x: -page.bleed, y: -page.bleed, w: W + page.bleed * 2, h: H * 0.58 + page.bleed };
els.push(photo(newId, band, hero.photoId));
const cy = headingBlock(ctx, els, { x: m, y: H * 0.58 + 16, w: page.pageWidth - m * 2 }, { size: 18 });
const body = { x: m, y: cy + 2, w: page.pageWidth - m * 2, h: H - cy - m - 12 };
if (storyOf(entry)) els.push(storyText(ctx, body, 10, 1.6, '#2a2a2a'));
const strip = rest.slice(0, 3);
if (strip.length) {
const cw = (page.pageWidth - m * 2 - gut * (strip.length - 1)) / strip.length;
strip.forEach((p, i) => {
const frame = { x: page.pageWidth + m + i * (cw + gut), y: H * 0.58 + 16, w: cw, h: H * 0.26 };
els.push(photo(newId, frame, p.photoId));
});
}
const flag = flagOf(ctx, { x: page.pageWidth + m, y: H - m - 16, w: page.pageWidth - m * 2, h: 7 });
if (flag) els.push(flag);
footMarks(ctx, els, { x: page.pageWidth + m, y: H - m - 4, w: page.pageWidth - m * 2 });
return sheet(newId, els, entry, '#ffffff');
}
/** Several pictures: one large, the rest ruled beneath the words, the way a magazine sets a picture story. */
export function gallerySpread(ctx: EntryContext): BookSpread {
const { entry, input, hand, newId } = ctx;
const { page } = input;
const H = page.pageHeight;
const m = 18;
const gut = 5;
const els: BookElement[] = [];
const [hero, ...rest] = withHero(entry.photos);
const heroOnLeft = hand === 'left';
const heroX = heroOnLeft ? -page.bleed : page.pageWidth;
const textX = (heroOnLeft ? page.pageWidth : 0) + m;
const colW = page.pageWidth - m * 2;
const heroFrame = { x: heroX, y: -page.bleed, w: page.pageWidth + page.bleed, h: H + page.bleed * 2 };
els.push(photo(newId, heroFrame, hero.photoId, { focalX: isPortrait(hero) ? 0.5 : 0.55 }));
const flag = flagOf(ctx, { x: textX, y: m + 2, w: colW, h: 7 });
const cy = headingBlock(ctx, els, { x: textX, y: m + (flag ? 26 : 16), w: colW }, { size: 19 });
if (flag) els.push(flag);
const strip = rest.slice(0, 3);
const stripH = strip.length ? (strip.length === 1 ? H * 0.28 : H * 0.22) : 0;
// The foot carries the rule and the chip, so nothing else may end there.
const footRoom = 22;
if (storyOf(entry)) {
const h = H - cy - m - (stripH ? stripH + 12 : 0) - footRoom;
els.push(storyText(ctx, { x: textX, y: cy + 2, w: colW, h: Math.max(18, h) }, 10, 1.62, '#2a2a2a'));
}
if (strip.length) {
const cw = (colW - gut * (strip.length - 1)) / strip.length;
strip.forEach((p, i) => {
const frame = { x: textX + i * (cw + gut), y: H - m - footRoom - stripH, w: cw, h: stripH };
els.push(photo(newId, frame, p.photoId));
});
}
footMarks(ctx, els, { x: textX, y: H - m - 4, w: colW });
return sheet(newId, els, entry, '#ffffff');
}
/** One picture over the whole sheet, the words set on top of it: the loudest page, used sparingly. */
export function immersiveSpread(ctx: EntryContext): BookSpread {
const { entry, input, newId } = ctx;
const { page } = input;
const W = page.pageWidth * 2;
const H = page.pageHeight;
const m = 20;
const els: BookElement[] = [];
const hero = entry.photos[0];
els.push(photo(newId, bleedFrame(page, true), hero ? hero.photoId : null, { focalY: 0.45 }));
// A panel behind the type: white on an unknown photograph is a coin toss.
const scrim = { x: -page.bleed, y: H * 0.56, w: W + page.bleed * 2, h: H * 0.44 + page.bleed };
els.push(shape(newId, scrim, '#0d0d0f', { gradient: 'up', opacity: 0.72 }));
const light = { size: 24, ink: '#ffffff', muted: '#d8d3ca' };
headingBlock(ctx, els, { x: m, y: H * 0.68, w: page.pageWidth - m * 2 }, light);
const body = { x: page.pageWidth + m, y: H * 0.68, w: page.pageWidth - m * 2, h: H * 0.26 };
if (storyOf(entry)) els.push(storyText(ctx, body, 9.5, 1.6, '#efece6'));
const coords = coordsMark(newId, { x: m, y: H - m - 5, w: page.pageWidth - m * 2, h: 5 }, entry.lat, entry.lng);
if (coords) els.push(coords);
return sheet(newId, els, entry, '#0d0d0f');
}
/**
* A page laid in ink, the picture overrunning it: one page solid, the other a
* photograph, and a second picture crossing the join so the two halves read
* as one sheet.
*/
export function panelSpread(ctx: EntryContext): BookSpread {
const { entry, input, hand, newId } = ctx;
const { page } = input;
const H = page.pageHeight;
const m = 20;
const els: BookElement[] = [];
const [hero, ...rest] = entry.photos;
const panelSide: Hand = hand === 'left' ? 'right' : 'left';
const panelX = panelSide === 'left' ? 0 : page.pageWidth;
const tx = panelX + m;
const colW = page.pageWidth - m * 2;
// The panel first: everything after it lands on top.
els.push(pagePanel(ctx, panelSide, PANEL_INK));
if (hero) {
const frame = {
x: panelSide === 'left' ? page.pageWidth : -page.bleed,
y: -page.bleed,
w: page.pageWidth + page.bleed,
h: H + page.bleed * 2,
};
els.push(photo(newId, frame, hero.photoId, { focalX: isPortrait(hero) ? 0.5 : 0.55 }));
} else {
const frame = { x: (panelSide === 'left' ? page.pageWidth : 0) + m, y: m, w: colW, h: H - m * 2 };
els.push(photo(newId, frame, null));
}
const flag = flagOf(ctx, { x: tx, y: m, w: colW, h: 7 });
if (flag) els.push(flag);
const onPanel = { size: 21, ink: PANEL_TYPE, muted: '#a8a094' };
const cy = headingBlock(ctx, els, { x: tx, y: m + 30, w: colW }, onPanel);
const body = { x: tx, y: cy + 3, w: colW, h: H - cy - m - 46 };
if (storyOf(entry)) els.push(storyText(ctx, body, 9.5, 1.66, '#d9d4cb'));
// A second picture across the fold, half on the panel, pushed last so it sits over both.
const crossing = rest[0];
if (crossing) {
const cw = 62;
const ch = 46;
const frame = { x: page.pageWidth - cw * 0.55, y: H - m - ch - 14, w: cw, h: ch };
els.push(photo(newId, frame, crossing.photoId, { radius: 1 }));
}
footMarks(ctx, els, { x: tx, y: H - m - 4, w: colW });
return sheet(newId, els, entry, CREAM);
}
/**
* A band down the edge, a ruled box, and pictures at two sizes: the quiet
* counterpart to the panel spread. The box makes the words an object on the
* page rather than something poured onto it.
*/
export function bandSpread(ctx: EntryContext): BookSpread {
const { entry, input, hand, newId } = ctx;
const { page } = input;
const H = page.pageHeight;
const m = 20;
const gut = 5;
const els: BookElement[] = [];
const photos = entry.photos;
els.push(edgeBand(ctx, hand, ACCENT, 6));
// The big picture takes most of one page, off the top and the outer edge.
const heroX = hand === 'left' ? 6 : page.pageWidth;
const heroW = page.pageWidth - 6 + (hand === 'left' ? 0 : page.bleed);
const first = photos[0];
if (first) els.push(photo(newId, { x: heroX, y: -page.bleed, w: heroW, h: H * 0.62 }, first.photoId));
else els.push(photo(newId, { x: heroX + m, y: m, w: heroW - m * 2, h: H * 0.5 }, null));
const tx = (hand === 'left' ? page.pageWidth : 0) + m;
const colW = page.pageWidth - m * 2;
const boxY = m + 6;
const boxH = H * 0.52;
// The words in a ruled box, set in from it on every side.
const box = { x: tx, y: boxY, w: colW, h: boxH };
els.push(shape(newId, box, null, { stroke: '#d8d2c6', strokeWidth: 0.3, radius: 1.5 }));
const flag = flagOf(ctx, { x: tx + 8, y: boxY + 8, w: colW - 16, h: 6 });
if (flag) els.push(flag);
const cy = headingBlock(ctx, els, { x: tx + 8, y: boxY + 30, w: colW - 16 }, { size: 18 });
const body = { x: tx + 8, y: cy + 2, w: colW - 16, h: boxY + boxH - cy - 12 };
if (storyOf(entry)) els.push(storyText(ctx, body, 9.5, 1.6, '#2a2a2a'));
// Two smaller pictures under the box, and one that overlaps the hero above.
const rest = photos.slice(1, 3);
if (rest.length) {
const cw = (colW - gut * (rest.length - 1)) / rest.length;
rest.forEach((ph, i) => {
const frame = { x: tx + i * (cw + gut), y: boxY + boxH + 10, w: cw, h: H * 0.2 };
els.push(photo(newId, frame, ph.photoId, { radius: 1 }));
});
}
const overlap = photos[3];
const inset = { x: heroX + 14, y: H * 0.62 - 26, w: 52, h: 40 };
if (overlap) els.push(photo(newId, inset, overlap.photoId, { radius: 1 }));
const mark = dateMark(newId, entry.date, input.locale, { x: heroX + 14, y: H - m - 34, w: 26, h: 22 });
if (mark) els.push(mark);
footMarks(ctx, els, { x: tx, y: H - m - 4, w: colW });
return sheet(newId, els, entry, '#ffffff');
}
+180
View File
@@ -0,0 +1,180 @@
import { bookCoordValue, formatBookCoords, formatBookDate } from '../book-text';
import { bookCountryMark, bookCountryName, bookDayText } from '../book-travel';
import {
MAX_TEXT_LENGTH,
type BookBadgeElement,
type BookElement,
type BookPageSetup,
type BookSpread,
} from '../book.schema';
import type { JourneyStats } from '../journey-stats.schema';
import { statsValues, type NewId } from './auto-elements';
import type { AutoTemplate } from './auto-templates.data';
import type { AutoEntry } from './auto-types';
/**
* Laying an entry out on a template somebody drew (`AUTO_TEMPLATES`).
*
* Only what the entry can answer for is filled: text carrying a `binding`
* (the title, the story, a caption), empty photo frames (the entry's photos in
* order), the day, coordinate, date and country marks, and the stats and
* countries elements from the journey's figures. Everything else is the design
* and is copied as drawn. That division is the whole contract between the
* person who draws a template and the code that uses it.
*
* The template's numbers are fractions of the page it was drawn on, so they
* are multiplied back up here: a template built on a 210mm square lays out on
* an A4 landscape book without being redrawn. Moved here from the Studio
* (client/src/components/Studio/applyTemplate.ts) and renamed, since
* `applyBookTemplate` is the built-in layouts' own function.
*/
export interface AutoTemplateContext {
page: BookPageSetup;
locale: string;
stats: JourneyStats | null;
/** The day mark's label ("DAY {day}"), already translated, because this module has no translation context. */
dayLabel: string;
newId: NewId;
}
const round2 = (n: number) => Math.round(n * 100) / 100;
/** How well a template suits an entry: more is better, -1 means unusable. */
export function autoTemplateFit(template: AutoTemplate, entry: AutoEntry): number {
const frames = template.elements.filter((e) => e.kind === 'photo').length;
const photos = entry.photos.length;
const wantsStory = template.elements.some((e) => e.kind === 'text' && e.binding?.source === 'entry.story');
const hasStory = !!(entry.story || '').trim();
// A template is a template for an entry when it uses one: a binding or an empty frame says so.
const usesEntry = template.elements.some(
(e) => ('binding' in e && e.binding) || (e.kind === 'photo' && e.photoId == null),
);
if (!usesEntry) return -1;
// Three frames for one picture leaves two placeholders on a finished page; more pictures than frames is fine.
if (frames > photos + 1) return -1;
if (wantsStory && !hasStory) return -1;
return 100 - Math.abs(frames - photos) * 10 - (wantsStory === hasStory ? 0 : 5);
}
/** Fill a template with an entry, and hand back the spread it makes. */
export function applyAutoTemplate(template: AutoTemplate, entry: AutoEntry, ctx: AutoTemplateContext): BookSpread {
const PW = ctx.page.pageWidth;
const PH = ctx.page.pageHeight;
let nextPhoto = 0;
// A journal entry has no length limit and a text element does.
const story = (entry.story || '').trim().slice(0, MAX_TEXT_LENGTH);
const heading = (entry.title || entry.location || '').slice(0, MAX_TEXT_LENGTH);
const elements = template.elements.map((el) => {
const frame = {
x: round2(el.frame.x * PW),
y: round2(el.frame.y * PH),
w: round2(el.frame.w * PW),
h: round2(el.frame.h * PH),
};
const out = { ...el, id: ctx.newId(el.kind.charAt(0)), frame } as BookElement;
// Sizes came out as fractions of the page height, radii and strokes of its width.
if (out.kind === 'text' && typeof out.size === 'number') out.size = round2(out.size * PH);
if ((out.kind === 'photo' || out.kind === 'shape') && typeof out.radius === 'number') {
out.radius = round2(out.radius * PW);
}
if (out.kind === 'shape' && typeof out.strokeWidth === 'number') out.strokeWidth = round2(out.strokeWidth * PW);
if (out.kind === 'text' && out.binding) fillText(out, entry, ctx, { story, heading });
if (out.kind === 'photo' && out.photoId == null) {
const picture = entry.photos[nextPhoto++];
if (picture) out.photoId = picture.photoId;
}
if (out.kind === 'badge') fillBadge(out, entry, ctx);
if (out.kind === 'countries' && ctx.stats) {
out.codes = ctx.stats.countries.map((c) => c.code);
out.names = ctx.stats.countries.map((c) => c.name);
}
// The figures live in one map on the element, keyed by metric, as the panels write them.
if (out.kind === 'stats' && ctx.stats) out.values = statsValues(ctx.stats);
return out;
});
return {
id: ctx.newId('sp'),
role: 'inner',
background: template.background,
elements,
parked: [],
entryId: entry.id,
};
}
type TextEl = Extract<BookElement, { kind: 'text' }>;
/** A bound text, set from the entry; the raw value is kept where the words were made rather than copied. */
function fillText(
out: TextEl,
entry: AutoEntry,
ctx: AutoTemplateContext,
words: { story: string; heading: string },
): void {
if (!out.binding) return;
const { source, format } = out.binding;
let value: string | undefined;
if (source === 'entry.title') out.text = words.heading;
else if (source === 'entry.story') out.text = words.story;
else if (source === 'entry.date') {
out.text = formatBookDate(entry.date, ctx.locale);
value = entry.date ?? undefined;
} else if (source === 'entry.location') {
// The place as its name or as its point; a stop the entry cannot answer keeps the drawn words.
if (format && entry.lat != null && entry.lng != null) {
out.text = formatBookCoords(entry.lat, entry.lng, format);
value = bookCoordValue(entry.lat, entry.lng);
} else if (!format && entry.location) {
out.text = entry.location;
}
}
out.binding = { ...out.binding, entryId: entry.id, ...(value ? { value } : {}) };
}
/**
* The small marks, filled from the stop. A badge whose value the entry cannot
* answer keeps the one it was drawn with.
*/
function fillBadge(el: BookBadgeElement, entry: AutoEntry, ctx: AutoTemplateContext): void {
if (el.variant === 'day' && entry.dayNumber) el.text = bookDayText(ctx.dayLabel, entry.dayNumber);
if (el.variant === 'coords' && entry.lat != null && entry.lng != null) {
el.text = formatBookCoords(entry.lat, entry.lng);
}
if ((el.variant === 'flag' || el.variant === 'country') && entry.country) fillCountry(el, entry.country, ctx);
if (el.variant === 'date' && entry.date) {
const d = new Date(`${entry.date}T00:00:00`);
if (!Number.isNaN(d.getTime())) {
el.text = String(d.getDate());
el.sub = d.toLocaleDateString(ctx.locale, { month: 'long' }).toUpperCase();
}
}
if (el.variant === 'distance' && ctx.stats?.distance) {
el.text = `${Math.round(ctx.stats.distance / 1000).toLocaleString(ctx.locale)} km`;
}
}
/**
* A country mark takes the rule the engine and the Travel panel follow
* (`bookCountryMark`): the name as its words, and the drawn words beside them
* go. A flag keeps the place its template set the name in: in capitals as its
* words, the way the auto layout sets a flag, or beside the flag (`sub`) where
* it was placed from the panel, so no drawn name is left next to the new one.
*/
function fillCountry(el: BookBadgeElement, code: string, ctx: AutoTemplateContext): void {
const name = bookCountryName(code, ctx.locale, ctx.stats);
if (el.variant === 'country') {
Object.assign(el, bookCountryMark('country', code, name));
return;
}
el.code = code;
if (el.text || !el.sub) el.text = name.toUpperCase();
else el.sub = name;
}
File diff suppressed because it is too large Load Diff
+95
View File
@@ -0,0 +1,95 @@
import type { BookPageSetup } from '../book.schema';
import type { JourneyStats } from '../journey-stats.schema';
import type { AutoTemplate } from './auto-templates.data';
/**
* What the auto layout turns into a book: a journey as plain data.
*
* Moved here from the Studio (client/src/components/Studio/autoLayout.ts) so
* the Studio's Auto layout button and the server's design tool lay a book out
* with one implementation. Labels and the locale come in already chosen: this
* code builds a document and has no business reaching for a translation table.
*/
export interface AutoPhoto {
photoId: number;
width: number | null;
height: number | null;
caption?: string | null;
/** When it was taken (ISO), where the gallery knows: the templated auto layout shares loose photos out by day. */
takenAt?: string | null;
}
export interface AutoEntry {
id: number;
title: string | null;
story: string | null;
location: string | null;
date: string | null;
photos: AutoPhoto[];
/**
* Where this stop is, when the journey's figures know.
*
* Filled from the stats points rather than carried on the entry: the entry
* knows a place name, the stats know what that place resolved to. A page can
* then print the flag, the country outline and the coordinates.
*/
lat?: number | null;
lng?: number | null;
country?: string | null;
/** Which day of the journey this is, 1-based. Null when the dates do not say. */
dayNumber?: number | null;
/** How many days the journey runs, for the progress rule along the foot. */
dayCount?: number | null;
/** The journal's mood and weather keys (`amazing`, `partly`), for the marks the book engine places. */
mood?: string | null;
weather?: string | null;
/** The entry's pros and cons, for a list element. */
pros?: readonly string[];
cons?: readonly string[];
}
export interface AutoInput {
/**
* The app's language, not the browser's. A book whose captions are dated in
* the reader's OS locale while the rest of it is written in the app's is a
* mismatch nobody asked for.
*/
locale: string;
title: string;
subtitle: string | null;
coverPhotoId: number | null;
entries: AutoEntry[];
page: BookPageSetup;
/**
* What the journey adds up to. Null when the figures could not be fetched:
* the book then simply has no summary pages rather than pages with nothing
* on them.
*/
stats: JourneyStats | null;
/** The heading over a list of bare stops, already translated. */
stationsLabel: string;
/**
* The words of a day chip, already translated: `{day}` stands where the
* number goes ("DAY {day}", "{day}日目"), and a word without it is followed
* by the number ("DAY 5"). See `bookDayText`.
*/
dayLabel: string;
/**
* The real geometry of the route, when the journey has any (GPX and KML
* imports), already thinned with `bookPath`.
*/
path?: [number, number][][];
/** "TRIP SUMMARY" over the figures. */
summaryLabel: string;
/** "COUNTRIES" over the outlines. */
countriesLabel: string;
/** Mints element and spread ids; the default is `bookElementId`, tests pass a counter. */
newId?: (prefix: string) => string;
/**
* The drawn templates an entry is tried against first. The default is the
* shipped set (`AUTO_TEMPLATES`); an empty list lays every entry out with the
* layouts written as code, which is what their tests pin.
*/
templates?: readonly AutoTemplate[];
}
+32
View File
@@ -0,0 +1,32 @@
/**
* The twelve cover archetypes a decorated book starts from: the Studio's cover
* templates are drawn in them, and the assistant's art direction names one.
*
* - spine-band: a bleed photo with a coloured band on the binding side.
* - poster-pop: a two-tone colour block, a heavy two-line title, a tilted inset photo.
* - cutout: a saturated page, organic cut-out shapes around a bordered portrait photo.
* - postcard: a pastel page, a landmark drawing, a display serif title and a script line.
* - grid-badge: a two by two photo grid with a round title badge at its centre.
* - minimal-serif: a white page, a large photo with a hairline, a very large thin serif title.
* - stamp-collage: photos in arches and stamps over a checker band, with a round postmark.
* - riso: a risograph print, spot inks overprinted a little out of register, halftone dots, bold type.
* - editorial: a travel magazine, a huge masthead, thin rules, an issue line, a photo edge to edge.
* - vintage-poster: a 1950s travel poster, flat layered mountains under a sun, a stacked title, a thin frame.
* - night-film: a dark cinematic page, a letterboxed photo, a film strip with sprocket holes, a neon accent.
* - field-notes: a traveller's notebook, squared paper, prints taped in at an angle, pressed leaves.
*/
export const BOOK_COVER_ARCHETYPES = [
'spine-band',
'poster-pop',
'cutout',
'postcard',
'grid-badge',
'minimal-serif',
'stamp-collage',
'riso',
'editorial',
'vintage-poster',
'night-film',
'field-notes',
] as const;
export type BookCoverArchetype = (typeof BOOK_COVER_ARCHETYPES)[number];
+146
View File
@@ -0,0 +1,146 @@
import {
alignElements,
arrangeElements,
arrangeWithinGroup,
boundsOfFrames,
distributableCount,
distributeElements,
} from './book-arrange';
import {
bookPageSetupSchema,
bookShapeElementSchema,
bookSpreadSchema,
type BookElement,
type BookSpread,
} from './book.schema';
import { describe, expect, it } from 'vitest';
/**
* Paint order, alignment and spacing, with groups moving as one. The page is
* the default square book: 210 mm pages, the fold at 210, 5 mm safe margin.
*/
const pageSetup = bookPageSetupSchema.parse({});
const box = (id: string, x: number, y: number, w = 20, h = 20, over: Partial<BookElement> = {}) =>
bookShapeElementSchema.parse({ id, kind: 'shape', frame: { x, y, w, h }, shape: 'rect', ...over }) as BookElement;
const spread = (elements: BookElement[]): BookSpread => bookSpreadSchema.parse({ id: 'sp', elements });
const ids = (sp: BookSpread) => sp.elements.map((e) => e.id);
const at = (sp: BookSpread, id: string) => sp.elements.find((e) => e.id === id)?.frame;
const pick = (sp: BookSpread, list: string[]) => sp.elements.filter((e) => list.includes(e.id));
describe('paint order', () => {
const sp = spread([
box('a', 0, 0),
box('g1', 0, 0, 20, 20, { group: 'g' }),
box('g2', 0, 0, 20, 20, { group: 'g' }),
box('b', 0, 0),
]);
it('BKARR-001: to front and to back keep the moved ones in their order, and a group together', () => {
expect(ids(arrangeElements(sp, ['a'], 'front'))).toEqual(['g1', 'g2', 'b', 'a']);
expect(ids(arrangeElements(sp, ['b'], 'back'))).toEqual(['b', 'a', 'g1', 'g2']);
// One member moved to the front takes its group along.
expect(ids(arrangeElements(sp, ['g1'], 'front'))).toEqual(['a', 'b', 'g1', 'g2']);
});
it('BKARR-002: forward and backward step one place', () => {
// A step goes past a whole group, never into it.
expect(ids(arrangeElements(sp, ['a'], 'forward'))).toEqual(['g1', 'g2', 'a', 'b']);
expect(ids(arrangeElements(sp, ['g2'], 'backward'))).toEqual(['g1', 'g2', 'a', 'b']);
expect(arrangeElements(sp, ['b'], 'front')).toBe(sp);
expect(ids(arrangeElements(spread([box('a', 0, 0), box('b', 0, 0), box('c', 0, 0)]), ['a'], 'forward'))).toEqual([
'b',
'a',
'c',
]);
expect(ids(arrangeElements(spread([box('a', 0, 0), box('b', 0, 0), box('c', 0, 0)]), ['c'], 'backward'))).toEqual([
'a',
'c',
'b',
]);
});
it('BKARR-003: inside a group, a member moves among the members only', () => {
const grouped = spread([
box('a', 0, 0),
box('m1', 0, 0, 20, 20, { group: 'g' }),
box('m2', 0, 0, 20, 20, { group: 'g' }),
box('m3', 0, 0, 20, 20, { group: 'g' }),
box('b', 0, 0),
]);
expect(ids(arrangeWithinGroup(grouped, 'g', ['m1'], 'front'))).toEqual(['a', 'm2', 'm3', 'm1', 'b']);
expect(ids(arrangeWithinGroup(grouped, 'g', ['m3'], 'back'))).toEqual(['a', 'm3', 'm1', 'm2', 'b']);
expect(arrangeWithinGroup(grouped, 'g', ['m3'], 'front')).toBe(grouped);
expect(arrangeWithinGroup(grouped, 'g', ['m3'], 'front').elements[3]?.group).toBe('g');
});
});
describe('align and distribute', () => {
it('BKARR-004: lines single elements up on the edge of their box', () => {
const sp = spread([box('a', 10, 10), box('b', 40, 30)]);
const left = alignElements(sp, pageSetup, sp.elements, 'left', 'selection');
expect([at(left, 'a')?.x, at(left, 'b')?.x]).toEqual([10, 10]);
const bottom = alignElements(sp, pageSetup, sp.elements, 'bottom', 'selection');
expect([at(bottom, 'a')?.y, at(bottom, 'b')?.y]).toEqual([30, 30]);
// The other axis is left exactly as it was.
expect(at(left, 'b')?.y).toBe(30);
});
it('BKARR-005: moves a group as one box, and lines a group up inside itself when it is all that is picked', () => {
const sp = spread([
box('a', 100, 10),
box('g1', 10, 50, 20, 20, { group: 'g' }),
box('g2', 40, 60, 20, 20, { group: 'g' }),
]);
const right = alignElements(sp, pageSetup, sp.elements, 'right', 'selection');
// The group's box (10..60) goes to the right edge 120 as one: 60 to the right.
expect([at(right, 'g1')?.x, at(right, 'g2')?.x, at(right, 'a')?.x]).toEqual([70, 100, 100]);
const inside = alignElements(sp, pageSetup, pick(sp, ['g1', 'g2']), 'top', 'selection');
expect([at(inside, 'g1')?.y, at(inside, 'g2')?.y]).toEqual([50, 50]);
});
it('BKARR-006: aligns against the page under an element, and its safe area', () => {
const sp = spread([box('r', pageSetup.pageWidth + 90, 10)]);
const centred = alignElements(sp, pageSetup, sp.elements, 'center', 'page');
expect(at(centred, 'r')?.x).toBe(pageSetup.pageWidth + (pageSetup.pageWidth - 20) / 2);
const safe = alignElements(sp, pageSetup, sp.elements, 'top', 'safe');
expect(at(safe, 'r')?.y).toBe(pageSetup.safe);
const middle = alignElements(sp, pageSetup, sp.elements, 'middle', 'page');
expect(at(middle, 'r')?.y).toBe((pageSetup.pageHeight - 20) / 2);
});
it('BKARR-007: spaces units evenly, a group counted once, or by a fixed gap', () => {
const sp = spread([
box('a', 0, 0),
box('g1', 30, 0, 10, 10, { group: 'g' }),
box('g2', 45, 0, 10, 10, { group: 'g' }),
box('c', 100, 0),
]);
expect(distributableCount(sp, sp.elements)).toBe(3);
const even = distributeElements(sp, sp.elements, 'horizontal');
// Span 0..120, sizes 20 + 25 + 20, so two gaps of 27.5; the group moves as one.
expect([at(even, 'g1')?.x, at(even, 'g2')?.x, at(even, 'c')?.x]).toEqual([47.5, 62.5, 100]);
const fixed = distributeElements(sp, sp.elements, 'horizontal', 5);
expect([at(fixed, 'g1')?.x, at(fixed, 'c')?.x]).toEqual([25, 55]);
const down = distributeElements(
spread([box('a', 0, 0), box('b', 0, 50), box('c', 0, 30)]),
spread([box('a', 0, 0), box('b', 0, 50), box('c', 0, 30)]).elements,
'vertical',
);
expect(at(down, 'c')?.y).toBe(25);
});
it('BKARR-008: leaves a page with fewer than three units as it is, and measures a box', () => {
const sp = spread([box('a', 0, 0), box('b', 50, 0)]);
expect(distributeElements(sp, sp.elements, 'horizontal')).toBe(sp);
expect(
boundsOfFrames([
{ x: 1, y: 2, w: 3, h: 4 },
{ x: 10, y: 0, w: 1, h: 1 },
]),
).toEqual({ x: 1, y: 0, w: 10, h: 6 });
});
});
+218
View File
@@ -0,0 +1,218 @@
import { commonGroup, gatherGroups } from './book-groups';
import type { BookElement, BookFrame, BookPageSetup, BookSpread } from './book.schema';
/**
* Paint order, alignment and spacing of the elements of a page.
*
* The `arrange`, `align` and `distribute` operations of the book engine run
* these (book-ops-elements.ts), and the Studio's layer buttons, align bar and
* layers panel run the same engine, so a press and an assistant's operation
* move a page the same way.
*
* Groups move as one: aligning two groups lines up their boxes, not every
* member on the same edge, and distributing spaces the boxes. When every named
* element is in the one group, the members line up among themselves, which is
* how the inside of a lockup is set.
*/
export type BookArrangeTo = 'front' | 'forward' | 'backward' | 'back';
export type BookAlignEdge = 'left' | 'center' | 'right' | 'top' | 'middle' | 'bottom';
export type BookAlignTo = 'selection' | 'page' | 'safe';
export type BookDistributeAxis = 'horizontal' | 'vertical';
const round2 = (v: number) => Math.round(v * 100) / 100;
/**
* The page in paint order as the things that move as one: a group's members
* together (they are next to each other, see `gatherGroups`), every other
* element alone.
*/
function paintUnits(spread: BookSpread): BookElement[][] {
const units: BookElement[][] = [];
for (const el of gatherGroups(spread).elements) {
const last = units[units.length - 1];
if (el.group && last?.[0]?.group === el.group) last.push(el);
else units.push([el]);
}
return units;
}
/**
* The named elements moved in the paint order, keeping their order among
* themselves. A group moves whole, and a step forward or backward goes past a
* whole group at once, never into it.
*/
export function arrangeElements(spread: BookSpread, ids: readonly string[], to: BookArrangeTo): BookSpread {
const chosen = new Set(ids);
const units = paintUnits(spread);
const isChosen = (u: BookElement[]) => u.some((e) => chosen.has(e.id));
let next: BookElement[][];
if (to === 'front') next = [...units.filter((u) => !isChosen(u)), ...units.filter(isChosen)];
else if (to === 'back') next = [...units.filter(isChosen), ...units.filter((u) => !isChosen(u))];
else {
next = units.slice();
const step = to === 'forward' ? 1 : -1;
const order = next.map((_, i) => i);
if (step === 1) order.reverse();
for (const i of order) {
const here = next[i];
const there = next[i + step];
if (!here || !there || !isChosen(here) || isChosen(there)) continue;
next[i] = there;
next[i + step] = here;
}
}
const elements = next.flat();
return elements.every((e, i) => e === spread.elements[i]) ? spread : { ...spread, elements };
}
/**
* Members of one group moved in the paint order among the group's own members
* only, the group staying where it is on the page: what "to front" does to an
* element picked inside a group.
*/
export function arrangeWithinGroup(
spread: BookSpread,
groupId: string,
ids: readonly string[],
to: BookArrangeTo,
): BookSpread {
const slots: number[] = [];
spread.elements.forEach((e, i) => {
if (e.group === groupId) slots.push(i);
});
const members = slots.map((i) => spread.elements[i] as BookElement);
const reordered = arrangeElements({ ...spread, elements: members.map(withoutGroupId) }, ids, to).elements;
const byId = new Map(members.map((m) => [m.id, m]));
const elements = spread.elements.slice();
slots.forEach((slot, k) => {
const moved = reordered[k];
if (moved) elements[slot] = byId.get(moved.id) as BookElement;
});
return elements.every((e, i) => e === spread.elements[i]) ? spread : { ...spread, elements };
}
/** A member taken out of its group for reordering among the members alone, so gathering leaves them be. */
function withoutGroupId(el: BookElement): BookElement {
const next = { ...el };
delete next.group;
return next;
}
/** The box around frames. */
export function boundsOfFrames(frames: readonly BookFrame[]): BookFrame {
const x = Math.min(...frames.map((f) => f.x));
const y = Math.min(...frames.map((f) => f.y));
const right = Math.max(...frames.map((f) => f.x + f.w));
const bottom = Math.max(...frames.map((f) => f.y + f.h));
return { x, y, w: right - x, h: bottom - y };
}
/** The page a box's centre is on, or its safe area. */
function pageBox(spread: BookSpread, page: BookPageSetup, f: BookFrame, safe: boolean): BookFrame {
const onRight = spread.role === 'inner' && f.x + f.w / 2 >= page.pageWidth;
const x = onRight ? page.pageWidth : 0;
const inset = safe ? page.safe : 0;
return { x: x + inset, y: inset, w: page.pageWidth - inset * 2, h: page.pageHeight - inset * 2 };
}
/** Where a box goes to line up on an edge of another. */
function alignedAt(f: BookFrame, box: BookFrame, edge: BookAlignEdge): { x: number; y: number } {
switch (edge) {
case 'left':
return { x: box.x, y: f.y };
case 'center':
return { x: box.x + (box.w - f.w) / 2, y: f.y };
case 'right':
return { x: box.x + box.w - f.w, y: f.y };
case 'top':
return { x: f.x, y: box.y };
case 'middle':
return { x: f.x, y: box.y + (box.h - f.h) / 2 };
case 'bottom':
return { x: f.x, y: box.y + box.h - f.h };
}
}
/** What moves as one: a group's named members together, every other element alone. */
interface Unit {
members: BookElement[];
box: BookFrame;
}
function unitsOf(spread: BookSpread, els: readonly BookElement[]): Unit[] {
const ids = els.map((e) => e.id);
// All in one group: the members are the units, so the inside of a group can be set.
const inside = commonGroup(spread, ids) !== null;
const byKey = new Map<string, BookElement[]>();
for (const el of els) {
const key = !inside && el.group ? `g:${el.group}` : `e:${el.id}`;
byKey.set(key, [...(byKey.get(key) ?? []), el]);
}
return [...byKey.values()].map((members) => ({ members, box: boundsOfFrames(members.map((m) => m.frame)) }));
}
/** Every member of a unit moved by the same offset, rounded as the document stores it. */
function shifted(unit: Unit, dx: number, dy: number): BookElement[] {
// An axis that does not move is left exactly as it was, unrounded or not.
return unit.members.map((e) => {
const x = dx === 0 ? e.frame.x : round2(e.frame.x + dx);
const y = dy === 0 ? e.frame.y : round2(e.frame.y + dy);
return { ...e, frame: { ...e.frame, x, y } } as BookElement;
});
}
function replaceAll(spread: BookSpread, next: readonly BookElement[]): BookSpread {
const byId = new Map(next.map((e) => [e.id, e]));
return { ...spread, elements: spread.elements.map((e) => byId.get(e.id) ?? e) };
}
/** The named elements lined up on an edge or a centre line of their box, their page, or its safe area. */
export function alignElements(
spread: BookSpread,
page: BookPageSetup,
els: readonly BookElement[],
edge: BookAlignEdge,
to: BookAlignTo,
): BookSpread {
const units = unitsOf(spread, els);
const selection = boundsOfFrames(units.map((u) => u.box));
const next = units.flatMap((u) => {
const box = to === 'selection' ? selection : pageBox(spread, page, u.box, to === 'safe');
const at = alignedAt(u.box, box, edge);
return shifted(u, at.x - u.box.x, at.y - u.box.y);
});
return replaceAll(spread, next);
}
/** How many units a distribute has: it needs three. */
export function distributableCount(spread: BookSpread, els: readonly BookElement[]): number {
return unitsOf(spread, els).length;
}
/** Three or more units spaced evenly between the outer two, or by a fixed gap in millimetres. */
export function distributeElements(
spread: BookSpread,
els: readonly BookElement[],
axis: BookDistributeAxis,
gap?: number,
): BookSpread {
const units = unitsOf(spread, els);
if (units.length < 3) return spread;
const across = axis === 'horizontal';
const start = (f: BookFrame) => (across ? f.x : f.y);
const size = (f: BookFrame) => (across ? f.w : f.h);
const sorted = units.slice().sort((a, b) => start(a.box) - start(b.box));
const first = sorted[0] as Unit;
const last = sorted[sorted.length - 1] as Unit;
const total = sorted.reduce((sum, u) => sum + size(u.box), 0);
const span = start(last.box) + size(last.box) - start(first.box);
const space = gap ?? (span - total) / (sorted.length - 1);
let cursor = start(first.box);
const next = sorted.flatMap((u) => {
const delta = round2(cursor) - start(u.box);
cursor += size(u.box) + space;
return across ? shifted(u, delta, 0) : shifted(u, 0, delta);
});
return replaceAll(spread, next);
}
+57
View File
@@ -0,0 +1,57 @@
/**
* The search `list_book_assets` runs over every catalogue it lists (stickers,
* shapes, fonts, lockups, themes, patterns): every word of the query has to
* be found, a word that is the id or one of the tags counts for more than one
* buried in the description, and between equals the catalogue keeps its own
* order. Case and accents do not matter.
*/
/** Lower case, accents taken off: how ids, tags and words are compared. */
const normAsset = (s: string): string => s.toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '');
/** What an item of a catalogue is found by. */
export interface AssetKey {
id: string;
/** Every word it is found by: its id, its tags, its description. */
words: readonly string[];
tags: readonly string[];
}
/** How well an item answers the words of a query, 0 when one of them is not found. */
function score(key: AssetKey, words: readonly string[]): number {
const hay = normAsset(key.words.join(' '));
const id = normAsset(key.id);
const tags = key.tags.map(normAsset);
let total = 0;
for (const w of words) {
if (!hay.includes(w)) return 0;
if (id === w || tags.includes(w)) total += 3;
else if (tags.some((t) => t.split(' ').includes(w)) || id.startsWith(w)) total += 2;
else total += 1;
}
return total;
}
/**
* The items carrying every one of `tags` that answer `query`, best first,
* the catalogue's own order between equals; all of them in that order
* without a query.
*/
export function rankAssets<T>(
pool: readonly T[],
keyOf: (item: T) => AssetKey,
query: string | undefined,
tags: readonly string[] = [],
): T[] {
const wanted = tags.map(normAsset);
const tagged = pool.filter((item) => wanted.every((t) => keyOf(item).tags.map(normAsset).includes(t)));
const words = normAsset(query ?? '')
.split(/\s+/)
.filter(Boolean);
if (!words.length) return tagged;
return tagged
.map((item, i) => ({ item, i, n: score(keyOf(item), words) }))
.filter((r) => r.n > 0)
.sort((a, b) => b.n - a.n || a.i - b.i)
.map((r) => r.item);
}

Some files were not shown because too many files have changed in this diff Show More