zinkee 0.1.68 → 0.1.70

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
@@ -388,6 +388,9 @@ zinkee schemas fields update projects start-date --raw '{
388
388
 
389
389
  # Text type (valid values: NORMAL, LONG)
390
390
  zinkee schemas fields update projects description --raw '{"type":"TextField","config":{"textType":"LONG"}}'
391
+
392
+ # Warn in the web when a value is not a valid CIF (also: none, length, dniNie, email, iban)
393
+ zinkee schemas fields update customers nif --raw '{"type":"TextField","config":{"expectedFormat":{"kind":"cif"}}}'
391
394
  ```
392
395
 
393
396
  ### Formula syntax
@@ -1003,8 +1006,40 @@ zinkee --json automations actions add <automation-uuid> \
1003
1006
  --name "Clone budget" \
1004
1007
  --plugin clone-budget \
1005
1008
  --arg mode=safe
1009
+
1010
+ # Send email (needs an active, verified SMTP connection: automations connections list)
1011
+ zinkee --json automations actions add <automation-uuid> \
1012
+ --type send_email \
1013
+ --name "Notify operations" \
1014
+ --connection <smtp-connection-uuid> \
1015
+ --cc operations@example.com \
1016
+ --subject "New project" \
1017
+ --message "<p>A project was created.</p>"
1006
1018
  ```
1007
1019
 
1020
+ ### Send email
1021
+
1022
+ `send_email` sends a real email; `send_message` is an in-app notification.
1023
+
1024
+ - `--to`, `--cc` and `--bcc` repeat; `--reply-to` takes one value. An email can go only in copy.
1025
+ - Each recipient is a fixed address or `${key}`, a placeholder declared in `config.variables` that takes the address from a field. The API rejects a malformed address (`automation_email_recipient_invalid`) and an undeclared `${key}` (`automation_email_variable_undeclared`).
1026
+ - `config.variables` maps each key to `{"sourceType":"trigger_field","fieldId":"<field-uuid>"}` (the triggering record) or `{"sourceType":"previous_action","actionId":"<action-uuid>","fieldId":"<field-uuid>"}`. These source types are lower case, unlike the field mapping ones.
1027
+ - `config.attachments` takes `{"sourceType":"trigger_field","fieldId":"<file-field-uuid>","name":"Contract","skipIfEmpty":true}`. With `skipIfEmpty`, an empty file field sends the email without that attachment; without it the send fails. A file that cannot be downloaded always fails it.
1028
+ - Pass `variables` and `attachments` with `--raw-file`; the typed flags override the file. See `zinkee automations actions add --example`.
1029
+
1030
+ ### Dates relative to today
1031
+
1032
+ A condition on a date field can compare with «today ± N days», written as JSON text in `rawValue`: `{"type":"today","offset":5,"ianaTimeZone":"Europe/Madrid"}`. `--condition-today field:comparator[:±N]` builds it with the workspace time zone, in triggers (`--trigger-schema`) and in `search_records`/`update_record` (`--target-schema`):
1033
+
1034
+ ```bash
1035
+ zinkee --json automations actions add <automation-uuid> \
1036
+ --type search_records --name "Invoices due in 5 days" \
1037
+ --target-schema <invoices-uuid> \
1038
+ --condition-today <due-date-field-uuid>:eq:+5
1039
+ ```
1040
+
1041
+ Comparators: `eq` (the whole day), `ne`, `gt`, `ge`, `lt`, `le`. N is a whole number of days up to 3650. The API rejects a malformed value with `automation_condition_dynamic_date_invalid`. `--condition` splits its value on commas, so it cannot carry JSON; use `--condition-json` with the JSON as a string value instead. A record-changed trigger only checks its conditions when the record changes: for a daily reminder, use a scheduled trigger with a `search_records` action.
1042
+
1008
1043
  Valid action types: `create_record`, `update_record`, `search_records`, `send_message`, `send_email`, `http_request`, `execute_plugin`, `generate_document`, `invoicing`.
1009
1044
 
1010
1045
  ### Field mapping format
@@ -489,7 +489,7 @@ var fieldTypeDefinitions = [
489
489
  key: "text",
490
490
  className: "TextField",
491
491
  aliases: ["text", "TextField"],
492
- description: "Plain text field.",
492
+ description: "Plain text field. config.expectedFormat ({kind: none|length|dniNie|cif|email|iban}) warns in the web on values that do not fit (DNI/NIE, CIF, email, IBAN or a length); it never blocks saving.",
493
493
  rawShape: '{"type":"TextField","slug":"name","label":"Name","config":{"textType":"NORMAL"}}',
494
494
  examplePayloads: [
495
495
  {
@@ -506,6 +506,19 @@ var fieldTypeDefinitions = [
506
506
  }
507
507
  }
508
508
  },
509
+ {
510
+ name: "Text field with an expected format (CIF)",
511
+ payload: {
512
+ type: "TextField",
513
+ slug: "nif",
514
+ label: "NIF",
515
+ required: false,
516
+ config: {
517
+ textType: "NORMAL",
518
+ expectedFormat: { kind: "cif" }
519
+ }
520
+ }
521
+ },
509
522
  {
510
523
  name: "Text field (long)",
511
524
  payload: {
@@ -1408,4 +1421,4 @@ export {
1408
1421
  buildSchemaFieldCreateHelpText,
1409
1422
  buildSchemaFieldCreateValidationMessage
1410
1423
  };
1411
- //# sourceMappingURL=chunk-DCC56F2L.js.map
1424
+ //# sourceMappingURL=chunk-SVBC47AD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/output.ts","../src/client.ts","../src/utils/errors.ts","../src/utils/schema-fields.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\n\nimport type {\n JsonEnvelopeMeta,\n JsonErrorEnvelope,\n JsonSuccessEnvelope,\n} from \"../types.js\";\n\nconst require = createRequire(import.meta.url);\n\nexport interface OutputWriter {\n write(chunk: string): unknown;\n}\n\nfunction stringifyCellValue(value: unknown): string {\n if (value === null || value === undefined) {\n return \"\";\n }\n\n if (typeof value === \"string\") {\n return value;\n }\n\n if (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n return String(value);\n }\n\n return JSON.stringify(value);\n}\n\nexport function buildJsonSuccess<TData, TMeta extends JsonEnvelopeMeta = JsonEnvelopeMeta>(\n data: TData,\n meta: TMeta = {} as TMeta,\n): JsonSuccessEnvelope<TData, TMeta> {\n return { data, meta };\n}\n\nexport function buildJsonError<TErr, TMeta extends JsonEnvelopeMeta = JsonEnvelopeMeta>(\n error: TErr,\n meta: TMeta = {} as TMeta,\n): JsonErrorEnvelope<TErr, TMeta> {\n return { error, meta };\n}\n\nexport interface FolderLocation {\n id?: string;\n name?: string | null;\n isRoot?: boolean;\n}\n\n/** Column keys, in order, produced by {@link folderColumns}. Append them to a table's key list. */\nexport const FOLDER_TABLE_KEYS = [\"folderId\", \"folderName\", \"folderIsRoot\"] as const;\n\n/**\n * Flattens the API `folder` object (`{ id, name, isRoot }`) into the folderId/folderName/folderIsRoot table columns.\n * The root folder arrives with a null name, so folderName renders it as \"(root)\". A missing folder (e.g. a workspace\n * without a default group) leaves every column empty.\n */\nexport function folderColumns(folder: FolderLocation | null | undefined): {\n folderId: string;\n folderName: string;\n folderIsRoot: string;\n} {\n if (!folder) {\n return { folderId: \"\", folderName: \"\", folderIsRoot: \"\" };\n }\n\n return {\n folderId: folder.id ?? \"\",\n folderName: folder.name ?? (folder.isRoot === true ? \"(root)\" : \"\"),\n folderIsRoot: folder.isRoot === undefined ? \"\" : String(folder.isRoot),\n };\n}\n\nexport function printTable(\n rows: readonly Record<string, unknown>[],\n keys?: readonly string[],\n writer?: OutputWriter,\n): void {\n const output = writer ?? process.stdout;\n const firstRow = rows[0];\n\n if (!firstRow) {\n output.write(\"No results.\\n\");\n return;\n }\n\n const headings = [...(keys ?? Object.keys(firstRow))];\n const Table = require(\"cli-table3\") as typeof import(\"cli-table3\");\n const table = new Table({\n head: headings,\n wordWrap: true,\n });\n\n for (const row of rows) {\n table.push(headings.map((heading) => stringifyCellValue(row[heading])));\n }\n\n output.write(`${table.toString()}\\n`);\n}\n","import { createRequire } from \"node:module\";\nimport { Readable, Transform, type Writable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\n\nconst require = createRequire(import.meta.url);\n\nlet cliUserAgent: string | undefined;\n\n/**\n * `zinkee-cli/<version>`, read from the CLI's package.json on first use: code that compiles this\n * client from another folder passes `userAgent` and never reads it.\n */\nfunction defaultUserAgent(): string {\n if (cliUserAgent === undefined) {\n const { version } = require(\"../package.json\") as { version: string };\n cliUserAgent = `zinkee-cli/${version}`;\n }\n\n return cliUserAgent;\n}\n\nexport interface ApiClientOptions {\n baseUrl: string;\n /** Sent as User-Agent; defaults to `zinkee-cli/<version>`. */\n userAgent?: string;\n apiKey?: string;\n /** Resolves the bearer token on the first request instead of apiKey; called at most once. */\n getToken?: () => Promise<string>;\n timeoutMs?: number;\n fetch?: typeof fetch;\n /** Sent as Idempotency-Key on write requests, which are then retried on transient failures. */\n idempotencyKey?: string;\n /** Called before each wait on a 429 response that is going to be retried. */\n onRateLimitRetry?: (retry: RateLimitRetry) => void;\n}\n\nexport interface RateLimitRetry {\n /** Seconds the server asked to wait in Retry-After, before jitter. */\n retryAfterSeconds: number;\n /** Number of the attempt sent after the wait, counting the first request. */\n nextAttempt: number;\n maxAttempts: number;\n}\n\nexport type ApiClientErrorCode =\n | \"network_error\"\n | \"http_error\"\n | \"timeout\"\n | \"invalid_json\";\n\nexport interface ApiClientErrorDetails {\n url: string;\n method: string;\n status?: number;\n responseBody?: unknown;\n responseText?: string;\n retryAfter?: string;\n cause?: unknown;\n}\n\nexport class ApiClientError extends Error {\n override name = \"ApiClientError\";\n\n readonly code: ApiClientErrorCode;\n\n readonly url: string;\n\n readonly method: string;\n\n readonly status?: number;\n\n readonly responseBody?: unknown;\n\n readonly responseText?: string;\n\n readonly retryAfter?: string;\n\n override readonly cause?: unknown;\n\n constructor(\n code: ApiClientErrorCode,\n message: string,\n details: ApiClientErrorDetails,\n ) {\n super(message);\n this.code = code;\n this.url = details.url;\n this.method = details.method;\n this.status = details.status;\n this.responseBody = details.responseBody;\n this.responseText = details.responseText;\n this.retryAfter = details.retryAfter;\n this.cause = details.cause;\n }\n}\n\nexport interface ApiRequestOptions extends RequestInit {\n timeoutMs?: number;\n}\n\nfunction isJsonContentType(contentType: string | null): boolean {\n return contentType ? /(^|\\/|\\+)json\\b/i.test(contentType) : false;\n}\n\nfunction looksLikeJson(text: string): boolean {\n const trimmed = text.trim();\n\n return (\n trimmed.startsWith(\"{\") ||\n trimmed.startsWith(\"[\") ||\n trimmed === \"null\" ||\n trimmed === \"true\" ||\n trimmed === \"false\" ||\n /^-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?$/.test(trimmed) ||\n trimmed.startsWith('\"')\n );\n}\n\nfunction parseJsonBody<T>(text: string, url: string, method: string): T {\n const trimmed = text.trim();\n\n if (trimmed.length === 0) {\n return undefined as T;\n }\n\n try {\n return JSON.parse(trimmed) as T;\n } catch (cause) {\n throw new ApiClientError(\"invalid_json\", `Failed to parse JSON response from ${method} ${url}.`, {\n url,\n method,\n responseText: text,\n cause,\n });\n }\n}\n\nfunction parseErrorBody(text: string, contentType: string | null): unknown {\n if (text.trim().length === 0) {\n return undefined;\n }\n\n if (!isJsonContentType(contentType) && !looksLikeJson(text)) {\n return text;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction summarizeNetworkCause(cause: unknown): string | undefined {\n const seen = new Set<unknown>();\n let current: unknown = cause;\n\n while (current && typeof current === \"object\" && !seen.has(current)) {\n seen.add(current);\n\n const candidate = current as { message?: unknown; code?: unknown; cause?: unknown };\n const message = typeof candidate.message === \"string\" ? candidate.message.trim() : \"\";\n const code = typeof candidate.code === \"string\" ? candidate.code : undefined;\n\n if (message && message !== \"fetch failed\") {\n return code && !message.includes(code) ? `${message} (${code})` : message;\n }\n\n current = candidate.cause;\n }\n\n return undefined;\n}\n\nconst IDEMPOTENT_WRITE_METHODS = new Set([\"POST\", \"PATCH\", \"PUT\", \"DELETE\"]);\n/** Attempts per request, shared by every kind of retry. */\nconst MAX_ATTEMPTS = 3;\nconst MAX_RETRY_AFTER_MS = 30_000;\n/**\n * Rate-limit waits per client, which is per command: a command that sends several requests still\n * ends within Kraken's 120 s bash timeout.\n */\nconst MAX_RATE_LIMIT_WAIT_MS = 60_000;\nconst MAX_RATE_LIMIT_JITTER_MS = 250;\n\n/** Reads Retry-After in delta-seconds; an HTTP-date or any other form gives undefined. */\nexport function parseRetryAfterSeconds(retryAfter: string | undefined): number | undefined {\n const value = retryAfter?.trim();\n\n return value && /^\\d+$/.test(value) ? Number(value) : undefined;\n}\n\n/** `:query` and `:aggregate` endpoints only read, so the server ignores the key there. */\nconst READ_ONLY_POST_PATH = /:(query|aggregate)$/;\n\nfunction acceptsIdempotencyKey(method: string, url: string): boolean {\n return IDEMPOTENT_WRITE_METHODS.has(method.toUpperCase()) && !READ_ONLY_POST_PATH.test(new URL(url).pathname);\n}\n\n/** Streams and form data cannot be sent twice as they are. */\nfunction isReusableBody(body: RequestInit[\"body\"]): boolean {\n return body === undefined || body === null || typeof body === \"string\" || body instanceof Uint8Array;\n}\n\nfunction isRetryableWithIdempotencyKey(error: unknown): error is ApiClientError {\n if (!(error instanceof ApiClientError)) {\n return false;\n }\n\n if (error.code === \"network_error\" || error.code === \"timeout\") {\n return true;\n }\n\n const body = error.responseBody;\n return error.status === 409\n && typeof body === \"object\"\n && body !== null\n && (body as { reason?: unknown }).reason === \"idempotency_request_in_progress\";\n}\n\nfunction idempotentRetryDelayMs(error: ApiClientError, attempt: number): number {\n const retryAfterSeconds = parseRetryAfterSeconds(error.retryAfter);\n\n if (retryAfterSeconds !== undefined) {\n return Math.min(retryAfterSeconds * 1000, MAX_RETRY_AFTER_MS);\n }\n\n return 1000 * 2 ** (attempt - 1);\n}\n\n/**\n * Seconds to wait before retrying a 429, or undefined when it must not be retried: without a\n * delta-seconds Retry-After (a request that costs more than the whole limit gets none) or with\n * a longer wait than the cap, which is reported instead of blocking the command.\n */\nfunction rateLimitRetrySeconds(error: unknown): number | undefined {\n if (!(error instanceof ApiClientError) || error.status !== 429) {\n return undefined;\n }\n\n const retryAfterSeconds = parseRetryAfterSeconds(error.retryAfter);\n\n return retryAfterSeconds !== undefined && retryAfterSeconds * 1000 <= MAX_RETRY_AFTER_MS\n ? retryAfterSeconds\n : undefined;\n}\n\n/** Spreads clients that hit the limit together so they do not all retry at the same instant. */\nfunction rateLimitJitterMs(): number {\n return Math.floor(Math.random() * (MAX_RATE_LIMIT_JITTER_MS + 1));\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport class ApiClient {\n private readonly fetchImpl: typeof fetch;\n\n private tokenPromise?: Promise<string>;\n\n /** Time already spent waiting on rate limits, across every request of this client. */\n private rateLimitWaitedMs = 0;\n\n constructor(private readonly options: ApiClientOptions) {\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n getJson<T>(path: string, init: ApiRequestOptions = {}): Promise<T> {\n return this.requestJson<T>(path, { ...init, method: \"GET\" });\n }\n\n requestJson<T>(path: string, init: ApiRequestOptions = {}): Promise<T> {\n return this.request(\n path,\n init,\n async (response, url) => {\n const text = await response.text();\n return parseJsonBody<T>(text, url, init.method ?? \"GET\");\n },\n \"application/json\",\n );\n }\n\n download(\n path: string,\n destination: Writable,\n init: ApiRequestOptions = {},\n ): Promise<number> {\n return this.request(path, init, async (response, _url, signal) => {\n let bytes = 0;\n const counter = new Transform({\n transform(chunk: Buffer, _encoding, callback) {\n bytes += chunk.length;\n callback(null, chunk);\n },\n });\n const source = response.body\n ? Readable.fromWeb(response.body as Parameters<typeof Readable.fromWeb>[0])\n : Readable.from([]);\n\n await pipeline(source, counter, destination, { signal });\n return bytes;\n });\n }\n\n private buildUrl(path: string): string {\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n\n return new URL(normalizedPath, this.options.baseUrl).toString();\n }\n\n private async request<T>(\n path: string,\n init: ApiRequestOptions,\n consume: (response: Response, url: string, signal: AbortSignal) => Promise<T>,\n accept?: string,\n ): Promise<T> {\n const url = this.buildUrl(path);\n const method = init.method ?? \"GET\";\n const headers = new Headers(init.headers);\n headers.set(\"user-agent\", this.options.userAgent ?? defaultUserAgent());\n\n if (accept && !headers.has(\"accept\")) {\n headers.set(\"accept\", accept);\n }\n\n // Awaited outside the try below so its own errors are not reported as network errors.\n const token = this.options.getToken\n ? await (this.tokenPromise ??= this.options.getToken())\n : this.options.apiKey;\n\n if (token && !headers.has(\"authorization\")) {\n headers.set(\"authorization\", `Bearer ${token}`);\n }\n\n const { idempotencyKey } = this.options;\n\n if (idempotencyKey && !headers.has(\"idempotency-key\") && acceptsIdempotencyKey(method, url)) {\n headers.set(\"idempotency-key\", idempotencyKey);\n }\n\n const keyed = headers.has(\"idempotency-key\");\n const reusableBody = isReusableBody(init.body);\n\n for (let attempt = 1; ; attempt += 1) {\n try {\n return await this.send(url, method, headers, init, consume);\n } catch (error) {\n if (!reusableBody || attempt >= MAX_ATTEMPTS || init.signal?.aborted) {\n throw error;\n }\n\n // The server answers 429 before any side effect, so it is retried with or without a key.\n const rateLimitSeconds = rateLimitRetrySeconds(error);\n\n if (\n rateLimitSeconds !== undefined &&\n this.rateLimitWaitedMs + rateLimitSeconds * 1000 <= MAX_RATE_LIMIT_WAIT_MS\n ) {\n this.options.onRateLimitRetry?.({\n retryAfterSeconds: rateLimitSeconds,\n nextAttempt: attempt + 1,\n maxAttempts: MAX_ATTEMPTS,\n });\n this.rateLimitWaitedMs += rateLimitSeconds * 1000;\n await sleep(rateLimitSeconds * 1000 + rateLimitJitterMs());\n continue;\n }\n\n // Anything else is only retried with a key: the server replays or rejects a repeat instead of running it again.\n if (!keyed || !isRetryableWithIdempotencyKey(error)) {\n throw error;\n }\n\n await sleep(idempotentRetryDelayMs(error, attempt));\n }\n }\n }\n\n private async send<T>(\n url: string,\n method: string,\n headers: Headers,\n init: ApiRequestOptions,\n consume: (response: Response, url: string, signal: AbortSignal) => Promise<T>,\n ): Promise<T> {\n const controller = new AbortController();\n const timeoutMs = init.timeoutMs ?? this.options.timeoutMs;\n let timedOut = false;\n let timeoutHandle: ReturnType<typeof setTimeout> | undefined;\n\n const abortListener = (): void => {\n controller.abort(init.signal?.reason);\n };\n\n if (init.signal) {\n if (init.signal.aborted) {\n controller.abort(init.signal.reason);\n } else {\n init.signal.addEventListener(\"abort\", abortListener, { once: true });\n }\n }\n\n if (timeoutMs !== undefined) {\n timeoutHandle = setTimeout(() => {\n if (!controller.signal.aborted) {\n timedOut = true;\n controller.abort();\n }\n }, timeoutMs);\n }\n\n try {\n controller.signal.throwIfAborted();\n const response = await this.fetchImpl(url, {\n ...init,\n headers,\n signal: controller.signal,\n });\n const responseUrl = response.url || url;\n\n if (!response.ok) {\n const text = await response.text();\n throw this.buildHttpError(response, text, init, responseUrl);\n }\n\n return await consume(response, responseUrl, controller.signal);\n } catch (cause) {\n if (cause instanceof ApiClientError) {\n throw cause;\n }\n\n if (timedOut) {\n throw new ApiClientError(\"timeout\", `Request timed out after ${timeoutMs}ms.`, {\n url,\n method,\n cause,\n });\n }\n\n const causeSummary = summarizeNetworkCause(cause);\n const message = causeSummary\n ? `Request failed for ${method} ${url}: ${causeSummary}.`\n : `Request failed for ${method} ${url}.`;\n\n throw new ApiClientError(\"network_error\", message, {\n url,\n method,\n cause,\n });\n } finally {\n if (timeoutHandle !== undefined) {\n clearTimeout(timeoutHandle);\n }\n\n if (init.signal) {\n init.signal.removeEventListener(\"abort\", abortListener);\n }\n }\n }\n\n private buildHttpError(\n response: Response,\n text: string,\n init: ApiRequestOptions,\n url: string,\n ): ApiClientError {\n const method = init.method ?? \"GET\";\n const responseBody = parseErrorBody(text, response.headers.get(\"content-type\"));\n\n return new ApiClientError(\n \"http_error\",\n `Request failed with status ${response.status} for ${method} ${url}.`,\n {\n url,\n method,\n status: response.status,\n responseBody,\n responseText: responseBody === text ? text : undefined,\n retryAfter: response.headers.get(\"retry-after\") ?? undefined,\n },\n );\n }\n}\n","import { ApiClientError, parseRetryAfterSeconds } from \"../client.js\";\nimport type { JsonEnvelopeMeta, JsonErrorEnvelope } from \"../types.js\";\n\nimport { buildJsonError } from \"./output.js\";\n\nexport type CliErrorCode =\n | \"unknown_error\"\n | \"invalid_cli_usage\"\n | \"configuration_error\"\n | \"authentication_required\"\n | \"command_not_allowed_in_read_only_mode\"\n | \"rate_limited\"\n | \"network_error\"\n | \"http_error\"\n | \"timeout\"\n | \"invalid_json\";\n\nexport const cliExitCodeByErrorCode = {\n unknown_error: 1,\n invalid_cli_usage: 2,\n configuration_error: 2,\n authentication_required: 3,\n rate_limited: 4,\n command_not_allowed_in_read_only_mode: 7,\n network_error: 1,\n http_error: 1,\n timeout: 1,\n invalid_json: 1,\n} as const satisfies Record<CliErrorCode, number>;\n\nexport interface CliErrorDetails {\n [key: string]: unknown;\n}\n\nexport interface CliErrorPayload {\n code: CliErrorCode;\n message: string;\n exitCode: number;\n details?: CliErrorDetails;\n}\n\nconst errorCodeByName: Record<string, CliErrorCode> = {\n ProfileResolutionError: \"configuration_error\",\n};\n\nexport class CliError extends Error {\n override name = \"CliError\";\n\n readonly code: CliErrorCode;\n\n readonly exitCode: number;\n\n readonly details?: CliErrorDetails;\n\n constructor(\n code: CliErrorCode,\n message: string,\n details: CliErrorDetails = {},\n exitCode: number = cliExitCodeByErrorCode[code],\n ) {\n super(message);\n this.code = code;\n this.exitCode = exitCode;\n\n if (Object.keys(details).length > 0) {\n this.details = details;\n }\n }\n\n toJSON(): CliErrorPayload {\n const payload: CliErrorPayload = {\n code: this.code,\n message: this.message,\n exitCode: this.exitCode,\n };\n\n if (this.details) {\n payload.details = this.details;\n }\n\n return payload;\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction readString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim().length > 0 ? value : undefined;\n}\n\nfunction readNumber(value: unknown): number | undefined {\n return typeof value === \"number\" ? value : undefined;\n}\n\nfunction extractApiErrorDetails(error: ApiClientError): {\n message: string;\n details: CliErrorDetails;\n meta: JsonEnvelopeMeta;\n} {\n const details: CliErrorDetails = {};\n const meta: JsonEnvelopeMeta = {};\n const responseBody = isRecord(error.responseBody) ? error.responseBody : undefined;\n const errorBody = responseBody?.error;\n const backendError = isRecord(errorBody) ? errorBody : responseBody;\n const backendMeta = isRecord(responseBody?.meta) ? responseBody.meta : undefined;\n const reason =\n readString(backendError?.reason) ??\n readString(backendError?.code);\n const action = readString(backendError?.action);\n const requestId =\n readString(backendMeta?.requestId) ??\n readString(responseBody?.requestId) ??\n readString(backendError?.requestId);\n const status =\n readNumber(backendError?.status) ??\n readNumber(responseBody?.status) ??\n error.status;\n const backendMessage = readString(backendError?.message);\n\n if (reason !== undefined) {\n details.reason = reason;\n }\n\n if (action !== undefined) {\n details.action = action;\n }\n\n if (requestId !== undefined) {\n details.requestId = requestId;\n meta.requestId = requestId;\n }\n\n if (status !== undefined) {\n details.status = status;\n meta.status = status;\n }\n\n const retryAfterSeconds = error.status === 429 ? parseRetryAfterSeconds(error.retryAfter) : undefined;\n\n if (retryAfterSeconds !== undefined) {\n details.retryAfterSeconds = retryAfterSeconds;\n }\n\n return {\n message: backendMessage ?? error.message,\n details,\n meta,\n };\n}\n\nexport function toCliError(error: unknown): CliError {\n if (error instanceof CliError) {\n return error;\n }\n\n if (error instanceof ApiClientError) {\n const apiError = extractApiErrorDetails(error);\n // A 429 reaching here was not retried or ran out of attempts.\n const code = error.status === 429 ? \"rate_limited\" : error.code;\n\n return new CliError(code, apiError.message, apiError.details);\n }\n\n if (error instanceof Error) {\n return new CliError(errorCodeByName[error.name] ?? \"unknown_error\", error.message);\n }\n\n return new CliError(\"unknown_error\", \"Unknown error\");\n}\n\nexport function getExitCode(error: unknown): number {\n return toCliError(error).exitCode;\n}\n\nexport function buildJsonCliError<TMeta extends JsonEnvelopeMeta = JsonEnvelopeMeta>(\n error: unknown,\n meta: TMeta = {} as TMeta,\n): JsonErrorEnvelope<CliErrorPayload, TMeta> {\n const cliError = toCliError(error);\n const apiErrorMeta =\n error instanceof ApiClientError\n ? extractApiErrorDetails(error).meta\n : {};\n\n return buildJsonError(cliError.toJSON(), { ...apiErrorMeta, ...meta } as TMeta);\n}\n\nexport function formatCliErrorText(error: unknown): string {\n return toCliError(error).message;\n}\n\nexport function formatCliErrorJson<TMeta extends JsonEnvelopeMeta = JsonEnvelopeMeta>(\n error: unknown,\n meta: TMeta = {} as TMeta,\n): string {\n return JSON.stringify(buildJsonCliError(error, meta));\n}\n","import type { JsonObject } from \"../types.js\";\nimport { CliError } from \"./errors.js\";\n\nexport type SchemaFieldTypeKey =\n | \"text\"\n | \"number\"\n | \"date\"\n | \"option\"\n | \"file\"\n | \"reference\"\n | \"formula\"\n | \"member\"\n | \"autoincremental\"\n | \"schedule\";\n\nexport interface SchemaFieldExamplePayload {\n name: string;\n payload: JsonObject;\n}\n\nexport interface SchemaFieldTypeDefinition {\n key: SchemaFieldTypeKey;\n className: string;\n aliases: readonly string[];\n description: string;\n rawShape: string;\n examplePayloads: readonly SchemaFieldExamplePayload[];\n}\n\nfunction isJsonObject(value: unknown): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction toJsonObject(value: unknown): JsonObject | undefined {\n return isJsonObject(value) ? value : undefined;\n}\n\nfunction toStringValue(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim().length > 0 ? value : undefined;\n}\n\nfunction toNumberValue(value: unknown): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return value;\n }\n\n if (typeof value === \"string\" && value.trim().length > 0) {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) {\n return parsed;\n }\n }\n\n return undefined;\n}\n\nconst fieldTypeDefinitions = [\n {\n key: \"text\",\n className: \"TextField\",\n aliases: [\"text\", \"TextField\"],\n description:\n \"Plain text field. config.expectedFormat ({kind: none|length|dniNie|cif|email|iban}) warns in the web on values that do not fit (DNI/NIE, CIF, email, IBAN or a length); it never blocks saving.\",\n rawShape:\n '{\"type\":\"TextField\",\"slug\":\"name\",\"label\":\"Name\",\"config\":{\"textType\":\"NORMAL\"}}',\n examplePayloads: [\n {\n name: \"Text field (normal)\",\n payload: {\n type: \"TextField\",\n slug: \"customer-name\",\n label: \"Customer Name\",\n required: true,\n config: {\n textType: \"NORMAL\",\n defaultValue: null,\n conditionalFormatting: [],\n },\n },\n },\n {\n name: \"Text field with an expected format (CIF)\",\n payload: {\n type: \"TextField\",\n slug: \"nif\",\n label: \"NIF\",\n required: false,\n config: {\n textType: \"NORMAL\",\n expectedFormat: { kind: \"cif\" },\n },\n },\n },\n {\n name: \"Text field (long)\",\n payload: {\n type: \"TextField\",\n slug: \"customer-notes\",\n label: \"Customer Notes\",\n required: false,\n config: {\n textType: \"LONG\",\n defaultValue: \"Add internal notes here...\",\n conditionalFormatting: [],\n },\n },\n },\n ],\n },\n {\n key: \"number\",\n className: \"NumberField\",\n aliases: [\"number\", \"NumberField\"],\n description: \"Numeric field.\",\n rawShape:\n '{\"type\":\"NumberField\",\"slug\":\"quantity\",\"label\":\"Quantity\",\"config\":{\"defaultValue\":\"0\",\"formatOptions\":{\"format\":\"number\",\"decimals\":0,\"thousandsSeparator\":false}}}',\n examplePayloads: [\n {\n name: \"Number field (plain integer)\",\n payload: {\n type: \"NumberField\",\n slug: \"quantity\",\n label: \"Quantity\",\n required: false,\n config: {\n defaultValue: \"0\",\n formatOptions: {\n format: \"number\",\n decimals: 0,\n thousandsSeparator: false,\n },\n conditionalFormatting: [],\n },\n },\n },\n {\n name: \"Number field (decimal with thousands)\",\n payload: {\n type: \"NumberField\",\n slug: \"weight\",\n label: \"Weight (kg)\",\n required: false,\n config: {\n defaultValue: \"0\",\n formatOptions: {\n format: \"number\",\n decimals: 2,\n thousandsSeparator: true,\n negativesInRed: false,\n },\n conditionalFormatting: [],\n },\n },\n },\n {\n name: \"Number field (currency € prefix)\",\n payload: {\n type: \"NumberField\",\n slug: \"amount-eur\",\n label: \"Amount (EUR)\",\n required: false,\n config: {\n defaultValue: \"0\",\n formatOptions: {\n format: \"currency\",\n decimals: 2,\n negativesInRed: true,\n thousandsSeparator: true,\n symbolEnabled: true,\n symbolPosition: \"before\",\n symbolValue: \"€\",\n },\n conditionalFormatting: [],\n },\n },\n },\n {\n name: \"Number field (currency $ suffix)\",\n payload: {\n type: \"NumberField\",\n slug: \"amount-usd\",\n label: \"Amount (USD)\",\n required: false,\n config: {\n defaultValue: \"0\",\n formatOptions: {\n format: \"currency\",\n decimals: 2,\n negativesInRed: false,\n thousandsSeparator: true,\n symbolEnabled: true,\n symbolPosition: \"right\",\n symbolValue: \" $\",\n },\n conditionalFormatting: [],\n },\n },\n },\n {\n name: \"Number field (percentage)\",\n payload: {\n type: \"NumberField\",\n slug: \"discount-rate\",\n label: \"Discount Rate\",\n required: false,\n config: {\n defaultValue: \"0\",\n formatOptions: {\n format: \"percentage\",\n decimals: 1,\n negativesInRed: true,\n },\n conditionalFormatting: [],\n },\n },\n },\n {\n name: \"Number field (duration HH:MM)\",\n payload: {\n type: \"NumberField\",\n slug: \"tracked-time\",\n label: \"Tracked Time\",\n required: false,\n config: {\n defaultValue: \"0\",\n formatOptions: {\n format: \"duration\",\n durationFormat: \"HH:MM\",\n },\n conditionalFormatting: [],\n },\n },\n },\n ],\n },\n {\n key: \"date\",\n className: \"DateField\",\n aliases: [\"date\", \"DateField\"],\n description: \"Date or datetime field.\",\n rawShape:\n '{\"type\":\"DateField\",\"slug\":\"due-date\",\"label\":\"Due Date\",\"config\":{\"formatOptions\":{\"format\":\"date\",\"dateFormat\":\"YYYY-MM-DD\",\"showTime\":false}}}',\n examplePayloads: [\n {\n name: \"Date field (date only)\",\n payload: {\n type: \"DateField\",\n slug: \"birth-date\",\n label: \"Birth Date\",\n required: false,\n config: {\n defaultValue: null,\n formatOptions: {\n format: \"date\",\n dateFormat: \"YYYY-MM-DD\",\n showTime: false,\n },\n conditionalFormatting: [],\n },\n },\n },\n {\n name: \"Date field (datetime EU)\",\n payload: {\n type: \"DateField\",\n slug: \"due-date\",\n label: \"Due Date\",\n required: false,\n config: {\n defaultValue: null,\n formatOptions: {\n format: \"datetime\",\n dateFormat: \"DD/MM/YYYY\",\n showTime: true,\n },\n conditionalFormatting: [],\n },\n },\n },\n {\n name: \"Date field (datetime US)\",\n payload: {\n type: \"DateField\",\n slug: \"appointment-at\",\n label: \"Appointment\",\n required: false,\n config: {\n defaultValue: null,\n formatOptions: {\n format: \"datetime\",\n dateFormat: \"MM/DD/YYYY\",\n showTime: true,\n },\n conditionalFormatting: [],\n },\n },\n },\n ],\n },\n {\n key: \"option\",\n className: \"OptionField\",\n aliases: [\"option\", \"OptionField\"],\n description: \"Dropdown/select field with options.\",\n rawShape:\n '{\"type\":\"OptionField\",\"slug\":\"status\",\"label\":\"Status\",\"config\":{\"options\":[{\"id\":1,\"name\":\"Open\",\"color\":\"default\"},{\"id\":2,\"name\":\"Closed\",\"color\":\"success\"}]}}',\n examplePayloads: [\n {\n name: \"Option field (select dropdown)\",\n payload: {\n type: \"OptionField\",\n slug: \"priority\",\n label: \"Priority\",\n required: false,\n config: {\n options: [\n { id: 1, name: \"Low\", color: \"default\" },\n { id: 2, name: \"Medium\", color: \"warning\" },\n { id: 3, name: \"High\", color: \"cond-critico\" },\n ],\n defaultValue: 1,\n conditionalFormatting: [],\n buttonConfig: null,\n },\n },\n },\n {\n name: \"Option field (button cycle)\",\n payload: {\n type: \"OptionField\",\n slug: \"stage\",\n label: \"Stage\",\n required: false,\n config: {\n options: [\n { id: 1, name: \"To Do\", color: \"default\" },\n { id: 2, name: \"Doing\", color: \"warning\" },\n { id: 3, name: \"Done\", color: \"success\" },\n ],\n defaultValue: 1,\n conditionalFormatting: [],\n buttonConfig: {\n displayMode: \"button\",\n buttonBehavior: {\n mode: \"cycle\",\n cycleOrder: [1, 2, 3],\n requireConfirmation: false,\n lockAfterSelection: false,\n allowReselect: true,\n },\n },\n },\n },\n },\n {\n name: \"Option field (button dropdown w/ confirm)\",\n payload: {\n type: \"OptionField\",\n slug: \"status\",\n label: \"Status\",\n required: false,\n config: {\n options: [\n { id: 1, name: \"Open\", color: \"default\" },\n { id: 2, name: \"In Progress\", color: \"warning\" },\n { id: 3, name: \"Done\", color: \"success\" },\n ],\n defaultValue: 1,\n conditionalFormatting: [],\n buttonConfig: {\n displayMode: \"button\",\n buttonBehavior: {\n mode: \"dropdown\",\n requireConfirmation: true,\n confirmationMessage: \"Confirm status change\",\n useFixedLabel: true,\n buttonLabel: \"Set status\",\n allowReselect: true,\n },\n },\n },\n },\n },\n ],\n },\n {\n key: \"file\",\n className: \"FileField\",\n aliases: [\"file\", \"FileField\"],\n description: \"File attachment field.\",\n rawShape:\n '{\"type\":\"FileField\",\"slug\":\"attachment\",\"label\":\"Attachment\",\"config\":{}}',\n examplePayloads: [\n {\n name: \"File field\",\n payload: {\n type: \"FileField\",\n slug: \"attachment\",\n label: \"Attachment\",\n required: false,\n config: {},\n },\n },\n ],\n },\n {\n key: \"reference\",\n className: \"ReferenceField\",\n aliases: [\"reference\", \"ReferenceField\"],\n description: \"Reference to another schema.\",\n rawShape:\n '{\"type\":\"ReferenceField\",\"slug\":\"company-ref\",\"label\":\"Company\",\"config\":{\"targetSchema\":\"<schema-uuid>\",\"targetDisplayField\":\"<field-uuid>\"}}',\n examplePayloads: [\n {\n name: \"Reference field (minimal)\",\n payload: {\n type: \"ReferenceField\",\n slug: \"company-ref\",\n label: \"Company\",\n required: false,\n config: {\n targetSchema: \"5223cbc8-8c6c-4694-93bc-dd176364df9b\",\n targetDisplayField: \"c60b8526-5835-4c9f-aecd-9a16c7704a34\",\n },\n },\n },\n {\n name: \"Reference field (restrict + filter + description)\",\n payload: {\n type: \"ReferenceField\",\n slug: \"customer-ref\",\n label: \"Customer\",\n required: false,\n config: {\n targetSchema: \"5223cbc8-8c6c-4694-93bc-dd176364df9b\",\n targetDisplayField: \"c60b8526-5835-4c9f-aecd-9a16c7704a34\",\n deleteBehavior: \"RESTRICT\",\n defaultValue: \"CUST-12\",\n filterFields: [\n {\n fatherField: \"c60b8526-5835-4c9f-aecd-9a16c7704a34\",\n currentField: \"45c5da96-0dc2-4cc1-ba61-7660a9c6da32\",\n comparison: \"EQUAL\",\n value: null,\n },\n ],\n descriptionFields: [\n {\n id: \"c52efe3f-2825-4c60-a7e3-34dd4c1ce043\",\n fieldType: \"NumberField\",\n options: null,\n format: \"number\",\n },\n ],\n conditionalFormatting: [],\n },\n },\n },\n ],\n },\n {\n key: \"formula\",\n className: \"FormulaField\",\n aliases: [\"formula\", \"FormulaField\"],\n description: \"Calculated field from a formula.\",\n rawShape:\n '{\"type\":\"FormulaField\",\"slug\":\"formula-code\",\"label\":\"Formula Code\",\"config\":{\"formulaText\":\"concat(\\\\\"CUST-\\\\\", f1e1d000-0000-0000-0000-000000000005)\",\"uiFormatKind\":\"none\"}}',\n examplePayloads: [\n {\n name: \"Formula field (none)\",\n payload: {\n type: \"FormulaField\",\n slug: \"formula-code\",\n label: \"Formula Code\",\n required: false,\n config: {\n formulaText:\n 'concat(\"CUST-\", f1e1d000-0000-0000-0000-000000000005)',\n uiFormatKind: \"none\",\n status: \"ACTIVE\",\n conditionalFormatting: [],\n },\n },\n },\n {\n name: \"Formula field (number)\",\n payload: {\n type: \"FormulaField\",\n slug: \"formula-total\",\n label: \"Formula Total\",\n required: false,\n config: {\n formulaText: \"c52efe3f-2825-4c60-a7e3-34dd4c1ce043 * 1.21\",\n uiFormatKind: \"number\",\n status: \"ACTIVE\",\n numberFormatOptions: {\n format: \"number\",\n decimals: 2,\n thousandsSeparator: true,\n },\n conditionalFormatting: [],\n },\n },\n },\n {\n name: \"Formula field (date)\",\n payload: {\n type: \"FormulaField\",\n slug: \"formula-period\",\n label: \"Formula Period\",\n required: false,\n config: {\n formulaText:\n 'date_format(d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f90, \"AAAA-MM\")',\n uiFormatKind: \"date\",\n status: \"ACTIVE\",\n dateFormatOptions: {\n format: \"date\",\n dateFormat: \"DD/MM/YYYY\",\n showTime: false,\n },\n conditionalFormatting: [],\n },\n },\n },\n {\n name: \"Formula field (member)\",\n payload: {\n type: \"FormulaField\",\n slug: \"formula-assignee\",\n label: \"Computed Assignee\",\n required: false,\n config: {\n formulaText: \"a7b8c9d0-e1f2-3a4b-5c6d-7e8f90123456\",\n uiFormatKind: \"member\",\n status: \"ACTIVE\",\n conditionalFormatting: [],\n },\n },\n },\n ],\n },\n {\n key: \"member\",\n className: \"MemberField\",\n aliases: [\"member\", \"MemberField\"],\n description: \"Workspace member field.\",\n rawShape:\n '{\"type\":\"MemberField\",\"slug\":\"owner\",\"label\":\"Owner\",\"config\":{\"defaultValue\":null}}',\n examplePayloads: [\n {\n name: \"Member field\",\n payload: {\n type: \"MemberField\",\n slug: \"owner\",\n label: \"Owner\",\n required: false,\n config: {\n defaultValue: null,\n conditionalFormatting: [],\n },\n },\n },\n ],\n },\n {\n key: \"autoincremental\",\n className: \"AutoIncrementalField\",\n aliases: [\n \"autoincremental\",\n \"auto-incremental\",\n \"auto_incremental\",\n \"AutoIncrementalField\",\n ],\n description: \"Auto-generated incremental counter.\",\n rawShape:\n '{\"type\":\"AutoIncrementalField\",\"slug\":\"order-number\",\"label\":\"Order Number\",\"config\":{\"segmentedByFieldId\":null}}',\n examplePayloads: [\n {\n name: \"Autoincremental (global counter)\",\n payload: {\n type: \"AutoIncrementalField\",\n slug: \"order-number\",\n label: \"Order Number\",\n required: false,\n config: {\n segmentedByFieldId: null,\n conditionalFormatting: [],\n },\n },\n },\n {\n name: \"Autoincremental (segmented)\",\n payload: {\n type: \"AutoIncrementalField\",\n slug: \"sequence-code\",\n label: \"Sequence Code\",\n required: false,\n config: {\n segmentedByFieldId: \"45c5da96-0dc2-4cc1-ba61-7660a9c6da32\",\n conditionalFormatting: [],\n },\n },\n },\n ],\n },\n {\n key: \"schedule\",\n className: \"ScheduleField\",\n aliases: [\"schedule\", \"ScheduleField\"],\n description:\n \"Recurrence/schedule field bound to a number reference and a date period (frequency: monthly or daily).\",\n rawShape:\n '{\"type\":\"ScheduleField\",\"slug\":\"recurrence\",\"label\":\"Recurrence\",\"config\":{\"referenceField\":\"<number-field-uuid>\",\"beginningPeriodField\":\"<date-field-uuid>\",\"endingPeriodField\":\"<date-field-uuid>\",\"frequency\":\"monthly\"}}',\n examplePayloads: [\n {\n name: \"Schedule field (monthly)\",\n payload: {\n type: \"ScheduleField\",\n slug: \"monthly-recurrence\",\n label: \"Monthly Recurrence\",\n required: false,\n config: {\n referenceField: \"c52efe3f-2825-4c60-a7e3-34dd4c1ce043\",\n beginningPeriodField: \"d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f90\",\n endingPeriodField: \"d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f90\",\n frequency: \"monthly\",\n },\n },\n },\n {\n name: \"Schedule field (daily)\",\n payload: {\n type: \"ScheduleField\",\n slug: \"daily-recurrence\",\n label: \"Daily Recurrence\",\n required: false,\n config: {\n referenceField: \"c52efe3f-2825-4c60-a7e3-34dd4c1ce043\",\n beginningPeriodField: \"d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f90\",\n endingPeriodField: \"d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f90\",\n frequency: \"daily\",\n },\n },\n },\n ],\n },\n] as const satisfies readonly SchemaFieldTypeDefinition[];\n\nconst fieldTypeDefinitionByAlias = new Map(\n fieldTypeDefinitions.flatMap((definition) =>\n definition.aliases.map((alias) => [alias.trim().toLowerCase(), definition] as const),\n ),\n);\n\nconst fieldTypeDefinitionByClassName = new Map<string, SchemaFieldTypeDefinition>(\n fieldTypeDefinitions.map((definition) => [definition.className, definition] as const),\n);\n\nconst optionValidationMessage =\n 'Option fields require an \"options\" array with at least one entry like {\"id\":1,\"name\":\"Open\",\"color\":\"default\"}.';\n\n// Mirrors the frontend OptionColorId palette; the UI rejects any other value.\nexport const OPTION_COLORS = [\n \"none\",\n \"default\",\n \"secondary\",\n \"success\",\n \"warning\",\n \"cond-verde-intenso\",\n \"cond-positivo\",\n \"cond-naranja\",\n \"cond-destacado\",\n \"cond-negativo\",\n \"cond-critico\",\n \"cond-morado\",\n \"cond-bajo\",\n \"cond-azul-intenso\",\n \"cond-vacio\",\n \"cond-gris-oscuro\",\n \"cond-rosa\",\n \"cond-morado-medio\",\n \"cond-azul-medio\",\n \"cond-amarillo-claro\",\n \"cond-amarillo-oscuro\",\n \"cond-naranja-medio\",\n] as const;\n\nconst optionColorSet = new Set<string>(OPTION_COLORS);\n\nexport function getSchemaFieldTypeDefinitions(): readonly SchemaFieldTypeDefinition[] {\n return fieldTypeDefinitions;\n}\n\nexport function listSchemaFieldTypes(): readonly SchemaFieldTypeKey[] {\n return fieldTypeDefinitions.map((definition) => definition.key);\n}\n\nexport function formatSchemaFieldTypes(): string {\n return listSchemaFieldTypes().join(\", \");\n}\n\nexport function resolveSchemaFieldType(\n input: string | undefined,\n): SchemaFieldTypeDefinition | undefined {\n if (!input) {\n return undefined;\n }\n\n return fieldTypeDefinitionByAlias.get(input.trim().toLowerCase());\n}\n\nexport function resolveSchemaFieldTypeByClassName(\n className: string | undefined,\n): SchemaFieldTypeDefinition | undefined {\n if (!className) {\n return undefined;\n }\n\n return fieldTypeDefinitionByClassName.get(className);\n}\n\nexport function normalizeSchemaFieldType(input: string): string {\n const definition = resolveSchemaFieldType(input);\n\n if (definition) {\n return definition.className;\n }\n\n if (/^[a-z]/.test(input) && !input.endsWith(\"Field\")) {\n return `${input.charAt(0).toUpperCase()}${input.slice(1)}Field`;\n }\n\n return input;\n}\n\nexport function assertSupportedSchemaFieldType(type: string): void {\n if (!resolveSchemaFieldTypeByClassName(type)) {\n throw new CliError(\n \"invalid_cli_usage\",\n `Unsupported field type \"${type}\". Valid types: ${formatSchemaFieldTypes()}.`,\n );\n }\n}\n\ninterface OptionEntry {\n [key: string]: string | number;\n id: number;\n name: string;\n color: string;\n}\n\nfunction normalizeOptionEntries(entries: readonly unknown[]): OptionEntry[] {\n const namesById = new Map<number, string>();\n const seenNames = new Set<string>();\n\n return entries.map((entry, index) => {\n if (!isJsonObject(entry)) {\n throw new CliError(\n \"invalid_cli_usage\",\n `Option ${index + 1} must be an object like {\"id\":1,\"name\":\"Open\",\"color\":\"default\"}.`,\n );\n }\n\n const name = toStringValue(entry.name) ?? toStringValue(entry.label);\n const color = toStringValue(entry.color) ?? \"default\";\n\n if (!name) {\n throw new CliError(\n \"invalid_cli_usage\",\n `Option ${index + 1} requires a non-empty \"name\".`,\n );\n }\n\n if (entry.id === undefined || entry.id === null) {\n throw new CliError(\n \"invalid_cli_usage\",\n `Option \"${name}\" requires a numeric \"id\" (unique integer >= 0), e.g. {\"id\":1,\"name\":\"Open\",\"color\":\"default\"}.`,\n );\n }\n\n const id = toNumberValue(entry.id);\n\n if (id === undefined || !Number.isInteger(id) || id < 0) {\n throw new CliError(\n \"invalid_cli_usage\",\n `Invalid option id ${JSON.stringify(entry.id)} for option \"${name}\". Option ids must be integers >= 0.`,\n );\n }\n\n const optionWithSameId = namesById.get(id);\n if (optionWithSameId !== undefined) {\n throw new CliError(\n \"invalid_cli_usage\",\n `Duplicate option id ${id} for options \"${optionWithSameId}\" and \"${name}\". Option ids must be unique.`,\n );\n }\n\n const nameKey = name.trim().toLowerCase();\n if (seenNames.has(nameKey)) {\n throw new CliError(\n \"invalid_cli_usage\",\n `Duplicate option name \"${name}\". Option names must be unique (case-insensitive).`,\n );\n }\n\n if (!optionColorSet.has(color)) {\n throw new CliError(\n \"invalid_cli_usage\",\n `Invalid option color \"${color}\" for option \"${name}\". Valid colors: ${OPTION_COLORS.join(\", \")}.`,\n );\n }\n\n namesById.set(id, name);\n seenNames.add(nameKey);\n return { id, name, color };\n });\n}\n\nfunction hasOptionEntries(input: JsonObject): boolean {\n return [\n input.options,\n toJsonObject(input.config)?.options,\n toJsonObject(input.additionalProperties)?.options,\n ].some((options) => options !== undefined);\n}\n\nfunction normalizeOptionPayload(input: JsonObject): JsonObject {\n const additionalProperties = toJsonObject(input.additionalProperties) ?? {};\n const config = toJsonObject(input.config);\n const rootOptions = Array.isArray(input.options) ? input.options : undefined;\n const nestedOptions = Array.isArray(additionalProperties.options)\n ? additionalProperties.options\n : Array.isArray(config?.options)\n ? config.options\n : undefined;\n const optionObjects = normalizeOptionEntries(\n nestedOptions ??\n (Array.isArray(rootOptions) ? rootOptions : []),\n );\n\n if (optionObjects.length === 0) {\n throw new CliError(\"invalid_cli_usage\", optionValidationMessage);\n }\n\n const { options: _options, additionalProperties: _additionalProperties, ...rest } = input;\n const defaultValue =\n config?.defaultValue ?? input.defaultValue ?? additionalProperties.defaultValue;\n const conditionalFormatting =\n config?.conditionalFormatting ?? additionalProperties.conditionalFormatting;\n const buttonConfig = config?.buttonConfig ?? additionalProperties.buttonConfig;\n\n return {\n ...rest,\n config: {\n ...(config ?? {}),\n options: optionObjects,\n ...(defaultValue !== undefined ? { defaultValue } : {}),\n ...(conditionalFormatting !== undefined ? { conditionalFormatting } : {}),\n ...(buttonConfig !== undefined ? { buttonConfig } : {}),\n },\n };\n}\n\nfunction normalizeReferencePayload(input: JsonObject): JsonObject {\n const additionalProperties = toJsonObject(input.additionalProperties) ?? {};\n const config = toJsonObject(input.config) ?? {};\n const targetSchema =\n config.targetSchema ?? input.targetSchema ?? additionalProperties.targetSchema;\n const targetDisplayField =\n config.targetDisplayField ??\n input.targetDisplayField ??\n additionalProperties.targetDisplayField;\n const deleteBehavior =\n config.deleteBehavior ?? input.deleteBehavior ?? additionalProperties.deleteBehavior;\n const defaultValue =\n config.defaultValue ?? input.defaultValue ?? additionalProperties.defaultValue;\n const filterFields =\n config.filterFields ?? input.filterFields ?? additionalProperties.filterFields;\n const descriptionFields =\n config.descriptionFields ??\n input.descriptionFields ??\n additionalProperties.descriptionFields;\n const conditionalFormatting =\n config.conditionalFormatting ??\n input.conditionalFormatting ??\n additionalProperties.conditionalFormatting;\n\n const normalized: JsonObject = {\n ...input,\n };\n\n normalized.config = {\n ...config,\n ...(targetSchema !== undefined ? { targetSchema } : {}),\n ...(targetDisplayField !== undefined ? { targetDisplayField } : {}),\n ...(deleteBehavior !== undefined ? { deleteBehavior } : {}),\n ...(defaultValue !== undefined ? { defaultValue } : {}),\n ...(filterFields !== undefined ? { filterFields } : {}),\n ...(descriptionFields !== undefined ? { descriptionFields } : {}),\n ...(conditionalFormatting !== undefined ? { conditionalFormatting } : {}),\n };\n\n const normalizedConfig = toJsonObject(normalized.config) ?? {};\n\n if (\n !toStringValue(normalizedConfig.targetSchema) ||\n !toStringValue(normalizedConfig.targetDisplayField)\n ) {\n const definition = resolveSchemaFieldType(\"reference\")!;\n throw new CliError(\n \"invalid_cli_usage\",\n `Reference fields require \"targetSchema\" and \"targetDisplayField\". Expected raw shape: ${definition.rawShape}`,\n );\n }\n\n return normalized;\n}\n\nconst scheduleAllowedFrequencies = new Set([\"monthly\", \"daily\"]);\n\nfunction normalizeSchedulePayload(input: JsonObject): JsonObject {\n const additionalProperties = toJsonObject(input.additionalProperties) ?? {};\n const config = toJsonObject(input.config) ?? {};\n const referenceField =\n config.referenceField ?? input.referenceField ?? additionalProperties.referenceField;\n const beginningPeriodField =\n config.beginningPeriodField ??\n input.beginningPeriodField ??\n additionalProperties.beginningPeriodField;\n const endingPeriodField =\n config.endingPeriodField ??\n input.endingPeriodField ??\n additionalProperties.endingPeriodField;\n const frequency =\n config.frequency ?? input.frequency ?? additionalProperties.frequency;\n\n const {\n referenceField: _referenceField,\n beginningPeriodField: _beginningPeriodField,\n endingPeriodField: _endingPeriodField,\n frequency: _frequency,\n additionalProperties: _additionalProperties,\n ...rest\n } = input;\n\n const normalized: JsonObject = {\n ...rest,\n config: {\n ...config,\n ...(referenceField !== undefined ? { referenceField } : {}),\n ...(beginningPeriodField !== undefined ? { beginningPeriodField } : {}),\n ...(endingPeriodField !== undefined ? { endingPeriodField } : {}),\n ...(frequency !== undefined ? { frequency } : {}),\n },\n };\n\n const normalizedConfig = toJsonObject(normalized.config) ?? {};\n const definition = resolveSchemaFieldType(\"schedule\")!;\n\n if (\n !toStringValue(normalizedConfig.referenceField) ||\n !toStringValue(normalizedConfig.beginningPeriodField) ||\n !toStringValue(normalizedConfig.endingPeriodField) ||\n !toStringValue(normalizedConfig.frequency)\n ) {\n throw new CliError(\n \"invalid_cli_usage\",\n `Schedule fields require \"referenceField\", \"beginningPeriodField\", \"endingPeriodField\" and \"frequency\". Expected raw shape: ${definition.rawShape}`,\n );\n }\n\n const frequencyValue = toStringValue(normalizedConfig.frequency)!;\n if (!scheduleAllowedFrequencies.has(frequencyValue)) {\n throw new CliError(\n \"invalid_cli_usage\",\n `Schedule \"frequency\" must be \"monthly\" or \"daily\" (received \"${frequencyValue}\").`,\n );\n }\n\n return normalized;\n}\n\nfunction normalizeFormulaPayload(input: JsonObject): JsonObject {\n const { status: _status, ...rest } = input;\n const rawAdditionalProperties = toJsonObject(input.additionalProperties);\n const rawConfig = toJsonObject(input.config);\n const { status: _additionalStatus, ...additionalProperties } =\n rawAdditionalProperties ?? {};\n const { status: _configStatus, ...config } = rawConfig ?? {};\n const formulaText =\n config.formulaText ??\n rest.formulaText ??\n rest.expression ??\n additionalProperties.formulaText ??\n additionalProperties.expression;\n\n const normalized: JsonObject = {\n ...rest,\n };\n\n normalized.config = {\n ...config,\n ...(formulaText !== undefined ? { formulaText } : {}),\n ...(config.uiFormatKind !== undefined ? { uiFormatKind: config.uiFormatKind } : {}),\n ...(config.defaultValue !== undefined ? { defaultValue: config.defaultValue } : {}),\n ...(config.numberFormatOptions !== undefined\n ? { numberFormatOptions: config.numberFormatOptions }\n : {}),\n ...(config.dateFormatOptions !== undefined\n ? { dateFormatOptions: config.dateFormatOptions }\n : {}),\n ...(config.conditionalFormatting !== undefined\n ? { conditionalFormatting: config.conditionalFormatting }\n : {}),\n };\n\n const normalizedConfig = toJsonObject(normalized.config) ?? {};\n\n if (!toStringValue(normalizedConfig.formulaText)) {\n const definition = resolveSchemaFieldType(\"formula\")!;\n throw new CliError(\n \"invalid_cli_usage\",\n `Formula fields require \"formulaText\". Expected raw shape: ${definition.rawShape}`,\n );\n }\n\n return normalized;\n}\n\nexport function normalizeSchemaFieldCreatePayload(input: JsonObject): JsonObject {\n const rawType = toStringValue(input.type);\n const normalizedType = rawType ? normalizeSchemaFieldType(rawType) : undefined;\n const definition = resolveSchemaFieldTypeByClassName(normalizedType);\n\n if (!definition) {\n return input;\n }\n\n const normalizedWithType: JsonObject = {\n ...input,\n type: definition.className,\n };\n\n switch (definition.key) {\n case \"option\":\n return normalizeOptionPayload(normalizedWithType);\n case \"reference\":\n return normalizeReferencePayload(normalizedWithType);\n case \"formula\":\n return normalizeFormulaPayload(normalizedWithType);\n case \"schedule\":\n return normalizeSchedulePayload(normalizedWithType);\n case \"autoincremental\": {\n const config = toJsonObject(normalizedWithType.config) ?? {};\n const segmentedByFieldId =\n config.segmentedByFieldId ??\n normalizedWithType.segmentedByFieldId ??\n null;\n return {\n ...normalizedWithType,\n config: {\n ...config,\n segmentedByFieldId,\n ...(config.conditionalFormatting !== undefined\n ? { conditionalFormatting: config.conditionalFormatting }\n : {}),\n },\n };\n }\n default:\n return normalizedWithType;\n }\n}\n\nexport function normalizeSchemaFieldUpdatePayload(\n type: string,\n input: JsonObject,\n): JsonObject {\n const definition = resolveSchemaFieldTypeByClassName(type);\n\n if (definition?.key === \"formula\") {\n return normalizeFormulaPayload(input);\n }\n\n // A patch replaces the whole option list, so validate it like a create when it is sent.\n if (definition?.key === \"option\" && hasOptionEntries(input)) {\n return normalizeOptionPayload(input);\n }\n\n return input;\n}\n\nexport function buildSchemaFieldCreateHelpText(): string {\n const sections = fieldTypeDefinitions.map(\n (definition) =>\n ` - ${definition.key}: ${definition.description}\\n raw: ${definition.rawShape}`,\n );\n\n return [\n \"\",\n \"Valid field types:\",\n ` ${formatSchemaFieldTypes()}`,\n \"\",\n \"Raw payload shapes by type:\",\n ...sections,\n \"\",\n 'Use \"zinkee --example schemas fields create --type <type>\" to show a concrete example for one type.',\n ].join(\"\\n\");\n}\n\nexport function buildSchemaFieldCreateValidationMessage(type: string): string {\n const definition = resolveSchemaFieldTypeByClassName(type);\n\n if (!definition) {\n return `Invalid payload for field type \"${type}\". Valid types: ${formatSchemaFieldTypes()}.`;\n }\n\n return `Invalid payload for field type \"${definition.key}\". Expected raw shape: ${definition.rawShape}`;\n}\n"],"mappings":";AAAA,SAAS,qBAAqB;AAQ9B,IAAMA,WAAU,cAAc,YAAY,GAAG;AAM7C,SAAS,mBAAmB,OAAwB;AAClD,MAAI,UAAU,QAAQ,UAAU,QAAW;AACzC,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,UAAU,YAAY,OAAO,UAAU,aAAa,OAAO,UAAU,UAAU;AACxF,WAAO,OAAO,KAAK;AAAA,EACrB;AAEA,SAAO,KAAK,UAAU,K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BAAsB,IACtD,CAAC;AAAA,QACP;AAAA,MACF;AAAA,IACF;AAAA,IACA;AACE,aAAO;AAAA,EACX;AACF;AAEO,SAAS,kCACd,MACA,OACY;AACZ,QAAM,aAAa,kCAAkC,IAAI;AAEzD,MAAI,YAAY,QAAQ,WAAW;AACjC,WAAO,wBAAwB,KAAK;AAAA,EACtC;AAGA,MAAI,YAAY,QAAQ,YAAY,iBAAiB,KAAK,GAAG;AAC3D,WAAO,uBAAuB,KAAK;AAAA,EACrC;AAEA,SAAO;AACT;AAEO,SAAS,iCAAyC;AACvD,QAAM,WAAW,qBAAqB;AAAA,IACpC,CAAC,eACC,OAAO,WAAW,GAAG,KAAK,WAAW,WAAW;AAAA,WAAc,WAAW,QAAQ;AAAA,EACrF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,KAAK,uBAAuB,CAAC;AAAA,IAC7B;AAAA,IACA;AAAA,IACA,GAAG;AAAA,IACH;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;AAEO,SAAS,wCAAwC,MAAsB;AAC5E,QAAM,aAAa,kCAAkC,IAAI;AAEzD,MAAI,CAAC,YAAY;AACf,WAAO,mCAAmC,IAAI,mBAAmB,uBAAuB,CAAC;AAAA,EAC3F;AAEA,SAAO,mCAAmC,WAAW,GAAG,0BAA0B,WAAW,QAAQ;AACvG;","names":["require","createRequire","require"]}
@@ -2,7 +2,7 @@ import {
2
2
  buildJsonSuccess,
3
3
  getSchemaFieldTypeDefinitions,
4
4
  resolveSchemaFieldType
5
- } from "./chunk-DCC56F2L.js";
5
+ } from "./chunk-SVBC47AD.js";
6
6
 
7
7
  // src/utils/examples.ts
8
8
  var SAMPLE_UUID = "550e8400-e29b-41d4-a716-446655440001";
@@ -473,13 +473,43 @@ var specificExamples = {
473
473
  }`
474
474
  },
475
475
  {
476
- description: "Declare an expected DNI/NIE format (warnings never block record saves). Omit expectedFormat to keep it; use kind none to disable it.",
476
+ description: "Declare an expected DNI/NIE format on a text field: the web shows an amber warning on values that do not fit; warnings never block record saves. kind is none, length, dniNie, cif, email or iban. Omit expectedFormat to keep it; use kind none to disable it.",
477
477
  command: `zinkee --json schemas fields update contacts tax-id --raw '{"type":"TextField","config":{"expectedFormat":{"kind":"dniNie"}}}'`,
478
478
  raw: `{
479
479
  "type": "TextField",
480
480
  "config": {
481
481
  "expectedFormat": { "kind": "dniNie" }
482
482
  }
483
+ }`
484
+ },
485
+ {
486
+ description: "Warn when a company tax id is not a valid CIF (the control digit is checked). Use email for addresses and iban for bank accounts the same way.",
487
+ command: `zinkee --json schemas fields update customers nif --raw '{"type":"TextField","config":{"expectedFormat":{"kind":"cif"}}}'`,
488
+ raw: `{
489
+ "type": "TextField",
490
+ "config": {
491
+ "expectedFormat": { "kind": "cif" }
492
+ }
493
+ }`
494
+ },
495
+ {
496
+ description: "Warn on a length: mode exact (min), min (min), max (max) or between (min and max); bounds are whole numbers from 1 to 200, or 2000 for LONG text, and min cannot exceed max. Only length takes mode, min and max.",
497
+ command: `zinkee --json schemas fields update products sku --raw '{"type":"TextField","config":{"expectedFormat":{"kind":"length","mode":"between","min":8,"max":12}}}'`,
498
+ raw: `{
499
+ "type": "TextField",
500
+ "config": {
501
+ "expectedFormat": { "kind": "length", "mode": "between", "min": 8, "max": 12 }
502
+ }
503
+ }`
504
+ },
505
+ {
506
+ description: "Stop warning: set the expected format back to none.",
507
+ command: `zinkee --json schemas fields update customers nif --raw '{"type":"TextField","config":{"expectedFormat":{"kind":"none"}}}'`,
508
+ raw: `{
509
+ "type": "TextField",
510
+ "config": {
511
+ "expectedFormat": { "kind": "none" }
512
+ }
483
513
  }`
484
514
  },
485
515
  {
@@ -4142,6 +4172,29 @@ var specificExamples = {
4142
4172
  "config": {
4143
4173
  "webhookEndpointId": "b3cb4283-97ab-4d94-9e6f-82d0ee5cee24"
4144
4174
  }
4175
+ }`
4176
+ },
4177
+ {
4178
+ description: "Replace the trigger with a record-changed trigger that runs when a due date is changed to 30 days ago or earlier. --condition-today writes \xABHoy \u2212 30 d\xEDas\xBB in the workspace time zone. A record-changed trigger only checks it when the record changes; for a reminder that fires every day, use a scheduled trigger and a search_records action with the same condition.",
4179
+ command: "zinkee --json automations trigger set automation-1 --trigger-type record_changed --trigger-schema invoices --trigger-field due-date --condition-today due-date:le:-30",
4180
+ raw: `{
4181
+ "type": "record_changed",
4182
+ "config": {
4183
+ "schemaId": "invoices",
4184
+ "fieldIds": ["due-date"],
4185
+ "conditions": [
4186
+ {
4187
+ "field": "due-date",
4188
+ "comparator": "le",
4189
+ "values": [
4190
+ {
4191
+ "rawValue": "{\\"type\\":\\"today\\",\\"offset\\":-30,\\"ianaTimeZone\\":\\"Europe/Madrid\\"}",
4192
+ "source": null
4193
+ }
4194
+ ]
4195
+ }
4196
+ ]
4197
+ }
4145
4198
  }`
4146
4199
  }
4147
4200
  ],
@@ -4310,7 +4363,7 @@ var specificExamples = {
4310
4363
  }`
4311
4364
  },
4312
4365
  {
4313
- description: "Add a send-message action. --to maps to fieldMapping.recipients and --message maps to fieldMapping.body. Values are wrapped in {rawValue, source} like every other automation field mapping; use --map / --map-json for extra keys.",
4366
+ description: "Add a send-message action: an in-app notification to workspace members, not an email (use send_email for email). --to maps to fieldMapping.recipients and --message maps to fieldMapping.body. Values are wrapped in {rawValue, source} like every other automation field mapping; use --map / --map-json for extra keys.",
4314
4367
  command: `zinkee --json automations actions add automation-1 --type send_message --name "Notify customer" --to customer@example.com --subject "Your order status has changed" --message "Hello, your order is now processed."`,
4315
4368
  raw: `{
4316
4369
  "type": "send_message",
@@ -4331,6 +4384,78 @@ var specificExamples = {
4331
4384
  }
4332
4385
  }
4333
4386
  }
4387
+ }`
4388
+ },
4389
+ {
4390
+ description: "Add a send-email action with the typed flags. --to, --cc and --bcc repeat; each value is a fixed address or ${key}, a placeholder declared in config.variables that takes the address from a field. An email can go only in copy (no --to). --connection must be an active, verified SMTP connection (automations connections list); the CLI cannot verify one, so create and verify it in the web (Configuraci\xF3n \u2192 Integraciones).",
4391
+ command: 'zinkee --json automations actions add automation-1 --type send_email --name "Notify operations" --connection 4fc20b5c-9353-4991-b68e-1027cb674ed4 --cc operations@example.com --subject "New project" --message "<p>A project was created.</p>"',
4392
+ raw: `{
4393
+ "type": "send_email",
4394
+ "name": "Notify operations",
4395
+ "config": {
4396
+ "connectionId": "4fc20b5c-9353-4991-b68e-1027cb674ed4",
4397
+ "cc": ["operations@example.com"],
4398
+ "subject": "New project",
4399
+ "body": "<p>A project was created.</p>"
4400
+ }
4401
+ }`
4402
+ },
4403
+ {
4404
+ description: "Add a send-email action whose recipient and attachment come from the triggering record, sent even when the file field is empty (skipIfEmpty). variables map each ${key} to a field: sourceType trigger_field (the triggering record) or previous_action with its actionId (a search_records result), in lower case unlike fieldMapping sources. Without skipIfEmpty an empty file field makes the send fail; a file that cannot be downloaded always does. Pass variables and attachments with --raw-file; typed flags such as --subject override the file.",
4405
+ command: "zinkee --json automations actions add automation-1 --raw-file email-action.json",
4406
+ raw: `{
4407
+ "type": "send_email",
4408
+ "name": "Email the project manager",
4409
+ "config": {
4410
+ "connectionId": "4fc20b5c-9353-4991-b68e-1027cb674ed4",
4411
+ "to": ["\${manager_email}"],
4412
+ "cc": [],
4413
+ "bcc": [],
4414
+ "replyTo": "operations@example.com",
4415
+ "subject": "Project \${project_name} is in production",
4416
+ "body": "<p>Hello, project \${project_name} is now in production.</p>",
4417
+ "variables": {
4418
+ "manager_email": {
4419
+ "sourceType": "trigger_field",
4420
+ "fieldId": "34250412-f016-44c0-9f88-37dd1ddb4b13"
4421
+ },
4422
+ "project_name": {
4423
+ "sourceType": "trigger_field",
4424
+ "fieldId": "4dd04e57-2a01-4c49-8728-9cb288bffb8d"
4425
+ }
4426
+ },
4427
+ "attachments": [
4428
+ {
4429
+ "sourceType": "trigger_field",
4430
+ "fieldId": "c8edbde8-a361-4e9f-a39a-2e88971f21a7",
4431
+ "name": "Signed contract",
4432
+ "skipIfEmpty": true
4433
+ }
4434
+ ]
4435
+ }
4436
+ }`
4437
+ },
4438
+ {
4439
+ description: "Add a search-records action that finds invoices due in 5 days. --condition-today field:comparator[:\xB1N] writes \xABHoy + N d\xEDas\xBB in the workspace time zone (comparators eq, ne, gt, ge, lt, le; eq matches the whole day). Table and field accept slugs. Pair it with a scheduled trigger for a daily reminder. The equivalent --condition-json carries the same JSON text as a string value; --condition cannot, because it splits values on commas.",
4440
+ command: 'zinkee --json automations actions add automation-1 --type search_records --name "Invoices due in 5 days" --target-schema invoices --condition-today due-date:eq:+5',
4441
+ raw: `{
4442
+ "type": "search_records",
4443
+ "name": "Invoices due in 5 days",
4444
+ "config": {
4445
+ "targetSchemaId": "invoices",
4446
+ "conditions": [
4447
+ {
4448
+ "field": "due-date",
4449
+ "comparator": "eq",
4450
+ "values": [
4451
+ {
4452
+ "rawValue": "{\\"type\\":\\"today\\",\\"offset\\":5,\\"ianaTimeZone\\":\\"Europe/Madrid\\"}",
4453
+ "source": null
4454
+ }
4455
+ ]
4456
+ }
4457
+ ]
4458
+ }
4334
4459
  }`
4335
4460
  },
4336
4461
  {
@@ -4582,12 +4707,13 @@ var specificExamples = {
4582
4707
  ],
4583
4708
  "document-templates list": [
4584
4709
  {
4585
- description: "List every document template in the workspace. Each asset's link is a relative path to the asset download endpoint, ready to call without composition.",
4710
+ description: "List every document template in the workspace. Each asset's link is a relative path to the asset download endpoint, ready to call without composition. fileNamePattern is the generated file name of the template, or null when generated PDFs are named after the template. The table output shows it as a column.",
4586
4711
  command: "zinkee --json document-templates list",
4587
4712
  response: `[
4588
4713
  {
4589
4714
  "id": "7c4a8d3f-1b2e-4a5c-9d6e-1f2a3b4c5d6e",
4590
4715
  "name": "Quarterly report",
4716
+ "fileNamePattern": "Budget {{ record.number }} - {{ record.client }}",
4591
4717
  "assets": [
4592
4718
  {
4593
4719
  "id": "9e8d7c6b-5a4f-3e2d-1c0b-9a8b7c6d5e4f",
@@ -4610,6 +4736,7 @@ var specificExamples = {
4610
4736
  response: `{
4611
4737
  "id": "7c4a8d3f-1b2e-4a5c-9d6e-1f2a3b4c5d6e",
4612
4738
  "name": "Quarterly report",
4739
+ "fileNamePattern": "Budget {{ record.number }} - {{ record.client }}",
4613
4740
  "assets": [
4614
4741
  {
4615
4742
  "id": "9e8d7c6b-5a4f-3e2d-1c0b-9a8b7c6d5e4f",
@@ -4639,6 +4766,26 @@ var specificExamples = {
4639
4766
  response: `{
4640
4767
  "id": "7c4a8d3f-1b2e-4a5c-9d6e-1f2a3b4c5d6e",
4641
4768
  "name": "Quarterly report",
4769
+ "fileNamePattern": null,
4770
+ "assets": [],
4771
+ "createdAt": "2026-01-15T10:00:00Z",
4772
+ "updatedAt": "2026-01-15T10:00:00Z",
4773
+ "createdBy": "creator@example.com",
4774
+ "updatedBy": "creator@example.com"
4775
+ }`
4776
+ },
4777
+ {
4778
+ description: `Create a template whose generated PDFs are named from record data. The pattern is text plus variables written like in index.html, always rooted at record ({{ record.field }}, {{ record['field-slug'] }}, {{ record.clients.name }} for a related table); loops, conditions, filters and functions are rejected. Each PDF is named <resolved name>-vN.pdf, e.g. "Budget P-2026-0143 - Smith Hardware-v1.pdf". Fields are only checked when a document is generated: if one cannot be resolved, the PDF is named after the template and the automation history shows a DOCUMENT_FILE_NAME_FALLBACK warning.`,
4779
+ command: 'zinkee --json document-templates create --name "Budget" --file-name-pattern "Budget {{ record.number }} - {{ record.client }}"',
4780
+ raw: `{
4781
+ "name": "Budget",
4782
+ "fileNamePattern": "Budget {{ record.number }} - {{ record.client }}",
4783
+ "assets": []
4784
+ }`,
4785
+ response: `{
4786
+ "id": "7c4a8d3f-1b2e-4a5c-9d6e-1f2a3b4c5d6e",
4787
+ "name": "Budget",
4788
+ "fileNamePattern": "Budget {{ record.number }} - {{ record.client }}",
4642
4789
  "assets": [],
4643
4790
  "createdAt": "2026-01-15T10:00:00Z",
4644
4791
  "updatedAt": "2026-01-15T10:00:00Z",
@@ -4668,7 +4815,7 @@ var specificExamples = {
4668
4815
  ],
4669
4816
  "document-templates update": [
4670
4817
  {
4671
- description: "Rename a template. The template argument accepts a UUID or an exact current name. Only the name is updatable through this endpoint; assets are managed via the assets subcommands.",
4818
+ description: "Rename a template. The template argument accepts a UUID or an exact current name. A field that is not sent keeps its value, so renaming keeps the generated file name. Assets are managed via the assets subcommands.",
4672
4819
  command: 'zinkee --json document-templates update "Quarterly report" --name "Annual report"',
4673
4820
  raw: `{
4674
4821
  "name": "Annual report"
@@ -4676,6 +4823,7 @@ var specificExamples = {
4676
4823
  response: `{
4677
4824
  "id": "7c4a8d3f-1b2e-4a5c-9d6e-1f2a3b4c5d6e",
4678
4825
  "name": "Annual report",
4826
+ "fileNamePattern": "Budget {{ record.number }} - {{ record.client }}",
4679
4827
  "assets": [
4680
4828
  {
4681
4829
  "id": "9e8d7c6b-5a4f-3e2d-1c0b-9a8b7c6d5e4f",
@@ -4687,6 +4835,20 @@ var specificExamples = {
4687
4835
  "updatedAt": "2026-01-22T09:15:00Z",
4688
4836
  "createdBy": "creator@example.com",
4689
4837
  "updatedBy": "updater@example.com"
4838
+ }`
4839
+ },
4840
+ {
4841
+ description: "Set or change only the generated file name; the template name stays. Variables are always rooted at record; use the bracket form for slugs with hyphens and keep the whole pattern in double quotes in the shell. The API returns 400 with document_template_file_name_pattern_invalid, _unsupported, _root_mismatch, _root_hyphen, _no_variables or _too_long (500 characters) and quotes the variable that fails.",
4842
+ command: `zinkee --json document-templates update "Budget" --file-name-pattern "Budget {{ record['budget-number'] }} - {{ record.client }}"`,
4843
+ raw: `{
4844
+ "fileNamePattern": "Budget {{ record['budget-number'] }} - {{ record.client }}"
4845
+ }`
4846
+ },
4847
+ {
4848
+ description: "Remove the generated file name: generated PDFs are named after the template again (<template name>-vN.pdf). Sends fileNamePattern: null.",
4849
+ command: 'zinkee --json document-templates update "Budget" --clear-file-name-pattern',
4850
+ raw: `{
4851
+ "fileNamePattern": null
4690
4852
  }`
4691
4853
  }
4692
4854
  ],
@@ -4707,6 +4869,7 @@ var specificExamples = {
4707
4869
  response: `{
4708
4870
  "id": "7c4a8d3f-1b2e-4a5c-9d6e-1f2a3b4c5d6e",
4709
4871
  "name": "Quarterly report",
4872
+ "fileNamePattern": "Budget {{ record.number }} - {{ record.client }}",
4710
4873
  "assets": [
4711
4874
  {
4712
4875
  "id": "9e8d7c6b-5a4f-3e2d-1c0b-9a8b7c6d5e4f",
@@ -4812,4 +4975,4 @@ function withResponseEnvelope({ responseMeta, ...example }, commandName) {
4812
4975
  export {
4813
4976
  getCommandExamples
4814
4977
  };
4815
- //# sourceMappingURL=examples-BTITPK7X.js.map
4978
+ //# sourceMappingURL=examples-MT6FVPAD.js.map