fms-odata-mcp 0.9.5 → 0.9.6

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/README.md CHANGED
@@ -8,13 +8,15 @@ for AI assistants like Claude Desktop, Windsurf, Cursor, and Cline.
8
8
 
9
9
  ## Features
10
10
 
11
- - **39 MCP Tools** for FileMaker database operations (33 standard + 6 optional schema editing)
11
+ - **42 MCP Tools** for FileMaker database operations (36 standard + 6 optional schema editing)
12
12
  - **Multi-File Support** - Connect to multiple databases simultaneously (`fm_odata_connect_multi`)
13
13
  - **Session Management** - List and target active sessions per call
14
14
  (`fm_odata_list_active_sessions`, per-call `connection` param)
15
15
  - **Schema Discovery** - Merged schema across all active sessions (`fm_odata_describe_sessions`)
16
16
  - **Database Discovery** - Explore tables, fields, and metadata
17
17
  - **CRUD Operations** - Create, read, update, and delete records
18
+ - **Container Field Support** - Upload/download GIF, PNG, JPEG, TIFF, and PDF
19
+ container content; read single scalar field values via `/{field}/$value`
18
20
  - **Secure Connections** - SSL support for self-signed certificates
19
21
  - **Connection Management** - Save and reuse database connections
20
22
  - **OData 4.01 Standard** - Full query capabilities ($filter, $select, $orderby, $apply, etc.)
@@ -364,6 +366,7 @@ Create a new contact with name "John Doe" and email "john@example.com"
364
366
  | **Sessions** | `fm_odata_list_active_sessions`, `fm_odata_describe_sessions` |
365
367
  | **Diagnostics** | `fm_odata_get_server_version` |
366
368
  | **Config** | `fm_odata_config_add_connection`, `fm_odata_config_remove_connection`, `fm_odata_config_list_connections`, `fm_odata_config_get_connection`, `fm_odata_config_set_default_connection` |
369
+ | **Containers** | `fm_odata_upload_container`, `fm_odata_download_container`, `fm_odata_get_field_value` |
367
370
  | **Schema (DDL)** | `fm_odata_create_table`, `fm_odata_add_fields`, `fm_odata_delete_table`, `fm_odata_delete_field`, `fm_odata_create_index`, `fm_odata_delete_index` |
368
371
 
369
372
  > The **FM 2024/2025+** tools are connection-free expression builders. `fm_odata_cast` and
@@ -385,7 +388,7 @@ Create a new contact with name "John Doe" and email "john@example.com"
385
388
 
386
389
  ## Requirements
387
390
 
388
- - **Node.js** 18.0.0 or higher
391
+ - **Node.js** 24.0.0 or higher
389
392
  - **FileMaker Server** with OData API enabled
390
393
  - **FileMaker Account** with appropriate access privileges
391
394
 
@@ -397,10 +400,15 @@ Create a new contact with name "John Doe" and email "john@example.com"
397
400
  |---------------|------------------------------------------------|----------|---------|
398
401
  | `FM_SERVER` | FileMaker Server URL | Yes | - |
399
402
  | `FM_DATABASE` | Database name | Yes | - |
400
- | `FM_USER` | Username | Yes | - |
401
- | `FM_PASSWORD` | Password | Yes | - |
402
- | `FM_VERIFY_SSL`| Verify SSL certificates | No | `true` |
403
+ | `FM_USER` | Username for Basic auth | Basic auth | - |
404
+ | `FM_PASSWORD` | Password for Basic auth | Basic auth | - |
405
+ | `FM_AUTH_TYPE` | Authentication method: `basic` or `bearer` | No | `basic` |
406
+ | `FM_BEARER_TOKEN` | Bearer token for OAuth/Claris ID auth | Bearer auth | - |
407
+ | `FM_VERIFY_SSL` | Verify SSL certificates | No | `true` |
403
408
  | `FM_TIMEOUT` | Request timeout (ms) | No | `30000` |
409
+ | `FM_TLS_MAX_VERSION` | Maximum TLS version; set `TLSv1.3` to opt in | No | `TLSv1.2` |
410
+ | `FM_BATCH_MAX_ITEMS` | Max records per bulk create/update/delete call | No | `100` |
411
+ | `FM_MAX_RECORDS` | Max records returned by `query_all_records` | No | `10000` |
404
412
  | `FM_ALLOW_SCHEMA_EDITS` | Enable schema (DDL) tools | No | `false` |
405
413
 
406
414
  ### HTTP/HTTPS Transport
@@ -412,7 +420,8 @@ Create a new contact with name "John Doe" and email "john@example.com"
412
420
  | `MCP_HOST` | Host to bind to | No | `localhost` |
413
421
  | `MCP_CERT_PATH` | Path to SSL certificate (HTTPS only) | No | - |
414
422
  | `MCP_KEY_PATH` | Path to SSL private key (HTTPS only) | No | - |
415
- | `MCP_AUTH_TOKEN`| Bearer token for `/mcp` auth (HTTP/HTTPS) | No | - (open endpoint, warning logged) |
423
+ | `MCP_AUTH_TOKEN` | Bearer token for `/mcp` auth (HTTP/HTTPS) | No | - (open endpoint, warning logged) |
424
+ | `MCP_MAX_BODY_SIZE` | Maximum JSON-RPC request body size | No | `50mb` |
416
425
 
417
426
  ## OData Query Syntax
418
427
 
@@ -495,6 +504,46 @@ Merged schema with field comments and AI annotations:
495
504
  On v25 and older servers these options are ignored safely — call
496
505
  `fm_odata_get_server_version` first to check `metadata_comments` support.
497
506
 
507
+ ## Container Fields
508
+
509
+ FileMaker excludes container-field content from normal record responses, so
510
+ container data must be read through the field's `/$value` endpoint. Three tools
511
+ cover the container lifecycle:
512
+
513
+ | Tool | Purpose |
514
+ |------|---------|
515
+ | `fm_odata_upload_container` | Upload GIF, PNG, JPEG, TIFF, or PDF content into a container field |
516
+ | `fm_odata_download_container` | Download container bytes as base64, with content type, size, and filename when available |
517
+ | `fm_odata_get_field_value` | Read one scalar field unwrapped via `/{field}/$value` without fetching the full record |
518
+
519
+ `fm_odata_upload_container` accepts raw base64 or a `data:...;base64,...` URI.
520
+ Its default `mode: "base64"` sends FileMaker's inline JSON annotations. If
521
+ FileMaker's magic-byte media-type inference does not match the declared type,
522
+ retry with `mode: "binary"` so the explicit `Content-Type` and
523
+ `Content-Disposition` headers are sent with raw bytes.
524
+
525
+ ```text
526
+ Upload a PDF:
527
+ fm_odata_upload_container with
528
+ table="Invoices", recordId="42", field="PDF_Container",
529
+ filename="invoice-42.pdf", contentType="application/pdf",
530
+ base64Data="<base64>", mode="binary"
531
+
532
+ Download it:
533
+ fm_odata_download_container with
534
+ table="Invoices", recordId="42", field="PDF_Container"
535
+ → { base64Data, contentType, sizeBytes, filename? }
536
+
537
+ Read one scalar field:
538
+ fm_odata_get_field_value with
539
+ table="Invoices", recordId="42", field="InvoiceNumber"
540
+ ```
541
+
542
+ **Limitations:** FileMaker supports only GIF, PNG, JPEG, TIFF, and PDF for
543
+ container uploads. Uploads target the first repetition — repetition indexes are
544
+ supported only for downloads/scalar reads. Large base64 uploads over HTTP or
545
+ HTTPS transport may require increasing `MCP_MAX_BODY_SIZE` (default `50mb`).
546
+
498
547
  ## Schema Editing (DDL)
499
548
 
500
549
  FileMaker Server exposes a proprietary OData schema extension through the
@@ -97,6 +97,72 @@ export interface FMTableDefinition {
97
97
  tableName: string;
98
98
  fields: FMFieldDefinition[];
99
99
  }
100
+ /**
101
+ * Media types FileMaker Server's OData endpoint documents for container
102
+ * uploads. Uploads outside this list may be rejected server-side.
103
+ */
104
+ export declare const SUPPORTED_CONTAINER_TYPES: readonly ["image/gif", "image/png", "image/jpeg", "image/tiff", "application/pdf"];
105
+ /**
106
+ * Result of a container upload (base64 or binary mode).
107
+ */
108
+ export interface ContainerUploadResult {
109
+ sizeBytes: number;
110
+ /** MIME type inferred from magic bytes, or null when unrecognized. */
111
+ detectedMime: string | null;
112
+ }
113
+ /**
114
+ * Result of a container download — raw bytes wrapped in base64 so the
115
+ * payload is safe for JSON-RPC transport.
116
+ */
117
+ export interface ContainerDownloadResult {
118
+ base64Data: string;
119
+ contentType: string;
120
+ sizeBytes: number;
121
+ filename?: string;
122
+ }
123
+ /**
124
+ * Result of a raw `/{field}/$value` read.
125
+ */
126
+ export interface FieldValueResult {
127
+ /** Decoded text value, or null for empty/binary fields. */
128
+ value: string | null;
129
+ contentType: string;
130
+ /** True when the response media type indicates container/binary data. */
131
+ isBinaryContainer: boolean;
132
+ }
133
+ /**
134
+ * Normalize user-supplied base64 input and decode it.
135
+ *
136
+ * Accepts raw base64 or a `data:<mime>;base64,<data>` URI, tolerates
137
+ * embedded whitespace, and enforces canonical padding so corrupt input is
138
+ * rejected before it reaches the server.
139
+ */
140
+ export declare function normalizeAndValidateBase64(input: string): {
141
+ cleanBase64: string;
142
+ buffer: Buffer;
143
+ };
144
+ /**
145
+ * Detect the container media type from magic bytes, mirroring the
146
+ * signatures FileMaker Server itself inspects for base64 uploads.
147
+ */
148
+ export declare function detectContainerMimeFromBytes(buf: Buffer): string | null;
149
+ /**
150
+ * Validate a string destined for an HTTP header value (filename, MIME
151
+ * type). Rejects empty values and CR/LF/NUL characters to prevent header
152
+ * injection.
153
+ */
154
+ export declare function sanitizeHeaderValue(value: string, label: string): string;
155
+ /**
156
+ * Build an RFC 6266-style `Content-Disposition: inline; filename=...`
157
+ * header value, quoting/escaping when the filename is not a bare token.
158
+ */
159
+ export declare function formatContentDisposition(filename: string): string;
160
+ /**
161
+ * Extract the filename from a `Content-Disposition` response header.
162
+ * Supports RFC 5987 `filename*=UTF-8''...`, quoted-string, and bare-token
163
+ * forms. Returns undefined when no filename is present.
164
+ */
165
+ export declare function parseContentDispositionFilename(header?: string): string | undefined;
100
166
  /**
101
167
  * OData Client for FileMaker Server
102
168
  * Implements Basic Authentication and OData 4.01 operations
@@ -137,6 +203,16 @@ export declare class ODataClient {
137
203
  * apostrophes for string-key paths.
138
204
  */
139
205
  private entityKey;
206
+ /**
207
+ * Encode a field name for use as an OData URL path segment in
208
+ * `/{table}({id})/{field}/$value` style URLs.
209
+ *
210
+ * Spaces and Unicode are percent-encoded, while `:` (FMFID:12345 field
211
+ * IDs) and `[`/`]` (repetition index, when the caller already embedded
212
+ * it, e.g. `Field[2]`) stay literal. An optional 1-based `repetition`
213
+ * index is appended as `[n]` unless the field already ends with `]`.
214
+ */
215
+ private encodeFieldSegment;
140
216
  /**
141
217
  * Encode a value for an OData query-string parameter.
142
218
  *
@@ -229,6 +305,49 @@ export declare class ODataClient {
229
305
  * Delete a record
230
306
  */
231
307
  deleteRecord(table: string, recordId: string): Promise<void>;
308
+ /**
309
+ * Upload container content inline as base64 inside a JSON PATCH body.
310
+ *
311
+ * FileMaker-specific OData extension: the base64 value is accompanied by
312
+ * `<field>@com.filemaker.odata.Filename` and
313
+ * `<field>@com.filemaker.odata.ContentType` annotation properties.
314
+ * FileMaker infers the media type from the first bytes of the decoded
315
+ * data — callers can compare `detectedMime` (magic-byte sniff on the
316
+ * client side) with the declared `contentType` and fall back to
317
+ * {@link uploadContainerBinary} when the types disagree.
318
+ */
319
+ uploadContainerBase64(table: string, recordId: string, field: string, base64Data: string, filename: string, contentType: string): Promise<ContainerUploadResult>;
320
+ /**
321
+ * Upload container content as a raw binary body.
322
+ *
323
+ * `PATCH /{table}({id})/{field}` with `Content-Type`, `Content-Disposition`,
324
+ * and `OData-Version` headers. Use this when FileMaker's magic-byte
325
+ * inference misidentifies a base64 upload — the explicit `Content-Type`
326
+ * header wins. Repetition index is NOT supported on upload by FileMaker
327
+ * OData.
328
+ */
329
+ uploadContainerBinary(table: string, recordId: string, field: string, binaryData: Buffer | Uint8Array, filename: string, contentType: string): Promise<{
330
+ sizeBytes: number;
331
+ }>;
332
+ /**
333
+ * Download raw bytes from a container field via `/{field}/$value`.
334
+ *
335
+ * Container fields are excluded from normal record responses, so this is
336
+ * the only way to read them. Bytes are wrapped in base64 for JSON-RPC
337
+ * safety. `contentType` comes from the response header, falling back to
338
+ * magic-byte detection when the server reports
339
+ * `application/octet-stream` (or omits the header).
340
+ */
341
+ downloadContainer(table: string, recordId: string, field: string, repetition?: number): Promise<ContainerDownloadResult>;
342
+ /**
343
+ * Read the raw value of a single field via `/{field}/$value`.
344
+ *
345
+ * Scalar fields come back as `text/plain` (HTTP 204 when empty/null).
346
+ * Container fields return binary media types — those are reported via
347
+ * `isBinaryContainer` so callers can redirect to
348
+ * {@link downloadContainer} instead of decoding them as text.
349
+ */
350
+ getFieldValue(table: string, recordId: string, field: string, repetition?: number): Promise<FieldValueResult>;
232
351
  /**
233
352
  * Result of a single operation within a batch.
234
353
  */
@@ -1 +1 @@
1
- {"version":3,"file":"odata-client.d.ts","sourceRoot":"","sources":["../src/odata-client.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,eAAe,EAA0C,MAAM,iBAAiB,CAAC;AAE1F,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,Q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IACG,SAAS,CAAC,UAAU,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,YAAY,CAAC;IAW7E;;;;;;OAMG;IACG,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,EAAE,WAAW,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,YAAY,CAAC;IAYxF;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAW3B;;;;;OAKG;IACH,OAAO,CAAC,gBAAgB;IA4CxB;;;OAGG;IACG,cAAc,IAAI,OAAO,CAAC,OAAO,CAAC;IAUxC;;;;OAIG;IACG,sBAAsB,IAAI,OAAO,CAAC;QAAE,EAAE,EAAE,IAAI,CAAA;KAAE,GAAG;QAAE,EAAE,EAAE,KAAK,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;CAUrF"}
@@ -3,6 +3,136 @@ import https from "https";
3
3
  import crypto from "crypto";
4
4
  import { logger } from "./logger.js";
5
5
  import { parseServerVersion, isFeatureSupported } from "./fm-version.js";
6
+ /**
7
+ * Media types FileMaker Server's OData endpoint documents for container
8
+ * uploads. Uploads outside this list may be rejected server-side.
9
+ */
10
+ export const SUPPORTED_CONTAINER_TYPES = [
11
+ "image/gif",
12
+ "image/png",
13
+ "image/jpeg",
14
+ "image/tiff",
15
+ "application/pdf",
16
+ ];
17
+ /**
18
+ * Normalize user-supplied base64 input and decode it.
19
+ *
20
+ * Accepts raw base64 or a `data:<mime>;base64,<data>` URI, tolerates
21
+ * embedded whitespace, and enforces canonical padding so corrupt input is
22
+ * rejected before it reaches the server.
23
+ */
24
+ export function normalizeAndValidateBase64(input) {
25
+ let s = String(input ?? "").trim();
26
+ if (s.startsWith("data:")) {
27
+ const marker = s.indexOf(";base64,");
28
+ if (marker !== -1) {
29
+ s = s.substring(marker + ";base64,".length);
30
+ }
31
+ }
32
+ const cleanBase64 = s.replace(/[\r\n\s]+/g, "");
33
+ if (cleanBase64.length === 0 ||
34
+ !/^[A-Za-z0-9+/]+={0,2}$/.test(cleanBase64) ||
35
+ cleanBase64.length % 4 !== 0) {
36
+ throw new Error("Invalid base64 data: input is empty or contains non-base64 characters / invalid padding");
37
+ }
38
+ const buffer = Buffer.from(cleanBase64, "base64");
39
+ if (buffer.length === 0) {
40
+ throw new Error("Invalid base64 data: decoded buffer is empty");
41
+ }
42
+ return { cleanBase64, buffer };
43
+ }
44
+ /**
45
+ * Detect the container media type from magic bytes, mirroring the
46
+ * signatures FileMaker Server itself inspects for base64 uploads.
47
+ */
48
+ export function detectContainerMimeFromBytes(buf) {
49
+ if (buf.length >= 4 && buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38) {
50
+ return "image/gif"; // GIF8
51
+ }
52
+ if (buf.length >= 8 &&
53
+ buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 &&
54
+ buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a) {
55
+ return "image/png";
56
+ }
57
+ if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
58
+ return "image/jpeg";
59
+ }
60
+ if (buf.length >= 4 &&
61
+ ((buf[0] === 0x49 && buf[1] === 0x49 && buf[2] === 0x2a && buf[3] === 0x00) ||
62
+ (buf[0] === 0x4d && buf[1] === 0x4d && buf[2] === 0x00 && buf[3] === 0x2a))) {
63
+ return "image/tiff"; // II*\x00 (LE) or MM\x00* (BE)
64
+ }
65
+ if (buf.length >= 4 && buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46) {
66
+ return "application/pdf"; // %PDF
67
+ }
68
+ return null;
69
+ }
70
+ /**
71
+ * Validate a string destined for an HTTP header value (filename, MIME
72
+ * type). Rejects empty values and CR/LF/NUL characters to prevent header
73
+ * injection.
74
+ */
75
+ export function sanitizeHeaderValue(value, label) {
76
+ const v = String(value ?? "");
77
+ if (v.trim().length === 0 || /[\r\n\0]/.test(v)) {
78
+ throw new Error(`Invalid ${label}: must be non-empty and must not contain CR/LF/null characters`);
79
+ }
80
+ return v.trim();
81
+ }
82
+ /**
83
+ * Build an RFC 6266-style `Content-Disposition: inline; filename=...`
84
+ * header value, quoting/escaping when the filename is not a bare token.
85
+ */
86
+ export function formatContentDisposition(filename) {
87
+ const clean = sanitizeHeaderValue(filename, "filename");
88
+ if (/^[A-Za-z0-9._-]+$/.test(clean)) {
89
+ return `inline; filename=${clean}`;
90
+ }
91
+ if (/^[ -~]+$/.test(clean)) {
92
+ const escaped = clean.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
93
+ return `inline; filename="${escaped}"`;
94
+ }
95
+ const asciiFallback = clean
96
+ .replace(/[^\x20-\x7e]/g, "_")
97
+ .replace(/\\/g, "\\\\")
98
+ .replace(/"/g, '\\"');
99
+ const rfc5987 = encodeURIComponent(clean).replace(/['()*]/g, (ch) => `%${ch.charCodeAt(0).toString(16).toUpperCase()}`);
100
+ return `inline; filename="${asciiFallback}"; filename*=UTF-8''${rfc5987}`;
101
+ }
102
+ function isTextualMediaType(contentType) {
103
+ return (contentType.startsWith("text/") ||
104
+ contentType === "application/json" ||
105
+ contentType === "application/xml" ||
106
+ contentType.endsWith("+json") ||
107
+ contentType.endsWith("+xml"));
108
+ }
109
+ /**
110
+ * Extract the filename from a `Content-Disposition` response header.
111
+ * Supports RFC 5987 `filename*=UTF-8''...`, quoted-string, and bare-token
112
+ * forms. Returns undefined when no filename is present.
113
+ */
114
+ export function parseContentDispositionFilename(header) {
115
+ if (!header)
116
+ return undefined;
117
+ const ext = /filename\*\s*=\s*UTF-8''([^;\r\n]+)/i.exec(header);
118
+ if (ext) {
119
+ try {
120
+ return decodeURIComponent(ext[1].trim());
121
+ }
122
+ catch {
123
+ return ext[1].trim();
124
+ }
125
+ }
126
+ const quoted = /filename\s*=\s*"((?:[^"\\]|\\.)*)"/i.exec(header);
127
+ if (quoted) {
128
+ return quoted[1].replace(/\\(.)/g, "$1");
129
+ }
130
+ const token = /filename\s*=\s*([^;\s\r\n]+)/i.exec(header);
131
+ if (token) {
132
+ return token[1].trim();
133
+ }
134
+ return undefined;
135
+ }
6
136
  /**
7
137
  * OData Client for FileMaker Server
8
138
  * Implements Basic Authentication and OData 4.01 operations
@@ -60,7 +190,15 @@ export class ODataClient {
60
190
  });
61
191
  // Add response interceptor for error handling
62
192
  this.axiosInstance.interceptors.response.use((response) => response, (error) => {
63
- logger.error("Response error:", error.response?.data || error.message);
193
+ const rawData = error.response?.data;
194
+ const logPayload = Buffer.isBuffer(rawData) || rawData instanceof ArrayBuffer
195
+ ? Buffer.from(rawData).toString("utf-8").slice(0, 500)
196
+ : ArrayBuffer.isView(rawData)
197
+ ? Buffer.from(rawData.buffer, rawData.byteOffset, rawData.byteLength)
198
+ .toString("utf-8")
199
+ .slice(0, 500)
200
+ : rawData || error.message;
201
+ logger.error("Response error:", logPayload);
64
202
  return Promise.reject(this.handleError(error));
65
203
  });
66
204
  }
@@ -83,7 +221,26 @@ export class ODataClient {
83
221
  */
84
222
  handleError(error) {
85
223
  if (error.response) {
86
- const odataError = error.response.data;
224
+ // When a request used responseType: "arraybuffer" (/$value reads),
225
+ // error payloads arrive as Buffer/ArrayBuffer rather than parsed JSON.
226
+ // Decode UTF-8 and attempt JSON.parse so OData error codes surface.
227
+ let responseData = error.response.data;
228
+ if (Buffer.isBuffer(responseData) ||
229
+ responseData instanceof ArrayBuffer ||
230
+ ArrayBuffer.isView(responseData)) {
231
+ try {
232
+ const buf = Buffer.isBuffer(responseData)
233
+ ? responseData
234
+ : ArrayBuffer.isView(responseData)
235
+ ? Buffer.from(responseData.buffer, responseData.byteOffset, responseData.byteLength)
236
+ : Buffer.from(responseData);
237
+ responseData = JSON.parse(buf.toString("utf-8"));
238
+ }
239
+ catch {
240
+ // Leave responseData as-is; fall through to HTTP status error below
241
+ }
242
+ }
243
+ const odataError = responseData;
87
244
  if (odataError?.error) {
88
245
  return new Error(`OData Error [${odataError.error.code}]: ${odataError.error.message}`);
89
246
  }
@@ -108,6 +265,31 @@ export class ODataClient {
108
265
  const rid = String(recordId);
109
266
  return /^-?\d+$/.test(rid) ? `(${rid})` : `('${rid.replace(/'/g, "''")}')`;
110
267
  }
268
+ /**
269
+ * Encode a field name for use as an OData URL path segment in
270
+ * `/{table}({id})/{field}/$value` style URLs.
271
+ *
272
+ * Spaces and Unicode are percent-encoded, while `:` (FMFID:12345 field
273
+ * IDs) and `[`/`]` (repetition index, when the caller already embedded
274
+ * it, e.g. `Field[2]`) stay literal. An optional 1-based `repetition`
275
+ * index is appended as `[n]` unless the field already ends with `]`.
276
+ */
277
+ encodeFieldSegment(field, repetition) {
278
+ if (!field || !field.trim() || field.includes("/")) {
279
+ throw new Error(`Invalid field name "${field}": must be non-empty and must not contain '/'`);
280
+ }
281
+ const encoded = encodeURIComponent(field)
282
+ .replace(/%3A/gi, ":")
283
+ .replace(/%5B/gi, "[")
284
+ .replace(/%5D/gi, "]");
285
+ if (repetition === undefined) {
286
+ return encoded;
287
+ }
288
+ if (!Number.isInteger(repetition) || repetition < 1) {
289
+ throw new Error(`Invalid repetition "${repetition}": must be an integer >= 1`);
290
+ }
291
+ return encoded.endsWith("]") ? encoded : `${encoded}[${repetition}]`;
292
+ }
111
293
  /**
112
294
  * Encode a value for an OData query-string parameter.
113
295
  *
@@ -412,6 +594,136 @@ export class ODataClient {
412
594
  await this.axiosInstance.delete(url);
413
595
  }
414
596
  // -------------------------------------------------------------------------
597
+ // Container & Field Value Operations (Plan 018)
598
+ // -------------------------------------------------------------------------
599
+ /**
600
+ * Upload container content inline as base64 inside a JSON PATCH body.
601
+ *
602
+ * FileMaker-specific OData extension: the base64 value is accompanied by
603
+ * `<field>@com.filemaker.odata.Filename` and
604
+ * `<field>@com.filemaker.odata.ContentType` annotation properties.
605
+ * FileMaker infers the media type from the first bytes of the decoded
606
+ * data — callers can compare `detectedMime` (magic-byte sniff on the
607
+ * client side) with the declared `contentType` and fall back to
608
+ * {@link uploadContainerBinary} when the types disagree.
609
+ */
610
+ async uploadContainerBase64(table, recordId, field, base64Data, filename, contentType) {
611
+ if (!field || !field.trim()) {
612
+ throw new Error("Invalid field name: must be non-empty");
613
+ }
614
+ const safeFilename = sanitizeHeaderValue(filename, "filename");
615
+ const safeContentType = sanitizeHeaderValue(contentType, "contentType");
616
+ const { cleanBase64, buffer } = normalizeAndValidateBase64(base64Data);
617
+ const detectedMime = detectContainerMimeFromBytes(buffer);
618
+ const payload = {
619
+ [field]: cleanBase64,
620
+ [`${field}@com.filemaker.odata.Filename`]: safeFilename,
621
+ [`${field}@com.filemaker.odata.ContentType`]: safeContentType,
622
+ };
623
+ const url = `${this.baseUrl}/${encodeURIComponent(table).replace(/%3A/gi, ":")}${this.entityKey(recordId)}`;
624
+ logger.debug(`Uploading container (base64): ${url} field=${field} (${buffer.length} bytes)`);
625
+ await this.axiosInstance.patch(url, payload, {
626
+ maxBodyLength: Infinity,
627
+ maxContentLength: Infinity,
628
+ });
629
+ return { sizeBytes: buffer.length, detectedMime };
630
+ }
631
+ /**
632
+ * Upload container content as a raw binary body.
633
+ *
634
+ * `PATCH /{table}({id})/{field}` with `Content-Type`, `Content-Disposition`,
635
+ * and `OData-Version` headers. Use this when FileMaker's magic-byte
636
+ * inference misidentifies a base64 upload — the explicit `Content-Type`
637
+ * header wins. Repetition index is NOT supported on upload by FileMaker
638
+ * OData.
639
+ */
640
+ async uploadContainerBinary(table, recordId, field, binaryData, filename, contentType) {
641
+ if (binaryData.byteLength === 0) {
642
+ throw new Error("Invalid binary data: buffer is empty");
643
+ }
644
+ const safeContentType = sanitizeHeaderValue(contentType, "contentType");
645
+ const disposition = formatContentDisposition(filename);
646
+ const url = `${this.baseUrl}/${encodeURIComponent(table).replace(/%3A/gi, ":")}${this.entityKey(recordId)}/${this.encodeFieldSegment(field)}`;
647
+ logger.debug(`Uploading container (binary): ${url} (${binaryData.byteLength} bytes)`);
648
+ await this.axiosInstance.patch(url, Buffer.from(binaryData), {
649
+ headers: {
650
+ "Content-Type": safeContentType,
651
+ "Content-Disposition": disposition,
652
+ "OData-Version": "4.0",
653
+ "OData-MaxVersion": "4.0",
654
+ },
655
+ maxBodyLength: Infinity,
656
+ maxContentLength: Infinity,
657
+ });
658
+ return { sizeBytes: binaryData.byteLength };
659
+ }
660
+ /**
661
+ * Download raw bytes from a container field via `/{field}/$value`.
662
+ *
663
+ * Container fields are excluded from normal record responses, so this is
664
+ * the only way to read them. Bytes are wrapped in base64 for JSON-RPC
665
+ * safety. `contentType` comes from the response header, falling back to
666
+ * magic-byte detection when the server reports
667
+ * `application/octet-stream` (or omits the header).
668
+ */
669
+ async downloadContainer(table, recordId, field, repetition) {
670
+ const url = `${this.baseUrl}/${encodeURIComponent(table).replace(/%3A/gi, ":")}${this.entityKey(recordId)}/${this.encodeFieldSegment(field, repetition)}/$value`;
671
+ logger.debug(`Downloading container: ${url}`);
672
+ const response = await this.axiosInstance.get(url, {
673
+ responseType: "arraybuffer",
674
+ headers: { Accept: "*/*" },
675
+ maxContentLength: Infinity,
676
+ });
677
+ const buf = Buffer.isBuffer(response.data)
678
+ ? response.data
679
+ : Buffer.from(response.data ?? []);
680
+ const headerType = response.headers?.["content-type"];
681
+ let contentType = headerType
682
+ ? String(headerType).split(";")[0].trim().toLowerCase()
683
+ : "";
684
+ if (!contentType || contentType === "application/octet-stream") {
685
+ contentType =
686
+ detectContainerMimeFromBytes(buf) ??
687
+ (contentType || "application/octet-stream");
688
+ }
689
+ const filename = parseContentDispositionFilename(response.headers?.["content-disposition"]);
690
+ return {
691
+ base64Data: buf.toString("base64"),
692
+ contentType,
693
+ sizeBytes: buf.length,
694
+ ...(filename ? { filename } : {}),
695
+ };
696
+ }
697
+ /**
698
+ * Read the raw value of a single field via `/{field}/$value`.
699
+ *
700
+ * Scalar fields come back as `text/plain` (HTTP 204 when empty/null).
701
+ * Container fields return binary media types — those are reported via
702
+ * `isBinaryContainer` so callers can redirect to
703
+ * {@link downloadContainer} instead of decoding them as text.
704
+ */
705
+ async getFieldValue(table, recordId, field, repetition) {
706
+ const url = `${this.baseUrl}/${encodeURIComponent(table).replace(/%3A/gi, ":")}${this.entityKey(recordId)}/${this.encodeFieldSegment(field, repetition)}/$value`;
707
+ logger.debug(`Getting field value: ${url}`);
708
+ const response = await this.axiosInstance.get(url, {
709
+ responseType: "arraybuffer",
710
+ headers: { Accept: "text/plain, */*" },
711
+ });
712
+ const headerType = response.headers?.["content-type"];
713
+ const contentType = headerType
714
+ ? String(headerType).split(";")[0].trim().toLowerCase()
715
+ : "text/plain";
716
+ const isBinaryContainer = !isTextualMediaType(contentType);
717
+ if (response.status === 204) {
718
+ return { value: null, contentType, isBinaryContainer: false };
719
+ }
720
+ if (isBinaryContainer) {
721
+ return { value: null, contentType, isBinaryContainer: true };
722
+ }
723
+ const value = Buffer.from(response.data ?? []).toString("utf-8");
724
+ return { value, contentType, isBinaryContainer: false };
725
+ }
726
+ // -------------------------------------------------------------------------
415
727
  // Batch / bulk operations (Plan 013)
416
728
  // -------------------------------------------------------------------------
417
729
  /**