@typeflowus/mcp-server 0.1.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "name": "@typeflowus/mcp-server",
3
- "version": "0.1.4",
4
- "description": "TypeFlow MCP Server - Create and manage PDF templates programmatically via AI assistants",
3
+ "version": "0.3.0",
4
+ "description": "TypeFlow MCP Server - create and manage PDF templates in your TypeFlow library via AI assistants",
5
5
  "type": "module",
6
6
  "bin": {
7
- "typeflow-mcp-server": "src/index.js"
7
+ "typeflow-mcp-server": "src/stdio.js"
8
8
  },
9
9
  "files": [
10
10
  "src/"
11
11
  ],
12
12
  "scripts": {
13
- "start": "node src/index.js"
13
+ "start": "node src/stdio.js"
14
14
  },
15
15
  "dependencies": {
16
16
  "@modelcontextprotocol/sdk": "^1.29.0",
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The HTTP client the tools call.
3
+ *
4
+ * A factory rather than a module-level function, because the HTTP entrypoint
5
+ * serves many users from one process: the credentials belong to the request,
6
+ * not to the module. stdio passes the key from the environment once at
7
+ * startup; the worker passes a key resolved per request from an OAuth token.
8
+ */
9
+ export function createApiClient({ apiUrl, headers }) {
10
+ async function apiRequest(method, path, body, extraHeaders = {}) {
11
+ const options = {
12
+ method,
13
+ headers: {
14
+ ...headers,
15
+ ...extraHeaders,
16
+ "Content-Type": "application/json",
17
+ },
18
+ };
19
+
20
+ if (body) {
21
+ options.body = JSON.stringify(body);
22
+ }
23
+
24
+ const response = await fetch(`${apiUrl}/api${path}`, options);
25
+
26
+ if (!response.ok) {
27
+ const error = await response.json().catch(() => ({ error: response.statusText }));
28
+ // The flow routes explain a refusal in extra fields (which guard, which
29
+ // connections, close field names). Pass them on: the model needs them
30
+ // to fix the call instead of retrying it.
31
+ const { error: message, ...details } = error;
32
+ const extra = Object.keys(details).length ? `\n${JSON.stringify(details, null, 2)}` : "";
33
+ throw new Error(`TypeFlow API error (${response.status}): ${message || response.statusText}${extra}`);
34
+ }
35
+
36
+ return response.json();
37
+ }
38
+
39
+ /**
40
+ * validate_template is the one route outside /api/mcp, so it cannot go
41
+ * through apiRequest's path prefix. It gets its own method rather than a
42
+ * special case inside apiRequest, and carries the same headers.
43
+ */
44
+ apiRequest.validateTemplate = async function validateTemplate(body) {
45
+ const response = await fetch(`${apiUrl}/api/validate-template`, {
46
+ method: "POST",
47
+ headers: {
48
+ "Content-Type": "application/json",
49
+ ...headers,
50
+ },
51
+ body: JSON.stringify(body),
52
+ });
53
+
54
+ if (!response.ok) {
55
+ const error = await response.json().catch(() => ({ error: response.statusText }));
56
+ throw new Error(`Validation API error (${response.status}): ${error.error || response.statusText}`);
57
+ }
58
+
59
+ return response.json();
60
+ };
61
+
62
+ return apiRequest;
63
+ }
@@ -0,0 +1,250 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * Flow tools: set up an HTML/CSS flow on an Airtable table, write its
5
+ * template, map it, test it. Step 1 of
6
+ * typeflow-documentation/specification/2026-11-22-mcp-html-flows-step1.md
7
+ *
8
+ * Each tool calls /api/mcp/flows/*, which the worker relays to the app, where
9
+ * the app's own code does the work and refuses what would break a flow. The
10
+ * tools only shape the answers for the model.
11
+ *
12
+ * act_as: TypeFlow staff only (refused for any other key). Builds the flow in
13
+ * a customer's account for Build it for me; every such call is logged.
14
+ */
15
+
16
+ const actAs = z
17
+ .string()
18
+ .optional()
19
+ .describe("TypeFlow staff only: the user id or email to act for. Omit otherwise.");
20
+
21
+ const json = (value) => ({ content: [{ type: "text", text: JSON.stringify(value, null, 2) }] });
22
+
23
+ const failure = (err) => ({ content: [{ type: "text", text: err.message }], isError: true });
24
+
25
+ const PREVIEW_NOTE =
26
+ "Open preview_url in the user's browser and let them check the document. " +
27
+ "Never call activate_flow before they confirm.";
28
+
29
+ export function registerFlowTools(server, apiRequest) {
30
+ const call = (method, path, body, args) =>
31
+ apiRequest(method, path, body, args?.act_as ? { "x-typeflow-act-as": args.act_as } : {});
32
+
33
+ const run = (fn) => async (args) => {
34
+ try {
35
+ return await fn(args);
36
+ } catch (err) {
37
+ return failure(err);
38
+ }
39
+ };
40
+
41
+ server.tool(
42
+ "get_flow",
43
+ "Read a flow: base, table, attachment field, whether it has a template, its variables and which are still unmapped, and whether e-signature is on. Read only. Call it first to see what is missing.",
44
+ { automation_id: z.string().describe("The flow id, as in its URL"), act_as: actAs },
45
+ run(async (args) => json(await call("GET", `/mcp/flows/${encodeURIComponent(args.automation_id)}`, null, args)))
46
+ );
47
+
48
+ server.tool(
49
+ "create_flow",
50
+ `Create an HTML/CSS document flow on an Airtable table. The flow starts without a template: write one with update_flow_template next.
51
+
52
+ Returns the table's fields (names and types): write the template against these exact names.
53
+ If the account has several Airtable connections, the error lists them: ask the user which one and pass connection_id.
54
+ attachment_field is the Airtable attachment field the PDF is saved to; without it, generated PDFs are not written back.`,
55
+ {
56
+ base_id: z.string().describe("Airtable base id (appXXXXXXXXXXXXXX). get_airtable_schema lists them."),
57
+ table_id: z.string().describe("Table id (tblXXX) or exact table name"),
58
+ flow_name: z.string().describe("Name shown in TypeFlow"),
59
+ attachment_field: z.string().optional().describe("Attachment field id or exact name for the generated PDF"),
60
+ connection_id: z.string().optional().describe("Only when the account has several Airtable connections"),
61
+ act_as: actAs,
62
+ },
63
+ run(async (args) => {
64
+ const { act_as, ...body } = args;
65
+ const result = await call("POST", "/mcp/flows", body, { act_as });
66
+ return json({ ...result, next: "Call get_template_guide, then update_flow_template with this automation_id." });
67
+ })
68
+ );
69
+
70
+ server.tool(
71
+ "get_flow_template",
72
+ "The flow's saved template: body html, css, header, footer, page format and variables. Read it before changing anything: update_flow_template is checked against it. Returns update_rules_version: the version of the rules in get_template_guide this server applies.",
73
+ { automation_id: z.string(), act_as: actAs },
74
+ run(async (args) => json(await call("GET", `/mcp/flows/${encodeURIComponent(args.automation_id)}/template`, null, args)))
75
+ );
76
+
77
+ server.tool(
78
+ "update_flow_template",
79
+ `Write the flow's template. Follow get_template_guide, including its "Updating an existing template" rules.
80
+
81
+ - html is the body (a leading <style> block is split into css). header and footer are separate zones with inline styles only: never <header>/<footer> tags in the body. {{page}} and {{total}} work only there.
82
+ - Refused, with nothing written, when the change would: drop a data-tf-node-id or a tf-i-* class, change the TYPEFLOW INSPECTOR OVERRIDES block, put a header or footer in the body, fail validation against the flow's table, or remove a mapped variable (unless replace_mapped_variables is true and the user asked for it).
83
+ - Mappings of variables still in the template are kept. A revision of the previous version is saved.
84
+ - Never activates the flow. ${PREVIEW_NOTE}`,
85
+ {
86
+ automation_id: z.string(),
87
+ html: z.string().describe("Body HTML (may start with a <style> block)"),
88
+ css: z.string().optional().describe("CSS without <style> tags, if not inside html"),
89
+ header: z.string().optional().describe("Header zone HTML, inline styles. Omit to keep the current one, '' to clear it."),
90
+ footer: z.string().optional().describe("Footer zone HTML, inline styles. Omit to keep the current one, '' to clear it."),
91
+ page_format: z.string().optional().describe("Page format id (a4, letter, a4-landscape, label-100x150, ... or custom)"),
92
+ page_width_mm: z.number().optional().describe("With page_format custom"),
93
+ page_height_mm: z.number().optional().describe("With page_format custom"),
94
+ replace_mapped_variables: z.boolean().optional().describe("Allow removing variables that are mapped. Only when the user asked for it."),
95
+ act_as: actAs,
96
+ },
97
+ run(async (args) => {
98
+ const { automation_id, act_as, ...body } = args;
99
+ const result = await call("PUT", `/mcp/flows/${encodeURIComponent(automation_id)}/template`, body, { act_as });
100
+ return json({ ...result, next: `${PREVIEW_NOTE} Then set_mapping.` });
101
+ })
102
+ );
103
+
104
+ server.tool(
105
+ "set_mapping",
106
+ `Bind the template's variables to the flow's Airtable fields.
107
+
108
+ auto (default true) runs TypeFlow's auto-mapping, the same the app runs: exact field names, loop columns through linked records. It never overwrites a variable already mapped.
109
+ overrides maps main-field variables explicitly: { "{{Client}}": { "field": "Client name" } }, with optional barcode_type, width or height (px) for images. An unknown field name returns close matches and saves nothing.
110
+ Returns what is still unmapped: report it to the user, do not guess.`,
111
+ {
112
+ automation_id: z.string(),
113
+ auto: z.boolean().optional(),
114
+ overrides: z.record(z.object({
115
+ field: z.string().describe("Field id or exact name"),
116
+ barcode_type: z.string().optional(),
117
+ width: z.number().optional(),
118
+ height: z.number().optional(),
119
+ })).optional(),
120
+ act_as: actAs,
121
+ },
122
+ run(async (args) => {
123
+ const { automation_id, act_as, ...body } = args;
124
+ return json(await call("POST", `/mcp/flows/${encodeURIComponent(automation_id)}/mapping`, body, { act_as }));
125
+ })
126
+ );
127
+
128
+ server.tool(
129
+ "generate_test",
130
+ `Generate the flow's document for one Airtable record and return the PDF link. Counts as a test, not toward the plan limit.
131
+
132
+ preview_only: true renders the PDF with no side effect (nothing written to Airtable, no email, no signature). Prefer it while the template is being built.
133
+ Without preview_only the PDF is saved to the record's attachment field, as a test from the app would. If e-signature is on, a full test also creates a signature session and emails the first signer: it is refused unless allow_signature_emails is true, which needs the user's explicit agreement.`,
134
+ {
135
+ automation_id: z.string(),
136
+ record_id: z.string().describe("Airtable record id (recXXX)"),
137
+ preview_only: z.boolean().optional(),
138
+ allow_signature_emails: z.boolean().optional(),
139
+ act_as: actAs,
140
+ },
141
+ run(async (args) => {
142
+ const { automation_id, act_as, ...body } = args;
143
+ return json(await call("POST", `/mcp/flows/${encodeURIComponent(automation_id)}/test`, body, { act_as }));
144
+ })
145
+ );
146
+
147
+ server.tool(
148
+ "validate_flow_template",
149
+ "Validate a template against a flow's own Airtable table, without saving. Omit html to validate the saved template. Same validator as validate_template.",
150
+ {
151
+ automation_id: z.string(),
152
+ html: z.string().optional(),
153
+ css: z.string().optional(),
154
+ act_as: actAs,
155
+ },
156
+ run(async (args) => {
157
+ const { automation_id, act_as, ...body } = args;
158
+ return json(await call("POST", `/mcp/flows/${encodeURIComponent(automation_id)}/validate`, body, { act_as }));
159
+ })
160
+ );
161
+
162
+ server.tool(
163
+ "activate_flow",
164
+ "Mark the flow as set up (active). ONLY after the user has opened the flow in their browser and said the document is right. user_confirmation is their exact words; it is logged. Never call it on your own initiative, and never invent the confirmation.",
165
+ {
166
+ automation_id: z.string(),
167
+ user_confirmation: z.string().min(1).describe("The user's exact words confirming the document is right"),
168
+ act_as: actAs,
169
+ },
170
+ run(async (args) => {
171
+ const { automation_id, act_as, user_confirmation } = args;
172
+ return json(await call("POST", `/mcp/flows/${encodeURIComponent(automation_id)}/activate`, { user_confirmation }, { act_as }));
173
+ })
174
+ );
175
+
176
+ server.tool(
177
+ "get_esignature",
178
+ "The flow's e-signature setup: the {{e-signature.*}} tags in the template, the signer numbers they need, the saved config (signers, order, signed PDF field, field updates on completion) and the table's fields. Read only. Call it before configure_esignature.",
179
+ { automation_id: z.string(), act_as: actAs },
180
+ run(async (args) => json(await call("GET", `/mcp/flows/${encodeURIComponent(args.automation_id)}/esignature`, null, args)))
181
+ );
182
+
183
+ server.tool(
184
+ "configure_esignature",
185
+ `Set who signs the flow's document, and turn e-signature on. Writes the same config as the app's e-signature screen; settings not given here are kept as saved in the app.
186
+
187
+ - One signer per signer number of the template ({{e-signature.signature_1}} is signer 1). Every number must be configured, and only those.
188
+ - Each signer takes email_field (+ name_field) from the record, or static_email (+ static_name) for a fixed person, such as the user's own team. Never a {{variable}} in static_email or static_name: it would be sent as written. When the email is on a linked record (e.g. a Client link), give the link field as email_field and the field of the linked table as email_linked_field; same for the name.
189
+ - signed_pdf_field: attachment field the signed PDF is saved to. on_complete: fields set when everyone has signed, e.g. [{ "field": "Status", "value": "Signed" }] (plans with field sync).
190
+ - Sends nothing. Signers are emailed only when a document is generated; generate_test with allow_signature_emails does that, so ask the user first.`,
191
+ {
192
+ automation_id: z.string(),
193
+ signers: z.array(z.object({
194
+ signer_number: z.number().int().min(1),
195
+ email_field: z.string().optional().describe("Field id or exact name holding the signer's email"),
196
+ email_linked_field: z.string().optional().describe("When email_field is a linked record field: the field of the linked table holding the email"),
197
+ name_field: z.string().optional().describe("Field id or exact name holding the signer's name"),
198
+ name_linked_field: z.string().optional().describe("When name_field is a linked record field: the field of the linked table holding the name"),
199
+ static_email: z.string().optional().describe("Fixed email, for a signer who is the same on every document"),
200
+ static_name: z.string().optional().describe("Fixed name, with static_email"),
201
+ role: z.string().optional().describe("Label shown to signers, e.g. Client"),
202
+ optional: z.boolean().optional(),
203
+ })).optional(),
204
+ signing_mode: z.enum(["parallel", "sequential"]).optional().describe("sequential: signer 1 first, then signer 2"),
205
+ signed_pdf_field: z.string().optional().describe("Attachment field id or exact name"),
206
+ on_complete: z.array(z.object({ field: z.string(), value: z.string().optional() })).optional(),
207
+ expiration_days: z.number().int().min(1).max(365).optional(),
208
+ enabled: z.boolean().optional().describe("false turns e-signature off"),
209
+ act_as: actAs,
210
+ },
211
+ run(async (args) => {
212
+ const { automation_id, act_as, ...body } = args;
213
+ return json(await call("PUT", `/mcp/flows/${encodeURIComponent(automation_id)}/esignature`, body, { act_as }));
214
+ })
215
+ );
216
+
217
+ server.tool(
218
+ "list_signatures",
219
+ "The flow's signature requests, newest first: document, record, status, and for each signer whether they viewed or signed, and when they were last reminded. Read only.",
220
+ {
221
+ automation_id: z.string(),
222
+ status: z.enum(["pending", "completed", "declined", "expired", "cancelled"]).optional(),
223
+ record_id: z.string().optional().describe("Only the requests for this Airtable record"),
224
+ limit: z.number().int().min(1).max(100).optional(),
225
+ act_as: actAs,
226
+ },
227
+ run(async (args) => {
228
+ const query = new URLSearchParams();
229
+ for (const key of ["status", "record_id", "limit"]) if (args[key] !== undefined) query.set(key, String(args[key]));
230
+ const qs = query.toString();
231
+ return json(await call("GET", `/mcp/flows/${encodeURIComponent(args.automation_id)}/signatures${qs ? `?${qs}` : ""}`, null, args));
232
+ })
233
+ );
234
+
235
+ server.tool(
236
+ "cancel_signature",
237
+ "Cancel a pending signature request. Every pending signer is emailed that the document was cancelled, so ONLY when the user asked for it: user_confirmation is their exact words; it is logged.",
238
+ {
239
+ automation_id: z.string(),
240
+ request_id: z.string().describe("From list_signatures"),
241
+ user_confirmation: z.string().min(1).describe("The user's exact words asking to cancel"),
242
+ reason: z.string().optional(),
243
+ act_as: actAs,
244
+ },
245
+ run(async (args) => {
246
+ const { automation_id, request_id, act_as, ...body } = args;
247
+ return json(await call("POST", `/mcp/flows/${encodeURIComponent(automation_id)}/signatures/${encodeURIComponent(request_id)}/cancel`, body, { act_as }));
248
+ })
249
+ );
250
+ }
package/src/index.js CHANGED
@@ -1,222 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
- import { z } from "zod";
6
- import { TEMPLATE_CREATION_PROMPT } from "./prompt.js";
3
+ /**
4
+ * Kept so that anything pinned to the old entrypoint still starts. The code
5
+ * moved to stdio.js when the tools were extracted into server.js, so that the
6
+ * worker could serve the same tools over HTTP.
7
+ */
7
8
 
8
- const API_URL = process.env.TYPEFLOW_API_URL || "https://premium.typeflow.us";
9
- const API_KEY = process.env.TYPEFLOW_API_KEY;
10
-
11
- if (!API_KEY) {
12
- console.error("TYPEFLOW_API_KEY environment variable is required");
13
- process.exit(1);
14
- }
15
-
16
- // ============================================================
17
- // API Client
18
- // ============================================================
19
-
20
- async function apiRequest(method, path, body) {
21
- const options = {
22
- method,
23
- headers: {
24
- "x-typeflow-api-key": API_KEY,
25
- "Content-Type": "application/json",
26
- },
27
- };
28
-
29
- if (body) {
30
- options.body = JSON.stringify(body);
31
- }
32
-
33
- const response = await fetch(`${API_URL}/api${path}`, options);
34
-
35
- if (!response.ok) {
36
- const error = await response.json().catch(() => ({ error: response.statusText }));
37
- throw new Error(`TypeFlow API error (${response.status}): ${error.error || response.statusText}`);
38
- }
39
-
40
- return response.json();
41
- }
42
-
43
- // ============================================================
44
- // MCP Server
45
- // ============================================================
46
-
47
- const server = new McpServer({
48
- name: "typeflow",
49
- version: "0.1.1",
50
- instructions: "TypeFlow MCP Server for creating HTML/CSS PDF templates. IMPORTANT: You MUST call the get_template_guide tool before creating or updating any template. This is mandatory - the guide contains all the rules for generating compatible HTML.",
51
- });
52
-
53
- // ============================================================
54
- // Tool: get_template_guide
55
- // ============================================================
56
-
57
- server.tool(
58
- "get_template_guide",
59
- "Returns the COMPLETE TypeFlow template creation guide with all HTML/CSS rules, variable syntax, loop structures, image handling, and examples. You MUST call this before creating or updating any template.",
60
- {},
61
- async () => {
62
- return {
63
- content: [
64
- {
65
- type: "text",
66
- text: TEMPLATE_CREATION_PROMPT,
67
- },
68
- ],
69
- };
70
- }
71
- );
72
-
73
- // ============================================================
74
- // Tool: create_template
75
- // ============================================================
76
-
77
- server.tool(
78
- "create_template",
79
- `Create a new HTML template in the user's TypeFlow template library.
80
-
81
- IMPORTANT: You MUST call get_template_guide first before generating any HTML. The guide contains all the rules you need.
82
-
83
- The template is saved to the library and can later be used when creating flows in TypeFlow.`,
84
- {
85
- name: z.string().describe("Template name (e.g. 'Drilling Report Q2')"),
86
- html: z.string().describe("HTML content without <style> tags. Must follow TypeFlow template rules from server instructions."),
87
- css: z.string().describe("CSS content without <style> wrapper"),
88
- description: z.string().optional().describe("What the template is for"),
89
- page_format: z.enum(["a4", "a4-landscape", "a5", "a5-landscape", "letter", "letter-landscape", "legal", "legal-landscape"]).optional().describe("Page format. Default: a4"),
90
- tags: z.array(z.string()).optional().describe("Tags for organization (e.g. ['drilling', 'report'])"),
91
- },
92
- async (args) => {
93
- const result = await apiRequest("POST", "/mcp/templates", {
94
- name: args.name,
95
- html: args.html,
96
- css: args.css,
97
- description: args.description,
98
- page_format: args.page_format || "a4",
99
- tags: args.tags,
100
- });
101
-
102
- return {
103
- content: [
104
- {
105
- type: "text",
106
- text: `Template created successfully!\n\nID: ${result.id}\nName: ${result.name}\n\nThe template is now in your TypeFlow library. Open TypeFlow to create a flow using this template.`,
107
- },
108
- ],
109
- };
110
- }
111
- );
112
-
113
- // ============================================================
114
- // Tool: list_templates
115
- // ============================================================
116
-
117
- server.tool(
118
- "list_templates",
119
- "List all templates in the user's TypeFlow template library.",
120
- {
121
- tag: z.string().optional().describe("Filter by tag"),
122
- },
123
- async (args) => {
124
- const params = new URLSearchParams();
125
- if (args.tag) params.set("tag", args.tag);
126
-
127
- const queryString = params.toString();
128
- const path = `/mcp/templates${queryString ? `?${queryString}` : ""}`;
129
- const result = await apiRequest("GET", path);
130
-
131
- if (!result.templates || result.templates.length === 0) {
132
- return {
133
- content: [{ type: "text", text: "No templates found in your library." }],
134
- };
135
- }
136
-
137
- const list = result.templates.map((t) =>
138
- `- **${t.name}** (${t.page_format || "a4"})${t.description ? ` - ${t.description}` : ""}${t.tags?.length ? ` [${t.tags.join(", ")}]` : ""}\n ID: ${t.id}`
139
- ).join("\n");
140
-
141
- return {
142
- content: [{ type: "text", text: `Your template library:\n\n${list}` }],
143
- };
144
- }
145
- );
146
-
147
- // ============================================================
148
- // Tool: get_template
149
- // ============================================================
150
-
151
- server.tool(
152
- "get_template",
153
- "Get full details of a template including HTML, CSS, and detected variables/loops.",
154
- {
155
- id: z.string().describe("Template UUID"),
156
- },
157
- async (args) => {
158
- const result = await apiRequest("GET", `/mcp/templates/${args.id}`);
159
-
160
- const info = [
161
- `**${result.name}**`,
162
- result.description ? `Description: ${result.description}` : null,
163
- `Format: ${result.page_format || "a4"}`,
164
- result.tags?.length ? `Tags: ${result.tags.join(", ")}` : null,
165
- "",
166
- `**Variables found:** ${result.variables?.length ? result.variables.join(", ") : "none"}`,
167
- `**Loops found:** ${result.loops?.length ? result.loops.join(", ") : "none"}`,
168
- "",
169
- "--- HTML ---",
170
- result.html,
171
- "",
172
- "--- CSS ---",
173
- result.css,
174
- ].filter(Boolean).join("\n");
175
-
176
- return {
177
- content: [{ type: "text", text: info }],
178
- };
179
- }
180
- );
181
-
182
- // ============================================================
183
- // Tool: update_template
184
- // ============================================================
185
-
186
- server.tool(
187
- "update_template",
188
- `Update an existing template in the user's TypeFlow template library.
189
-
190
- Use this to iterate on a template - change the HTML, CSS, name, description, or page format. Fetch the template first with get_template to see the current state, then update what needs to change.
191
-
192
- YOU MUST FOLLOW THE SAME TEMPLATE CREATION RULES as create_template when generating HTML/CSS.`,
193
- {
194
- id: z.string().describe("Template UUID to update"),
195
- html: z.string().optional().describe("New HTML content (replaces existing)"),
196
- css: z.string().optional().describe("New CSS content (replaces existing)"),
197
- name: z.string().optional().describe("New template name"),
198
- description: z.string().optional().describe("New description"),
199
- page_format: z.enum(["a4", "a4-landscape", "a5", "a5-landscape", "letter", "letter-landscape", "legal", "legal-landscape"]).optional().describe("New page format"),
200
- tags: z.array(z.string()).optional().describe("New tags"),
201
- },
202
- async (args) => {
203
- const { id, ...updates } = args;
204
- const result = await apiRequest("PATCH", `/mcp/templates/${id}`, updates);
205
-
206
- return {
207
- content: [
208
- {
209
- type: "text",
210
- text: `Template updated successfully!\n\nID: ${result.id}\nName: ${result.name}`,
211
- },
212
- ],
213
- };
214
- }
215
- );
216
-
217
- // ============================================================
218
- // Start
219
- // ============================================================
220
-
221
- const transport = new StdioServerTransport();
222
- await server.connect(transport);
9
+ import "./stdio.js";
package/src/server.js ADDED
@@ -0,0 +1,461 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { z } from "zod";
3
+ import { registerFlowTools } from "./flow-tools.js";
4
+
5
+ /**
6
+ * What to tell the model about page formats.
7
+ *
8
+ * Deliberately a description rather than a z.enum. The published 0.1.x
9
+ * hard-coded eight ISO and US sizes, taken from the May specification, and so
10
+ * refused every label format the product actually ships - label-100x150,
11
+ * label-100x100, label-100x60, label-100x50, label-102x152, label-54x86,
12
+ * label-a5 - along with a3, b4, b5 and ledger. A user with a thermal printer
13
+ * could not create their template at all, and "Unknown page_format" gave no
14
+ * hint that the list in the client was the thing that was wrong.
15
+ *
16
+ * src/utils/page-formats.js in the app is the one table, and /api/mcp/templates
17
+ * validates against it. A second list here could only ever drift from it, the
18
+ * way the bundled prompt did. The API returns the valid ids on a bad value, so
19
+ * a wrong guess corrects itself in one round trip.
20
+ */
21
+ const PAGE_FORMAT_HINT =
22
+ "Page format id. Common: a4, a4-landscape, letter, letter-landscape, a5, a3, legal. " +
23
+ "Labels: label-100x150, label-100x100, label-100x60, label-100x50, label-102x152, " +
24
+ "label-54x86, label-a5. For a size that is none of these, pass 'custom' together " +
25
+ "with page_width_mm and page_height_mm. Default: a4";
26
+
27
+ // ============================================================
28
+ // The template rules
29
+ //
30
+ // Fetched, not bundled. Versions 0.1.0 to 0.1.4 shipped their own copy in
31
+ // prompt.js and decision-tree.js, cut from the app's
32
+ // src/lib/ai-template/system-prompt.js and then left behind: by October 2026
33
+ // the copy was five months old and three rules stale, one of which had been
34
+ // reversed in the app. Templates built here were generated against rules we
35
+ // already knew to be wrong, and nothing surfaced that - the tools returned
36
+ // confident, outdated text.
37
+ //
38
+ // Fetching makes a stale client impossible rather than unlikely, and lets a
39
+ // corrected rendering rule reach every user without an npm release. Cached for
40
+ // the process lifetime: the guide is requested once or twice per conversation,
41
+ // and the server is short-lived.
42
+ // ============================================================
43
+
44
+ let cachedPrompt = null;
45
+
46
+ async function getPrompt() {
47
+ if (cachedPrompt) return cachedPrompt;
48
+
49
+ const result = await apiRequest("GET", "/mcp/prompt");
50
+
51
+ if (!result?.prompt) {
52
+ throw new Error("TypeFlow returned an empty template guide");
53
+ }
54
+
55
+ cachedPrompt = result.prompt;
56
+ return cachedPrompt;
57
+ }
58
+
59
+ /**
60
+ * One server per caller.
61
+ *
62
+ * stdio builds one at startup and keeps it for the process. The HTTP
63
+ * entrypoint builds one per request and closes it, because the apiRequest it
64
+ * closes over carries that caller's credentials - a shared instance would
65
+ * serve one user's templates to another.
66
+ */
67
+ export function createTypeFlowMcpServer({ apiRequest, version }) {
68
+ const server = new McpServer({
69
+ name: "typeflow",
70
+ version,
71
+ instructions:
72
+ "TypeFlow MCP Server for creating HTML/CSS PDF templates. " +
73
+ "IMPORTANT: before creating or updating any template you MUST call " +
74
+ "get_template_guide, which returns the HTML/CSS rendering rules and the " +
75
+ "Airtable-schema-to-variable compilation rules together. When the template " +
76
+ "binds to Airtable data, also call get_airtable_schema first: TypeFlow " +
77
+ "maps variables by exact field name, so a guessed name maps to nothing. " +
78
+ "Templates are saved to the user's TypeFlow library, where they can be " +
79
+ "picked when creating a flow. To set up a flow directly: create_flow, " +
80
+ "update_flow_template, set_mapping, generate_test, then let the user " +
81
+ "check the flow in their browser before activate_flow. For e-signature: " +
82
+ "get_esignature, then configure_esignature; list_signatures follows them up."
83
+ });
84
+
85
+ // The guide is identical for every user and carries no user data, so one
86
+ // cache per server instance is enough and a shared one would also be
87
+ // correct. If the guide ever becomes per-user, this must not be hoisted
88
+ // out of the factory.
89
+ let cachedPrompt = null;
90
+
91
+ async function getPrompt() {
92
+ if (cachedPrompt) return cachedPrompt;
93
+
94
+ const result = await apiRequest("GET", "/mcp/prompt");
95
+
96
+ if (!result?.prompt) {
97
+ throw new Error("TypeFlow returned an empty template guide");
98
+ }
99
+
100
+ cachedPrompt = result.prompt;
101
+ return cachedPrompt;
102
+ }
103
+
104
+ // ============================================================
105
+ // Tool: get_template_guide
106
+ // ============================================================
107
+
108
+ server.tool(
109
+ "get_template_guide",
110
+ "Returns the COMPLETE TypeFlow template creation guide: HTML/CSS rules, variable syntax, loop structures, image handling, examples, and the decision tree for turning an Airtable schema into TypeFlow variables. You MUST call this before creating or updating any template.",
111
+ {},
112
+ async () => {
113
+ try {
114
+ return {
115
+ content: [{ type: "text", text: await getPrompt() }],
116
+ };
117
+ } catch (err) {
118
+ return {
119
+ content: [
120
+ {
121
+ type: "text",
122
+ text:
123
+ `Could not fetch the template guide: ${err.message}\n\n` +
124
+ "Do not generate a template without it - the rules change and " +
125
+ "guessing produces documents that fail to render. Check " +
126
+ "TYPEFLOW_API_KEY and that premium.typeflow.us is reachable.",
127
+ },
128
+ ],
129
+ isError: true,
130
+ };
131
+ }
132
+ }
133
+ );
134
+
135
+ // ============================================================
136
+ // Tool: get_airtable_schema
137
+ // ============================================================
138
+
139
+ server.tool(
140
+ "get_airtable_schema",
141
+ `List the user's Airtable bases, or read the tables and fields of one.
142
+
143
+ Call with no arguments to list the bases this account can reach. Call with a base_id to get its tables, fields and field types.
144
+
145
+ Read this BEFORE writing a template that binds to Airtable data. TypeFlow maps variables by name: {{Invoice Number}} binds to a field called exactly "Invoice Number" and to nothing else. A template written against guessed field names maps to nothing, and the user finds out one field at a time in the editor.
146
+
147
+ Returns structure only - table names, field names, field types. No record data.`,
148
+ {
149
+ base_id: z
150
+ .string()
151
+ .optional()
152
+ .describe("Airtable base id (appXXXXXXXXXXXXXX). Omit to list the available bases."),
153
+ },
154
+ async (args) => {
155
+ const path = args.base_id
156
+ ? `/mcp/airtable-schema?base_id=${encodeURIComponent(args.base_id)}`
157
+ : "/mcp/airtable-schema";
158
+
159
+ const result = await apiRequest("GET", path);
160
+
161
+ if (result.bases) {
162
+ if (result.bases.length === 0) {
163
+ return {
164
+ content: [{ type: "text", text: "No Airtable bases reachable with this connection." }],
165
+ };
166
+ }
167
+
168
+ const list = result.bases.map((b) => `- ${b.name}\n ${b.id}`).join("\n");
169
+ return {
170
+ content: [
171
+ {
172
+ type: "text",
173
+ text: `Airtable bases:\n\n${list}\n\nCall get_airtable_schema again with one of these base_id values to see its tables and fields.`,
174
+ },
175
+ ],
176
+ };
177
+ }
178
+
179
+ const tables = (result.tables || []).map((t) => {
180
+ const fields = t.fields
181
+ .map((f) => {
182
+ const extra = [
183
+ f.linkedTableId ? `links to ${f.linkedTableId}` : null,
184
+ f.choices ? `choices: ${f.choices.join(" | ")}` : null,
185
+ ].filter(Boolean).join(", ");
186
+ return ` - ${f.name} (${f.type})${extra ? ` [${extra}]` : ""}`;
187
+ })
188
+ .join("\n");
189
+ return ` ${t.name} (${t.id})\n${fields}`;
190
+ }).join("\n\n");
191
+
192
+ return {
193
+ content: [{ type: "text", text: `Base ${result.baseId}\n\n${tables}` }],
194
+ };
195
+ }
196
+ );
197
+
198
+ // ============================================================
199
+ // Tool: create_template
200
+ // ============================================================
201
+
202
+ server.tool(
203
+ "create_template",
204
+ `Create a new HTML template in the user's TypeFlow template library.
205
+
206
+ IMPORTANT: You MUST call get_template_guide first before generating any HTML. The guide contains all the rules you need.
207
+
208
+ The template is saved to the library and can later be picked when creating a flow in TypeFlow.`,
209
+ {
210
+ name: z.string().describe("Template name (e.g. 'Drilling Report Q2')"),
211
+ html: z.string().describe("HTML content without <style> tags. Must follow the rules from get_template_guide."),
212
+ css: z.string().describe("CSS content without <style> wrapper"),
213
+ description: z.string().optional().describe("What the template is for"),
214
+ page_format: z.string().optional().describe(PAGE_FORMAT_HINT),
215
+ page_width_mm: z.number().optional().describe("Page width in millimetres. Required when page_format is 'custom'."),
216
+ page_height_mm: z.number().optional().describe("Page height in millimetres. Required when page_format is 'custom'."),
217
+ tags: z.array(z.string()).optional().describe("Tags for organization (e.g. ['drilling', 'report'])"),
218
+ },
219
+ async (args) => {
220
+ const result = await apiRequest("POST", "/mcp/templates", {
221
+ name: args.name,
222
+ html: args.html,
223
+ css: args.css,
224
+ description: args.description,
225
+ page_format: args.page_format || "a4",
226
+ page_width_mm: args.page_width_mm,
227
+ page_height_mm: args.page_height_mm,
228
+ tags: args.tags,
229
+ });
230
+
231
+ return {
232
+ content: [
233
+ {
234
+ type: "text",
235
+ text: `Template created.\n\nID: ${result.id}\nName: ${result.name}\n\nIt is now in the TypeFlow library and can be picked when creating a flow.`,
236
+ },
237
+ ],
238
+ };
239
+ }
240
+ );
241
+
242
+ // ============================================================
243
+ // Tool: list_templates
244
+ // ============================================================
245
+
246
+ server.tool(
247
+ "list_templates",
248
+ "List all templates in the user's TypeFlow template library.",
249
+ {
250
+ tag: z.string().optional().describe("Filter by tag"),
251
+ },
252
+ async (args) => {
253
+ const params = new URLSearchParams();
254
+ if (args.tag) params.set("tag", args.tag);
255
+
256
+ const queryString = params.toString();
257
+ const result = await apiRequest("GET", `/mcp/templates${queryString ? `?${queryString}` : ""}`);
258
+
259
+ if (!result.templates || result.templates.length === 0) {
260
+ return {
261
+ content: [{ type: "text", text: "No templates found in your library." }],
262
+ };
263
+ }
264
+
265
+ const list = result.templates.map((t) =>
266
+ `- **${t.name}** (${t.page_format || "a4"})${t.description ? ` - ${t.description}` : ""}${t.tags?.length ? ` [${t.tags.join(", ")}]` : ""}\n ID: ${t.id}`
267
+ ).join("\n");
268
+
269
+ return {
270
+ content: [{ type: "text", text: `Your template library:\n\n${list}` }],
271
+ };
272
+ }
273
+ );
274
+
275
+ // ============================================================
276
+ // Tool: get_template
277
+ // ============================================================
278
+
279
+ server.tool(
280
+ "get_template",
281
+ "Get full details of a template including HTML, CSS, and the variables and loops it contains.",
282
+ {
283
+ id: z.string().describe("Template UUID"),
284
+ },
285
+ async (args) => {
286
+ const result = await apiRequest("GET", `/mcp/templates/${args.id}`);
287
+
288
+ const info = [
289
+ `**${result.name}**`,
290
+ result.description ? `Description: ${result.description}` : null,
291
+ `Format: ${result.page_format || "a4"}`,
292
+ result.tags?.length ? `Tags: ${result.tags.join(", ")}` : null,
293
+ "",
294
+ `**Variables found:** ${result.variables?.length ? result.variables.join(", ") : "none"}`,
295
+ `**Loops found:** ${result.loops?.length ? result.loops.join(", ") : "none"}`,
296
+ "",
297
+ "--- HTML ---",
298
+ result.html,
299
+ "",
300
+ "--- CSS ---",
301
+ result.css,
302
+ ].filter(Boolean).join("\n");
303
+
304
+ return {
305
+ content: [{ type: "text", text: info }],
306
+ };
307
+ }
308
+ );
309
+
310
+ // ============================================================
311
+ // Tool: update_template
312
+ // ============================================================
313
+
314
+ server.tool(
315
+ "update_template",
316
+ `Update an existing template in the user's TypeFlow template library.
317
+
318
+ Use this to iterate on a template - change the HTML, CSS, name, description, or page format. Fetch the template first with get_template to see the current state, then update what needs to change.
319
+
320
+ YOU MUST FOLLOW THE SAME TEMPLATE RULES as create_template when generating HTML/CSS. Call get_template_guide if you have not already.`,
321
+ {
322
+ id: z.string().describe("Template UUID to update"),
323
+ html: z.string().optional().describe("New HTML content (replaces existing)"),
324
+ css: z.string().optional().describe("New CSS content (replaces existing)"),
325
+ name: z.string().optional().describe("New template name"),
326
+ description: z.string().optional().describe("New description"),
327
+ page_format: z.string().optional().describe("New " + PAGE_FORMAT_HINT),
328
+ page_width_mm: z.number().optional().describe("New page width in millimetres, with page_format 'custom'."),
329
+ page_height_mm: z.number().optional().describe("New page height in millimetres, with page_format 'custom'."),
330
+ tags: z.array(z.string()).optional().describe("New tags"),
331
+ },
332
+ async (args) => {
333
+ const { id, ...updates } = args;
334
+ const result = await apiRequest("PATCH", `/mcp/templates/${id}`, updates);
335
+
336
+ return {
337
+ content: [
338
+ {
339
+ type: "text",
340
+ text: `Template updated.\n\nID: ${result.id}\nName: ${result.name}`,
341
+ },
342
+ ],
343
+ };
344
+ }
345
+ );
346
+
347
+ // ============================================================
348
+ // Tool: delete_template
349
+ // ============================================================
350
+
351
+ server.tool(
352
+ "delete_template",
353
+ "Delete a template from the user's TypeFlow library. Flows already created from it are not affected - they hold their own copy of the HTML.",
354
+ {
355
+ id: z.string().describe("Template UUID to delete"),
356
+ },
357
+ async (args) => {
358
+ const result = await apiRequest("DELETE", `/mcp/templates/${args.id}`);
359
+
360
+ return {
361
+ content: [{ type: "text", text: `Template ${result.id} deleted from your library.` }],
362
+ };
363
+ }
364
+ );
365
+
366
+ // ============================================================
367
+ // Tool: validate_template
368
+ // ============================================================
369
+
370
+ server.tool(
371
+ "validate_template",
372
+ `Validate an HTML template against an Airtable schema before creating it.
373
+
374
+ Returns hard errors (template will fail) and warnings (template works but may have issues).
375
+ Always call this after generating HTML and before calling create_template.
376
+
377
+ If the schema is omitted, only structural HTML/CSS checks are performed (no variable validation).`,
378
+ {
379
+ html: z.string().describe("The template HTML string to validate"),
380
+ schema: z.object({
381
+ mainTable: z.object({
382
+ name: z.string(),
383
+ id: z.string(),
384
+ fields: z.array(z.object({
385
+ name: z.string(),
386
+ type: z.string(),
387
+ id: z.string(),
388
+ options: z.any().optional(),
389
+ })),
390
+ }),
391
+ allTables: z.array(z.object({
392
+ name: z.string(),
393
+ id: z.string(),
394
+ fields: z.array(z.object({
395
+ name: z.string(),
396
+ type: z.string(),
397
+ id: z.string(),
398
+ options: z.any().optional(),
399
+ })).optional(),
400
+ })).optional(),
401
+ }).optional().describe("Airtable schema for semantic validation. If omitted, only structural checks run."),
402
+ },
403
+ async (args) => {
404
+ try {
405
+ const result = await apiRequest.validateTemplate({
406
+ html: args.html,
407
+ schema: args.schema || null,
408
+ });
409
+
410
+ // Format output for the agent
411
+ let output = "";
412
+
413
+ if (result.valid) {
414
+ output += "✅ Template is valid.\n\n";
415
+ } else {
416
+ output += `❌ Template has ${result.hardErrors.length} error(s) that must be fixed.\n\n`;
417
+ }
418
+
419
+ if (result.hardErrors.length > 0) {
420
+ output += "**Hard Errors (must fix):**\n";
421
+ for (const err of result.hardErrors) {
422
+ output += `- [${err.type}] ${err.message}`;
423
+ if (err.variable) output += ` (variable: ${err.variable})`;
424
+ if (err.suggestedFix) output += `\n → Fix: ${err.suggestedFix}`;
425
+ if (err.autoFixable) output += ` (auto-fixable)`;
426
+ output += "\n";
427
+ }
428
+ output += "\n";
429
+ }
430
+
431
+ if (result.warnings.length > 0) {
432
+ output += "**Warnings (won't break, but review):**\n";
433
+ for (const warn of result.warnings) {
434
+ output += `- [${warn.type}] ${warn.message}`;
435
+ if (warn.suggestedFix) output += `\n → Consider: ${warn.suggestedFix}`;
436
+ output += "\n";
437
+ }
438
+ output += "\n";
439
+ }
440
+
441
+ output += `**Summary:** ${result.summary.totalVariables} variables, ${result.summary.hardErrorCount} errors, ${result.summary.warningCount} warnings`;
442
+ if (result.summary.loops.length > 0) output += `, loops: ${result.summary.loops.join(", ")}`;
443
+ if (result.summary.tableLoops.length > 0) output += `, table_loops: ${result.summary.tableLoops.join(", ")}`;
444
+ if (result.summary.esignatureFields > 0) output += `, e-signature: ${result.summary.esignatureFields} fields`;
445
+
446
+ return {
447
+ content: [{ type: "text", text: output }],
448
+ };
449
+ } catch (err) {
450
+ return {
451
+ content: [{ type: "text", text: `Validation failed: ${err.message}` }],
452
+ isError: true,
453
+ };
454
+ }
455
+ }
456
+ );
457
+
458
+ registerFlowTools(server, apiRequest);
459
+
460
+ return server;
461
+ }
package/src/stdio.js ADDED
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * The stdio entrypoint: one process, one user, credentials from the
5
+ * environment. Claude Desktop and any other stdio client land here.
6
+ *
7
+ * Everything the model sees - the tools, their descriptions, their schemas -
8
+ * lives in server.js, which knows nothing about transports. The HTTP
9
+ * entrypoint in typeflow-worker builds the same server with a different
10
+ * apiRequest.
11
+ */
12
+
13
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
14
+ import { readFileSync } from "node:fs";
15
+ import { fileURLToPath } from "node:url";
16
+ import { dirname, join } from "node:path";
17
+
18
+ import { createTypeFlowMcpServer } from "./server.js";
19
+ import { createApiClient } from "./api-client.js";
20
+
21
+ const __dirname = dirname(fileURLToPath(import.meta.url));
22
+
23
+ const { version: VERSION } = JSON.parse(
24
+ readFileSync(join(__dirname, "..", "package.json"), "utf8")
25
+ );
26
+
27
+ const API_URL = process.env.TYPEFLOW_API_URL || "https://premium.typeflow.us";
28
+ const API_KEY = process.env.TYPEFLOW_API_KEY;
29
+
30
+ if (!API_KEY) {
31
+ console.error("TYPEFLOW_API_KEY environment variable is required");
32
+ process.exit(1);
33
+ }
34
+
35
+ const apiRequest = createApiClient({
36
+ apiUrl: API_URL,
37
+ headers: { "x-typeflow-api-key": API_KEY },
38
+ });
39
+
40
+ const server = createTypeFlowMcpServer({ apiRequest, version: VERSION });
41
+
42
+ const transport = new StdioServerTransport();
43
+ await server.connect(transport);
package/src/prompt.js DELETED
@@ -1 +0,0 @@
1
- export const TEMPLATE_CREATION_PROMPT = "# TypeFlow HTML Template Creation Guide\n\nYou are an expert at creating visually stunning HTML/CSS templates for GrapesJS that will be used with TypeFlow (a PDF generation system from Airtable data). You create professional, design-forward documents — not just basic invoices, but sales collateral, real estate brochures, catalogs, certificates, and more.\n\n---\n\n## STEP 1 — GATHER REQUIREMENTS\n\nBefore writing any code, ask the user:\n\n1. **Document type** — What kind of document? (invoice, quote, sales brochure, real estate listing, product catalog, certificate, delivery note, print label, contract, report, etc.)\n2. **Page format** — What size and orientation?\n - Standard: `A4`, `A5`, `Letter`, `Legal`\n - Orientation: `portrait` (default) or `landscape`\n - Custom: width × height in mm (e.g., `100mm × 60mm`)\n - Print labels: specific dimensions (e.g., `62mm × 29mm`)\n - **IMPORTANT: If the document type is a label, ALWAYS ask the user for the exact label dimensions before creating anything. Labels come in many sizes (Avery 5160, 4x6\", 2x3\", custom) and defaulting to A4 will produce a wrong result. Ask: \"What are the dimensions of your label? (e.g., 4x6 inches, 100x60mm, Avery 5160)\"**\n3. **Style / mood** — What visual direction? (minimalist, bold/colorful, editorial/magazine, corporate, luxury, playful, etc.) Ask for reference images or colors if possible.\n4. **Content structure** — What sections does the document need? (header, hero image, description, line items table, totals, footer, etc.)\n5. **Variables** — What data fields come from Airtable? List them. The user provides the field names.\n6. **Repeating data** — Are there line items or repeating blocks?\n - Simple line items in a table → `loop_0` (multiple linked tables: `loop_0`, `loop_1`, `loop_2`...)\n - Entire block repeated per record → `table_loop_0`\n - Parent/child grouped data → `nested_0` / `nested_items_0`\n7. **Images** — Any images?\n - Fixed images (logo, background): user provides URLs\n - Dynamic images from Airtable: `{{image_field}}`\n8. **Special features** — Barcodes (`{{barcode:field}}`), checkboxes (`{{checkbox:field|value}}`), page numbers (`{{page_number}}` / `{{total_pages}}`), today's date (`{{Today}}`)?\n\n---\n\n## STEP 2 — PAGE SETUP\n\n### The page sizing model\n\nUnderstanding how Typeflow generates PDFs is critical:\n\n1. **GrapesJS editor** uses a canvas in **pixels** (A4 = 794×1123px at 96 DPI)\n2. **GrapesJS auto-injects** `@page { size: 794px 1123px; margin: 0; }` into the CSS when saving\n3. **PDFShift** receives the HTML + the page format (e.g., `A4` or `210mmx297mm` for custom)\n4. **PDFShift renders in screen mode** (`use_print: false`) — this means `@media print` is IGNORED and the content flows like a web page\n5. **PDFShift adds its own margins** on top (default 0.7cm top/bottom, 0.5cm sides — can be overridden at document level)\n\n### CRITICAL rules\n\n**DO NOT:**\n- Set `width: 210mm` or `width: 794px` on `body` or top-level containers → causes horizontal overflow because of PDFShift margins\n- Use `@page` rules in your CSS → GrapesJS strips them and replaces with its own\n- Rely on `@media print` → PDFShift ignores it\n- Leave colored page sections without a `min-height` → they collapse to content size, leaving white space below\n\n**DO:**\n- Establish a full height chain: `html, body { height: 100%; min-height: 100% }`\n- Use `min-height: 297mm` (A4 portrait) on each top-level \"page\" section (cover, content, back cover) — this is the **only reliable way** to force a colored background to fill the entire PDF page\n- Use `width: 100%` on top-level sections (not `210mm`)\n- Use `display: flex; flex-direction: column` on `.cover-page` etc. so inner sections can use `flex: 1` to push content down\n\n### What NOT to do\n\n```css\n/* ❌ WRONG — causes right/bottom overflow in PDF */\n@page {\n size: A4 portrait;\n margin: 0;\n}\nbody {\n width: 210mm; /* overflows horizontally */\n min-height: 297mm;\n}\n.cover-page {\n width: 210mm; /* overflows horizontally */\n min-height: 297mm;\n}\n```\n\n### What TO do (canonical pattern)\n\n```css\n/* ✅ CORRECT — establishes a full-height chain and uses min-height in mm on inner containers */\n* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n print-color-adjust: exact;\n -webkit-print-color-adjust: exact;\n}\n\nhtml, body {\n width: 100%;\n height: 100%;\n min-height: 100%;\n}\n\nbody {\n font-family: 'Inter', sans-serif;\n color: #1a1a1a;\n}\n\n/* Top-level \"pages\" (sections that should each fill one PDF page) */\n.cover-page,\n.content-page,\n.back-cover {\n width: 100%;\n min-height: 297mm; /* A4 portrait height — ONLY used on inner sections, never body */\n display: flex;\n flex-direction: column;\n position: relative;\n}\n\n.cover-page,\n.content-page {\n page-break-after: always;\n}\n\n.back-cover {\n page-break-before: always;\n}\n```\n\n### Why `min-height: 297mm` works on `.cover-page` but breaks on `body`\n\n- On **`body` or `html`**: it interacts with PDFShift page margins (PDFShift uses screen mode, `use_print: false`) and causes horizontal overflow because the effective page width is less than 210mm.\n- On **an inner flex container** (`.cover-page`): it's just a normal CSS constraint — the element grows to at least 297mm tall, and since the body has no fixed width, there's no horizontal conflict.\n\n### Full-bleed sections inside a cover\n\nTo have a hero image fill the full width AND some content at the bottom fill the rest vertically:\n\n```css\n.cover-page {\n width: 100%;\n min-height: 297mm;\n display: flex;\n flex-direction: column;\n background: #1a3c34;\n}\n\n.cover-hero {\n width: 100%;\n height: 620px; /* fixed hero height */\n overflow: hidden;\n}\n\n.cover-bottom {\n flex: 1; /* fills the remaining space down to the bottom */\n padding: 40px 56px;\n}\n```\n\nWith `flex: 1`, `.cover-bottom` grows to fill whatever space is left below the hero, ensuring the colored background reaches the bottom of the page.\n\n### A4 dimensions reference\n\n| Format | Portrait (W × H) | Landscape (W × H) |\n|--------|------------------|--------------------|\n| A4 | 210mm × 297mm | 297mm × 210mm |\n| A5 | 148mm × 210mm | 210mm × 148mm |\n| Letter | 216mm × 279mm | 279mm × 216mm |\n| Legal | 216mm × 356mm | 356mm × 216mm |\n\nUse these values for `min-height` on top-level sections only.\n\n### Page dimensions reference (for sizing sections, not containers)\n\nUse these numbers when you need to know the available area for hero images, full-bleed sections, etc. **Don't set them as the body width.**\n\n| Format | Portrait (W × H in px) | Landscape (W × H in px) |\n|--------|------------------------|--------------------------|\n| A4 | 794 × 1123 | 1123 × 794 |\n| A5 | 559 × 794 | 794 × 559 |\n| Letter | 816 × 1056 | 1056 × 816 |\n| Legal | 816 × 1344 | 1344 × 816 |\n\n### Format and orientation\n\nThe page format (A4, A5, Letter, custom, landscape) is set at the **document level in Typeflow**, not in the CSS. When the user selects \"A4 landscape\", Typeflow configures PDFShift accordingly. Your CSS should just flow content naturally.\n\n### Print labels\n\nFor small format labels, the page is configured at document level. Keep the HTML flowing naturally:\n\n```css\n.label {\n padding: 6px;\n font-family: 'Inter', sans-serif;\n}\n.label-header {\n font-size: 9px;\n font-weight: 600;\n}\n.label-barcode {\n text-align: center;\n margin: 4px 0;\n}\n```\n\n### Multi-page documents\n\nFor multi-page (cover + content + back cover), use page breaks between sections:\n\n```html\n<div class=\"cover-page\">\n <!-- Cover content -->\n</div>\n\n<div class=\"content-page\">\n <!-- Main content -->\n</div>\n\n<div class=\"back-cover\">\n <!-- Back cover content -->\n</div>\n```\n\n```css\n.content-page,\n.back-cover {\n page-break-before: always;\n}\n```\n\nEach section flows within one page naturally — do NOT set `min-height: 297mm` or similar, as it breaks the flow.\n\n### Manual page break block (GrapesJS compatible)\n\n```html\n<div data-type-role=\"page-break\" class=\"gjs-plg-page-break\"></div>\n```\n\n```css\n.gjs-plg-page-break,\n[data-type-role=\"page-break\"] {\n break-after: page !important;\n page-break-after: always !important;\n height: 0 !important;\n margin: 0 !important;\n padding: 0 !important;\n border: none !important;\n}\n```\n\n### Recurring headers and footers\n\nUse the `<header>` and `<footer>` HTML tags to create content that **repeats on every page** of the PDF. TypeFlow automatically extracts these tags from the template and passes them to the PDF renderer as recurring elements.\n\n**How it works:**\n- `<header>` content appears at the top of every page\n- `<footer>` content appears at the bottom of every page\n- The relevant CSS (matching IDs and classes used inside the header/footer) is automatically extracted and injected\n- The tags are removed from the main body content to avoid duplication\n\n**Header example (logo repeating on every page):**\n\n```html\n<header style=\"padding: 10px 10mm; display: flex; align-items: center;\">\n <img src=\"https://example.com/logo.png\" alt=\"Logo\" style=\"height: 30px;\">\n</header>\n```\n\n**Footer example (company info + page numbers):**\n\n```html\n<footer style=\"padding: 4px 10mm; text-align: center; border-top: 0.5px solid #eeeeee; font-size: 6pt; color: #777777; font-family: Arial, sans-serif;\">\n <span>Company Name - Address - Phone</span>\n <span>Page {{page_number}} of {{total_pages}}</span>\n</footer>\n```\n\n**Rules:**\n- Use inline styles on `<header>` and `<footer>` tags (CSS classes work too but inline is simpler since the CSS extraction is automatic)\n- Keep header/footer content simple - text, logos, page numbers\n- `{{page_number}}` and `{{total_pages}}` work inside headers and footers\n- TypeFlow variables (`{{field_name}}`) also work inside headers/footers - they are replaced before PDF generation\n- Do NOT wrap `<header>`/`<footer>` inside other containers - they must be top-level elements in the HTML\n- Do NOT use `<header>`/`<footer>` for content that should appear only once - use regular `<div>` sections instead\n\n### Unit conversion cheatsheet (if porting from mm)\n\n- 1mm ≈ 3.78px (at 96 DPI)\n- 5mm ≈ 19px\n- 10mm ≈ 38px\n- 15mm ≈ 57px\n- 20mm ≈ 76px\n\nUse round px values that are close to the mm equivalents. For font sizes, use `px` or `pt` consistently — avoid mixing.\n\n---\n\n## STEP 3 — CRITICAL GRAPESJS RULES\n\n### 3.1 Text editability\n\nALL text content MUST be wrapped in `<span data-gjs-type=\"text\">`:\n\n```html\n<!-- Correct -->\n<h1><span data-gjs-type=\"text\">Company Name</span></h1>\n<p><span data-gjs-type=\"text\">{{client_name}}</span></p>\n\n<!-- Wrong — text not editable in GrapesJS -->\n<h1>Company Name</h1>\n```\n\n### 3.2 Tables — fixed layout\n\n```css\ntable {\n table-layout: fixed;\n width: 100%;\n border-collapse: collapse;\n}\ntd, th {\n word-wrap: break-word;\n overflow-wrap: break-word;\n}\n```\n\nSet column widths with nth-child:\n\n```css\ntd:nth-child(1) { width: 50%; }\ntd:nth-child(2) { width: 25%; }\ntd:nth-child(3) { width: 25%; }\n```\n\nAdd `class=\"table-body\"` on all `<tbody>` elements.\n\n### 3.2bis — CRITICAL: Flex containers with text content (rich text vars)\n\n**This is non-negotiable.** Any `display: flex` container that has children containing text (especially Airtable rich text variables like `{{What's Included}}`, `{{Description}}`, `{{Notes}}`, etc.) MUST follow this pattern, otherwise the content WILL overflow horizontally and break the entire PDF layout (cover misaligned, page wider than A4, content cut off).\n\n**Why:** Typeflow renders rich text variables with `&nbsp;` (non-breaking spaces) instead of regular spaces. `&nbsp;` forbids line breaks. Combined with flex's default `min-width: auto` on children, the flex item refuses to shrink → the row overflows → the document becomes wider than A4 → everything visually breaks.\n\n**The mandatory fix:**\n\n```css\n/* Parent flex row */\n.my-row {\n display: flex;\n gap: 30px;\n width: 100%;\n}\n\n/* Each flex column with text inside */\n.my-col {\n flex: 1 1 0; /* explicit basis 0 — DON'T just use `flex: 1` */\n min-width: 0; /* CRITICAL: overrides default min-width: auto */\n overflow-wrap: anywhere; /* MUST be `anywhere`, NOT `break-word` */\n word-break: break-word;\n}\n```\n\n**Important:**\n- `overflow-wrap: anywhere` is the **only** value that breaks across `&nbsp;`. `break-word` is NOT enough.\n- `min-width: 0` defeats flexbox's default `min-width: auto` which prevents shrinking below intrinsic content width.\n- `flex: 1 1 0` ensures basis is 0 (instead of `auto`).\n- `width: 100%` on the parent row anchors it to the available width.\n\n**Apply to EVERY flex container in your template that has text inside its children:**\n- `.includes-row` / `.includes-col`\n- `.terms-row` / `.terms-col`\n- `.price-row` / `.price-card`\n- `.cover-info-grid` / `.cover-info-item`\n- `.day-info-strip` / `.day-info-cell`\n- `.back-contact-row` / `.back-contact-item`\n- `.activity-block` / `.activity-content`\n- Any other custom flex containers\n\n**Quick checklist before delivering a template:** for every `display: flex` rule, verify that its children have `min-width: 0` AND `overflow-wrap: anywhere`. If a flex column will contain ANY text (static OR variable), it must have these properties.\n\n### 3.3 Table cell content\n\nInside `<td>`, use inline content only. Use `<br>` for line breaks, not `<p>` or `<div>`:\n\n```html\n<!-- Correct -->\n<td><span data-gjs-type=\"text\">Line 1<br>Line 2</span></td>\n\n<!-- Avoid — may break table structure -->\n<td><p>Line 1</p><p>Line 2</p></td>\n```\n\n### 3.4 Styling approach\n\n- Put ALL styles in `<style>` tags with CSS classes — avoid inline `style=\"...\"` attributes (EXCEPT for CSS Grid layouts inside `table_loop` templates)\n- Add classes to EVERY element (h1, h2, p, div, td, img, etc.) so users can easily modify styles in GrapesJS\n- Include `word-wrap: break-word; overflow-wrap: break-word;` on text containers\n\n### 3.5 Layout rules\n\n- Use **flexbox** for main layouts — NO CSS Grid for page-level layouts (except inside `table_loop` pricing grids)\n- NO `float` — use flexbox with `justify-content` / `align-items`\n- Widths in percentages for flexible layouts\n- `print-color-adjust: exact` on elements with background colors (ensures colors print)\n\n### 3.6 Font sizing for PDF\n\nPDFShift increases font sizes by ~30%. Compensate by reducing sizes:\n\n```css\n/* If you want 14pt rendered, use ~10pt in CSS */\n/* Rule of thumb: desired_size × 0.7 */\n.title { font-size: 18pt; } /* renders ~25pt in PDF */\n.body-text { font-size: 8pt; } /* renders ~11pt in PDF */\n```\n\n### 3.7 Background colors and print\n\n```css\n* {\n print-color-adjust: exact;\n -webkit-print-color-adjust: exact;\n}\n```\n\n---\n\n## STEP 4 — TYPEFLOW VARIABLES\n\n### Basic variables\n\n```html\n<span data-gjs-type=\"text\">{{Variable Name}}</span>\n```\n\nVariables are case-sensitive and map to Airtable field names.\n\n### Built-in variables\n\n| Variable | Description |\n|----------|-------------|\n| `{{Today}}` | Current date (YYYY-MM-DD) |\n| `{{page_number}}` | Current page number |\n| `{{total_pages}}` | Total pages |\n\n### Images\n\nThere are **three** ways to use images in a Typeflow template:\n\n#### 1. Fixed image (logo, background) — hardcoded URL\n\nFor images that are the same for every generated document (e.g., agency logo, hero image, decorative assets), use a standard `<img>` tag with a URL:\n\n```html\n<img class=\"logo\" src=\"https://example.com/logo.png\" alt=\"Logo\">\n```\n\n#### 2. Dynamic image from Airtable (outside `table_loop`) — `{{image_*}}`\n\nFor images that change per record (e.g., client logo, user avatar, product hero photo), use the **`image_` prefix** on the variable name. The worker detects this prefix and replaces the variable with a full `<img>` tag pointing to the Airtable attachment.\n\n**THREE HARD RULES (all required, no exceptions):**\n\n1. **Do NOT wrap `{{image_*}}` in an `<img src=\"...\">` yourself.** The backend injects the entire `<img>` tag with its own `src`, `width`, `height`, and inline styles. Putting the variable inside a `src=\"\"` produces malformed HTML.\n2. **Wrap the variable in a `<span>` inside the container.** Without the `<span>`, GrapesJS may strip the variable at save time, leaving an empty container. The worker then processes the image but has nowhere to put it in the HTML, and the logo silently disappears.\n3. **Override the worker's inline `width`/`height` with `!important`.** The worker generates `<img>` with inline styles like `width: 600px; height: 285px; display: block; margin: 5px 0;` based on the attachment's intrinsic dimensions. Inline styles beat regular class CSS, so you MUST use `!important` to constrain the image to your intended size.\n\n#### Canonical pattern for dynamic images\n\n```html\n<div class=\"client-logo\"><span>{{image_Client_Logo}}</span></div>\n```\n\n```css\n.client-logo {\n display: flex;\n align-items: center;\n height: 40px;\n}\n.client-logo img {\n max-height: 40px !important;\n max-width: 160px !important;\n width: auto !important;\n height: auto !important;\n object-fit: contain !important;\n display: block !important;\n margin: 0 !important;\n}\n```\n\nEvery single property that could conflict with the worker's inline styles has `!important`. Without it, your logo will appear at 600px wide in the middle of the page instead of 40px in your footer.\n\n#### Variable naming\n\nThe variable name after `image_` must match the Airtable field name, with **spaces replaced by underscores**: `Client Logo` → `{{image_Client_Logo}}`, `Product Photo` → `{{image_Product_Photo}}`, `Avatar` → `{{image_Avatar}}`.\n\n#### Dynamic image via linked record\n\nIf the image lives on a linked table (e.g. `Proposals → Client → Client Logo`), use the same `{{image_FieldName}}` syntax. The Typeflow UI mapping lets you point the variable to the linked record field — no special syntax in the template. The template only cares about the variable name; Typeflow handles the fieldPath resolution.\n\n#### 3. Dynamic image inside a `table_loop_0` — `{{table_image_*}}`\n\nInside a `table_loop_0`, images MUST use the **`table_image_` prefix** (not `image_`). The backend detects this prefix and handles image fetching/rendering per loop iteration.\n\n```html\n<tr><td>\n <div class=\"property-photo\"><span>{{table_image_Photo}}</span></div>\n</td></tr>\n```\n\n```css\n.property-photo {\n width: 100%;\n height: 200px;\n}\n.property-photo img {\n width: 100% !important;\n height: 100% !important;\n object-fit: cover !important;\n display: block !important;\n margin: 0 !important;\n}\n```\n\nSame three hard rules as `{{image_*}}`: no manual `<img>` wrapper, variable inside a `<span>`, CSS with `!important`.\n\n#### Why this complexity?\n\nThe worker's image replacement pipeline (`replaceImagePlaceholdersHTML` in `typeflow-worker/utils/html/replace-variable-html.js`) generates the `<img>` tag with hardcoded dimensions from the Airtable attachment. This is by design — it works well for gallery layouts where the image takes its natural size — but it fights against any template trying to constrain the image to a specific display size. The `!important` overrides are the only reliable workaround.\n\n#### Summary\n\n| Use case | Syntax | Wrap in `<img>`? | `<span>` wrapper? | `!important` CSS? |\n|----------|--------|------------------|-------------------|-------------------|\n| Fixed image (same for all records) | `<img src=\"https://...\">` | Yes, standard HTML | No | No |\n| Dynamic image (per record, outside loops) | `{{image_FieldName}}` | **No** — backend generates the `<img>` | **Yes** | **Yes** |\n| Dynamic image (inside `table_loop_0`) | `{{table_image_FieldName}}` | **No** — backend generates the `<img>` | **Yes** | **Yes** |\n\n### Multi-select fields (render modes)\n\nWhen you map a variable to an Airtable `multipleSelects` field, Typeflow can render it in **five different visual modes**, configured from the mapping UI (not from the template). The template just contains `{{Variable Name}}` — all styling comes from the mapping config.\n\n**Spec**: [`specification/2026-04-10-multi-select-render-modes.md`](../specification/2026-04-10-multi-select-render-modes.md)\n\n#### Available modes\n\n| Mode | Output | When to use |\n|------|--------|-------------|\n| `text` (default) | `Hardwood Floors, Pool, Smart Home` — comma-separated plain text | Simple inline lists, ultra-minimal |\n| `list` | `<ul><li>` bullet list | Classic vertical list (contracts, specs) |\n| `pills` | Inline rounded badges that wrap | Tags, categories, services, industries |\n| `grid` | CSS Grid of cards (2, 3, or 4 columns) with colored accent dot | Features grid, amenities, product capabilities |\n| `tags` (legacy) | 2-column HTML table with Airtable tag colors | Backward compatibility only — use `pills` for new templates |\n\n#### How to use in a template\n\nJust place the variable in a wrapper container:\n\n```html\n<div class=\"features-grid-wrap\">\n <span>{{Features}}</span>\n</div>\n```\n\n**No loop, no `data-loop`, no per-item HTML structure.** The worker generates the full HTML (list, pills, cards) based on the render mode selected in the UI.\n\n#### Configuration in the mapping UI\n\nWhen the user maps the variable, the UI shows:\n\n1. **Render as** dropdown (text / list / pills / grid / tags)\n2. **If `grid` selected**: columns (2/3/4) + 4 color pickers (background, border, text, accent dot)\n3. **If `pills` selected**: 3 color pickers (background, border, text)\n\nAll cards/pills share the **same colors** (chosen once, applied uniformly). Airtable's per-option tag colors are NOT used in the new modes.\n\n#### Behind the scenes\n\nThe mapping stores:\n\n```json\n{\n \"{{Features}}\": {\n \"baseFieldType\": \"multipleSelects\",\n \"renderAs\": \"grid\",\n \"renderConfig\": {\n \"columns\": 3,\n \"cardBackgroundColor\": \"#faf7f2\",\n \"cardBorderColor\": \"#e5e1d6\",\n \"cardTextColor\": \"#14213d\",\n \"cardAccentColor\": \"#c9a961\"\n }\n }\n}\n```\n\nThe worker (`render-multiselect.js`) reads `renderAs` and `renderConfig`, generates the HTML, and replaces `{{Features}}` with it at generation time.\n\n#### Why this is better than `loop_0` on a linked table\n\n- **Simpler schema**: no 3rd table for features/tags/categories\n- **Faster data entry**: pick from a multi-select dropdown in Airtable\n- **Flexible rendering**: change the look from the UI, not the template\n- **Unlimited items**: add options to the multi-select anytime\n- **No CSS complexity**: the worker injects everything inline\n\n### Checkboxes\n\n```html\n<span data-gjs-type=\"text\">{{checkbox:payment_method|Credit Card}}</span>\n```\n\nRenders ☑ if match, ☐ if not.\n\n### Barcodes (print labels)\n\n```html\n<div class=\"barcode-container\">\n {{barcode:SKU}}\n</div>\n```\n\nGenerated at PDF render time. Use in print labels and product tags.\n\n---\n\n## STEP 5 — LOOP STRUCTURES\n\n### Simple loop — `loop_0`, `loop_1`, `loop_2`...\n\nRepeats a `<tr>` for each linked record. The index increments for each separate linked-record table in the template: `loop_0` for the first, `loop_1` for the second, `loop_2` for the third, etc.\n\n```html\n<!-- First linked table (e.g. Line Items) — loop_0 -->\n<table class=\"line-items-table\">\n <thead>\n <tr>\n <th><span data-gjs-type=\"text\">Description</span></th>\n <th><span data-gjs-type=\"text\">Qty</span></th>\n <th><span data-gjs-type=\"text\">Price</span></th>\n </tr>\n </thead>\n <tbody class=\"table-body\">\n <tr class=\"loop_0\">\n <td><span data-gjs-type=\"text\">{{loop_0}}{{description}}</span></td>\n <td><span data-gjs-type=\"text\">{{quantity}}</span></td>\n <td><span data-gjs-type=\"text\">{{price}}</span></td>\n </tr>\n </tbody>\n</table>\n\n<!-- Second linked table (e.g. Flights) — loop_1 -->\n<table class=\"flights-table\">\n <thead>\n <tr>\n <th><span data-gjs-type=\"text\">Date</span></th>\n <th><span data-gjs-type=\"text\">From</span></th>\n <th><span data-gjs-type=\"text\">To</span></th>\n </tr>\n </thead>\n <tbody class=\"table-body\">\n <tr class=\"loop_1\">\n <td><span data-gjs-type=\"text\">{{loop_1}}{{Flight Date}}</span></td>\n <td><span data-gjs-type=\"text\">{{Departure}}</span></td>\n <td><span data-gjs-type=\"text\">{{Arrival}}</span></td>\n </tr>\n </tbody>\n</table>\n```\n\n**Rules:**\n- `class=\"loop_N\"` on the `<tr>` (where N = 0, 1, 2...)\n- `{{loop_N}}` placed before the first variable in the first `<td>`\n- `class=\"table-body\"` on `<tbody>`\n- Each loop index maps to a separate linked-record field in the Typeflow mapping UI\n- The index is determined by order of appearance in the template\n\n### Nested loop — `nested_0` / `nested_items_0`\n\nGroups items under a parent (e.g., categories with sub-items, or a linked record whose own linked records need to be looped). Use this when you need to access data **two levels deep** (main record → linked record → linked record's linked records).\n\n```html\n<tbody class=\"table-body\">\n <tr class=\"nested_0 parent\">\n <td><span data-gjs-type=\"text\">{{nested_0}}{{category_name}}</span></td>\n <td><span data-gjs-type=\"text\">{{category_total}}</span></td>\n </tr>\n <tr class=\"nested_items_0\">\n <td><span data-gjs-type=\"text\">{{nested_items_0}}{{item_name}}</span></td>\n <td><span data-gjs-type=\"text\">{{item_price}}</span></td>\n </tr>\n</tbody>\n```\n\n**Rules:**\n- TWO separate `<tr>` elements — parent row and child row\n- `class=\"nested_0 parent\"` on the parent row\n- `class=\"nested_items_0\"` on the child row\n- `{{nested_0}}` placed **before the first variable** in the parent row (required marker)\n- `{{nested_items_0}}` placed **before the first variable** in the child row (required marker — the worker needs BOTH markers to find the templates)\n- Both rows must have the **same number of `<td>`** for correct column alignment — no `colspan` tricks\n- Both rows must be inside the same `<tbody class=\"table-body\">`\n\n**Why the `{{nested_items_0}}` marker is mandatory:** the worker (`findNestedTemplates` in `typeflow-worker/utils/html/nested-line-items.js`) uses both `{{nested_0}}` and `{{nested_items_0}}` to locate the level-1 and level-2 template rows. Without the child marker, the worker cannot find the row to duplicate and the loop fails silently.\n\n### Hiding the parent row when you only need the child loop\n\nSometimes you need `nested_0` / `nested_items_0` for the data structure (e.g. `Main Record → Linked Record → N items`), but you don't want the parent row to appear visually — only the looped children should show.\n\nThe pattern: keep the parent row in the HTML (required by the worker) but style it to take zero visual space via CSS.\n\n**Example — \"headerless\" nested loop:**\n\n```html\n<tbody class=\"table-body\">\n <tr class=\"nested_0 parent nested-parent-hidden\">\n <td><span data-gjs-type=\"text\">{{nested_0}}{{parent_field}}</span></td>\n <td></td>\n <td></td>\n </tr>\n <tr class=\"nested_items_0\">\n <td><span data-gjs-type=\"text\">{{nested_items_0}}{{child_col_1}}</span></td>\n <td><span data-gjs-type=\"text\">{{child_col_2}}</span></td>\n <td><span data-gjs-type=\"text\">{{child_col_3}}</span></td>\n </tr>\n</tbody>\n```\n\n```css\n/* Hide the parent row visually while keeping it in the DOM for the worker */\n.nested-parent-hidden,\n.nested-parent-hidden td {\n border: none !important;\n padding: 0 !important;\n height: 0 !important;\n line-height: 0 !important;\n font-size: 0 !important;\n color: transparent !important;\n}\n```\n\n**Important:**\n- Do NOT use `display: none` on the parent row — it can break the table structure and the worker's row detection\n- Do NOT use `visibility: collapse` unless you tested it in PDFShift specifically (inconsistent support)\n- Keep the number of `<td>` in the parent row equal to the child row (fill empty ones with `<td></td>`) so the table layout is consistent\n- Include a parent field variable (even if never visible) — `{{nested_0}}{{some_field}}` — to avoid the worker considering the parent empty\n\nThis pattern is useful for PE/VC investor reports, quarterly financial reports, or any template where the \"parent\" is a single record (e.g. a Fund) and you only need to loop its children (e.g. Portfolio Companies) without showing the parent as a header.\n\n### Table loop — `table_loop_0`\n\nDuplicates an entire table per record (for catalogs, product sheets, listing pages):\n\n```html\n<table class=\"product-card\">\n <tbody>\n <tr><td><span data-gjs-type=\"text\">{{table_loop_0}}</span></td></tr>\n <tr><td>\n <div class=\"product-header\">\n <span data-gjs-type=\"text\">{{product_name}}</span>\n </div>\n </td></tr>\n <tr><td>\n <div class=\"product-image-container\">\n {{table_image_photo}}\n </div>\n </td></tr>\n <tr><td>\n <span data-gjs-type=\"text\">{{product_description}}</span>\n </td></tr>\n <tr><td>\n <div class=\"product-price\">\n <span data-gjs-type=\"text\">{{price}}</span>\n </div>\n </td></tr>\n </tbody>\n</table>\n```\n\n**Rules:**\n- `{{table_loop_0}}` in the first `<tr>`\n- ALL content in separate `<tr>` rows of the SAME table\n- **CRITICAL: NO nested `<table>` elements inside a `table_loop_0`.** The variable parser uses a non-greedy regex (`/<table[^>]*>([\\s\\S]*?)<\\/table>/gi`) which matches the FIRST `</table>` it finds. A nested table will close the parser's table context prematurely, and any variables after the nested table's `</table>` will be parsed as regular (top-level) variables instead of table_loop variables. This causes `{{table_image_*}}` and other variables to appear in the main variable panel instead of the table_loop mapping panel, making them unmappable. **Use flexbox `<div>` layouts for any tabular content inside a `table_loop_0`** (checklists, grids, data tables — all must be `<div>` with CSS flex, not `<table>`).\n- CSS Grid layouts with inline styles are OK here (exception to the no-inline-styles rule)\n\n**Why no nested tables:** Backend processes nested tables separately at top level — variables in nested tables are not linked to `table_loop_0` context.\n\n---\n\n## STEP 6 — DESIGN PATTERNS\n\n### 6.1 Typography with Google Fonts\n\nAll Google Fonts are available. Import them at the top of `<style>`:\n\n```css\n@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Playfair+Display:wght@400;700&display=swap');\n```\n\n**Recommended pairings:**\n\n| Style | Heading | Body |\n|-------|---------|------|\n| Modern corporate | Inter | Inter |\n| Elegant / luxury | Playfair Display | Inter |\n| Creative / bold | Montserrat | Open Sans |\n| Editorial | Lora | Source Sans 3 |\n| Tech / startup | Space Grotesk | DM Sans |\n| Friendly | Nunito | Nunito Sans |\n\n### 6.2 Color usage\n\nDefine colors as CSS custom properties for easy theming:\n\n```css\n:root {\n --primary: #2563eb;\n --primary-dark: #1e40af;\n --secondary: #f59e0b;\n --text-dark: #1a1a1a;\n --text-light: #6b7280;\n --bg-light: #f8fafc;\n --bg-accent: #eff6ff;\n --border: #e5e7eb;\n}\n```\n\nUse `print-color-adjust: exact` on all colored elements.\n\n### 6.3 Layout — full-bleed hero section\n\n```html\n<div class=\"hero-section\">\n <img class=\"hero-image\" src=\"{{hero_image}}\" alt=\"Hero\">\n <div class=\"hero-overlay\">\n <h1 class=\"hero-title\"><span data-gjs-type=\"text\">{{title}}</span></h1>\n <p class=\"hero-subtitle\"><span data-gjs-type=\"text\">{{subtitle}}</span></p>\n </div>\n</div>\n```\n\n```css\n.hero-section {\n position: relative;\n width: 100%;\n height: 140mm;\n overflow: hidden;\n print-color-adjust: exact;\n -webkit-print-color-adjust: exact;\n}\n.hero-image {\n width: 100%;\n height: 100%;\n object-fit: cover;\n}\n.hero-overlay {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n padding: 15mm 10mm;\n background: linear-gradient(transparent, rgba(0,0,0,0.7));\n print-color-adjust: exact;\n -webkit-print-color-adjust: exact;\n}\n.hero-title {\n color: #ffffff;\n font-size: 22pt;\n font-weight: 700;\n margin: 0;\n}\n.hero-subtitle {\n color: #ffffffcc;\n font-size: 10pt;\n margin: 5mm 0 0 0;\n}\n```\n\n### 6.4 Layout — two-column with sidebar\n\n```html\n<div class=\"two-col-layout\">\n <div class=\"sidebar\">\n <!-- Sidebar content -->\n </div>\n <div class=\"main-content\">\n <!-- Main content -->\n </div>\n</div>\n```\n\n```css\n.two-col-layout {\n display: flex;\n width: 100%;\n min-height: 297mm;\n}\n.sidebar {\n width: 65mm;\n background: var(--primary-dark);\n color: #ffffff;\n padding: 10mm 8mm;\n print-color-adjust: exact;\n -webkit-print-color-adjust: exact;\n}\n.main-content {\n flex: 1;\n padding: 10mm 12mm;\n}\n```\n\n### 6.5 Layout — card grid (for catalogs / listings)\n\n```css\n.card-grid {\n display: flex;\n flex-wrap: wrap;\n gap: 5mm;\n}\n.card {\n width: calc(50% - 2.5mm);\n border: 1px solid var(--border);\n border-radius: 3mm;\n overflow: hidden;\n}\n.card-image {\n width: 100%;\n height: 50mm;\n object-fit: cover;\n}\n.card-body {\n padding: 4mm;\n}\n```\n\n### 6.6 Accent elements\n\n**Colored divider:**\n\n```html\n<div class=\"divider\"></div>\n```\n\n```css\n.divider {\n width: 40mm;\n height: 1mm;\n background: var(--primary);\n margin: 5mm 0;\n print-color-adjust: exact;\n -webkit-print-color-adjust: exact;\n}\n```\n\n**Badge / tag:**\n\n```css\n.badge {\n display: inline-block;\n background: var(--primary);\n color: #ffffff;\n padding: 1mm 3mm;\n border-radius: 1mm;\n font-size: 6pt;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.5pt;\n print-color-adjust: exact;\n -webkit-print-color-adjust: exact;\n}\n```\n\n**Icon stat block:**\n\n```html\n<div class=\"stat-block\">\n <div class=\"stat-value\"><span data-gjs-type=\"text\">{{surface}}</span></div>\n <div class=\"stat-label\"><span data-gjs-type=\"text\">Surface</span></div>\n</div>\n```\n\n```css\n.stat-block {\n text-align: center;\n padding: 3mm;\n}\n.stat-value {\n font-size: 16pt;\n font-weight: 700;\n color: var(--primary);\n}\n.stat-label {\n font-size: 6pt;\n color: var(--text-light);\n text-transform: uppercase;\n letter-spacing: 0.5pt;\n}\n```\n\n### 6.7 Styled table (for invoices, quotes)\n\n```css\n.styled-table {\n width: 100%;\n table-layout: fixed;\n border-collapse: collapse;\n}\n.styled-table thead th {\n background: var(--primary);\n color: #ffffff;\n padding: 3mm 4mm;\n font-size: 7pt;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.3pt;\n text-align: left;\n print-color-adjust: exact;\n -webkit-print-color-adjust: exact;\n}\n.styled-table tbody td {\n padding: 3mm 4mm;\n font-size: 7pt;\n border-bottom: 0.5px solid var(--border);\n word-wrap: break-word;\n overflow-wrap: break-word;\n}\n.styled-table tbody tr:nth-child(even) {\n background: var(--bg-light);\n print-color-adjust: exact;\n -webkit-print-color-adjust: exact;\n}\n```\n\n### 6.8 Totals block (right-aligned)\n\n```html\n<div class=\"totals-container\">\n <div class=\"totals-block\">\n <div class=\"total-row\">\n <span data-gjs-type=\"text\">Subtotal</span>\n <span data-gjs-type=\"text\">{{subtotal}}</span>\n </div>\n <div class=\"total-row\">\n <span data-gjs-type=\"text\">Tax (20%)</span>\n <span data-gjs-type=\"text\">{{tax}}</span>\n </div>\n <div class=\"total-row total-final\">\n <span data-gjs-type=\"text\">Total</span>\n <span data-gjs-type=\"text\">{{total}}</span>\n </div>\n </div>\n</div>\n```\n\n```css\n.totals-container {\n display: flex;\n justify-content: flex-end;\n margin-top: 5mm;\n}\n.totals-block {\n width: 70mm;\n}\n.total-row {\n display: flex;\n justify-content: space-between;\n padding: 2mm 0;\n font-size: 7pt;\n border-bottom: 0.5px solid var(--border);\n}\n.total-final {\n font-weight: 700;\n font-size: 9pt;\n color: var(--primary);\n border-bottom: none;\n border-top: 1px solid var(--primary);\n padding-top: 3mm;\n margin-top: 1mm;\n}\n```\n\n---\n\n## STEP 7 — PRINT LABEL TEMPLATES\n\nFor small format labels (product tags, shipping labels, barcode labels):\n\n```html\n<div class=\"label\">\n <div class=\"label-header\">\n <span data-gjs-type=\"text\">{{product_name}}</span>\n </div>\n <div class=\"label-barcode\">\n {{barcode:sku}}\n </div>\n <div class=\"label-info\">\n <span data-gjs-type=\"text\">{{sku}}</span>\n <span data-gjs-type=\"text\">{{price}}</span>\n </div>\n</div>\n```\n\n```css\n@page {\n size: 62mm 29mm;\n margin: 0;\n}\nbody {\n width: 62mm;\n min-height: 29mm;\n margin: 0;\n padding: 1.5mm;\n font-family: 'Inter', sans-serif;\n}\n.label {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n}\n.label-header {\n font-size: 5pt;\n font-weight: 600;\n}\n.label-barcode {\n text-align: center;\n margin: 1mm 0;\n}\n.label-info {\n display: flex;\n justify-content: space-between;\n font-size: 4pt;\n color: #333;\n}\n```\n\n---\n\n## STEP 8 — COMPLETE TEMPLATE STRUCTURE\n\nEvery template you generate must follow this structure:\n\n```html\n<style>\n /* 1. Font imports */\n @import url('https://fonts.googleapis.com/css2?family=...&display=swap');\n\n /* 2. Page setup */\n @page {\n size: A4 portrait;\n margin: 0;\n }\n\n /* 3. CSS custom properties */\n :root {\n --primary: #2563eb;\n /* ... */\n }\n\n /* 4. Base reset */\n * {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n print-color-adjust: exact;\n -webkit-print-color-adjust: exact;\n }\n body {\n width: 210mm;\n min-height: 297mm;\n font-family: 'Inter', sans-serif;\n color: var(--text-dark);\n }\n\n /* 5. Component styles — class on every element */\n .header { /* ... */ }\n .main-content { /* ... */ }\n .footer { /* ... */ }\n /* etc. */\n</style>\n\n<!-- HTML body -->\n<div class=\"page\">\n <div class=\"header\">\n <!-- Logo, title, etc. -->\n </div>\n <div class=\"main-content\">\n <!-- Content sections -->\n </div>\n <div class=\"footer\">\n <!-- Footer info, page numbers -->\n </div>\n</div>\n```\n\n---\n\n## CHECKLIST BEFORE DELIVERING\n\n- [ ] ALL text wrapped in `<span data-gjs-type=\"text\">`\n- [ ] ALL elements have CSS classes\n- [ ] No `width: 210mm` on body or top-level containers (use `width: 100%`)\n- [ ] No `@page` rules in CSS (GrapesJS injects its own)\n- [ ] No `html, body { height: 100% }` (causes overflow with multi-section templates)\n- [ ] `min-height: 297mm` (or matching format) on top-level page sections (cover, content, back cover)\n- [ ] **EVERY `display: flex` container with text inside has `min-width: 0; overflow-wrap: anywhere; word-break: break-word; flex: 1 1 0` on its children** (CRITICAL — rich text variables use `&nbsp;` which break flex layout otherwise)\n- [ ] `print-color-adjust: exact` on colored elements\n- [ ] `table-layout: fixed` on all tables\n- [ ] `word-wrap: break-word` on table cells\n- [ ] `class=\"table-body\"` on all `<tbody>`\n- [ ] Loop markers correctly placed (`loop_0`/`loop_1`/`loop_2`..., `nested_0`, `table_loop_0`)\n- [ ] No CSS Grid for main layout (flexbox only)\n- [ ] No `float` usage\n- [ ] No inline styles (except CSS Grid inside `table_loop`)\n- [ ] All sizes in `px` (not `mm`) except `min-height` on top-level page sections\n- [ ] Google Fonts imported in `<style>`\n- [ ] Dynamic images use `{{image_*}}` (outside loops) or `{{table_image_*}}` (inside `table_loop_0`) — NEVER wrapped in `<img src=\"...\">`, backend generates the `<img>` tag\n- [ ] Every dynamic image variable is wrapped in a `<span>`: `<div class=\"x\"><span>{{image_Logo}}</span></div>` (GrapesJS strips bare variables in non-text contexts)\n- [ ] Dynamic image containers style the generated `<img>` via a descendant selector with `!important` on every sizing property (`.container img { max-height: 40px !important; max-width: 160px !important; width: auto !important; height: auto !important; object-fit: contain !important; margin: 0 !important; }`) to override the worker's inline `width`/`height`/`margin`\n- [ ] Images use `object-fit: cover` where appropriate\n- [ ] Multi-page uses `page-break-after: always` on each top-level section (except the last)\n";